-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_version_manager.py
More file actions
477 lines (401 loc) · 15.1 KB
/
model_version_manager.py
File metadata and controls
477 lines (401 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
"""
ML Model Version Manager
Handles model versioning, A/B testing, and rollback capabilities
"""
import json
import boto3
import pickle
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List, Tuple
from dataclasses import dataclass, asdict
import hashlib
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@dataclass
class ModelMetadata:
"""Model metadata structure"""
model_name: str
version: str
s3_path: str
created_at: str
metrics: Dict[str, float]
status: str # 'active', 'testing', 'deprecated', 'archived'
traffic_percentage: float # For A/B testing
checksum: str
description: str = ""
class ModelVersionManager:
"""
Manages ML model versions with A/B testing and rollback support
"""
def __init__(self, s3_bucket: str, dynamodb_table: str, region: str = 'us-east-1'):
"""
Initialize model version manager
Args:
s3_bucket: S3 bucket for model storage
dynamodb_table: DynamoDB table for model registry
region: AWS region
"""
self.s3_bucket = s3_bucket
self.dynamodb_table = dynamodb_table
self.region = region
self.s3_client = boto3.client('s3', region_name=region)
self.dynamodb = boto3.resource('dynamodb', region_name=region)
self.table = self.dynamodb.Table(dynamodb_table)
# Local model cache
self.model_cache: Dict[str, Tuple[Any, ModelMetadata]] = {}
self.cache_ttl = timedelta(hours=1)
self.cache_timestamps: Dict[str, datetime] = {}
def register_model(
self,
model_name: str,
version: str,
model_object: Any,
metrics: Dict[str, float],
description: str = "",
traffic_percentage: float = 0.0
) -> ModelMetadata:
"""
Register a new model version
Args:
model_name: Name of the model
version: Version string (e.g., 'v1.0.0')
model_object: Trained model object
metrics: Model performance metrics
description: Model description
traffic_percentage: Initial traffic percentage for A/B testing
Returns:
ModelMetadata object
"""
# Serialize model
model_bytes = pickle.dumps(model_object)
checksum = hashlib.sha256(model_bytes).hexdigest()
# Upload to S3
s3_path = f"ml-models/{model_name}/{version}/model.pkl"
self.s3_client.put_object(
Bucket=self.s3_bucket,
Key=s3_path,
Body=model_bytes,
Metadata={
'model_name': model_name,
'version': version,
'checksum': checksum,
'created_at': datetime.utcnow().isoformat()
}
)
# Create metadata
metadata = ModelMetadata(
model_name=model_name,
version=version,
s3_path=s3_path,
created_at=datetime.utcnow().isoformat(),
metrics=metrics,
status='testing',
traffic_percentage=traffic_percentage,
checksum=checksum,
description=description
)
# Store in DynamoDB
self.table.put_item(Item={
'model_name': model_name,
'version': version,
**asdict(metadata)
})
logger.info(f"Registered model {model_name} version {version}")
return metadata
def load_model(
self,
model_name: str,
version: Optional[str] = None,
use_cache: bool = True
) -> Tuple[Any, ModelMetadata]:
"""
Load a specific model version
Args:
model_name: Name of the model
version: Version to load (None for latest active)
use_cache: Whether to use cached model
Returns:
Tuple of (model_object, metadata)
"""
# Determine version to load
if version is None:
version = self.get_active_version(model_name)
cache_key = f"{model_name}:{version}"
# Check cache
if use_cache and cache_key in self.model_cache:
cache_time = self.cache_timestamps.get(cache_key)
if cache_time and datetime.utcnow() - cache_time < self.cache_ttl:
logger.info(f"Loading model {cache_key} from cache")
return self.model_cache[cache_key]
# Load metadata from DynamoDB
response = self.table.get_item(
Key={
'model_name': model_name,
'version': version
}
)
if 'Item' not in response:
raise ValueError(f"Model {model_name} version {version} not found")
item = response['Item']
metadata = ModelMetadata(**{k: v for k, v in item.items() if k in ModelMetadata.__annotations__})
# Load model from S3
response = self.s3_client.get_object(
Bucket=self.s3_bucket,
Key=metadata.s3_path
)
model_bytes = response['Body'].read()
# Verify checksum
checksum = hashlib.sha256(model_bytes).hexdigest()
if checksum != metadata.checksum:
raise ValueError(f"Model checksum mismatch for {model_name}:{version}")
# Deserialize model
model_object = pickle.loads(model_bytes)
# Update cache
self.model_cache[cache_key] = (model_object, metadata)
self.cache_timestamps[cache_key] = datetime.utcnow()
logger.info(f"Loaded model {cache_key} from S3")
return model_object, metadata
def get_active_version(self, model_name: str) -> str:
"""
Get the currently active version for a model
Args:
model_name: Name of the model
Returns:
Version string
"""
response = self.table.query(
KeyConditionExpression='model_name = :name',
FilterExpression='#status = :status',
ExpressionAttributeNames={'#status': 'status'},
ExpressionAttributeValues={
':name': model_name,
':status': 'active'
},
ScanIndexForward=False, # Latest first
Limit=1
)
if not response['Items']:
raise ValueError(f"No active version found for model {model_name}")
return response['Items'][0]['version']
def set_model_status(
self,
model_name: str,
version: str,
status: str,
traffic_percentage: Optional[float] = None
):
"""
Update model status and traffic allocation
Args:
model_name: Name of the model
version: Version string
status: New status ('active', 'testing', 'deprecated', 'archived')
traffic_percentage: Traffic percentage for A/B testing
"""
update_expression = "SET #status = :status"
expression_values = {':status': status}
expression_names = {'#status': 'status'}
if traffic_percentage is not None:
update_expression += ", traffic_percentage = :traffic"
expression_values[':traffic'] = traffic_percentage
self.table.update_item(
Key={
'model_name': model_name,
'version': version
},
UpdateExpression=update_expression,
ExpressionAttributeNames=expression_names,
ExpressionAttributeValues=expression_values
)
# Invalidate cache
cache_key = f"{model_name}:{version}"
if cache_key in self.model_cache:
del self.model_cache[cache_key]
del self.cache_timestamps[cache_key]
logger.info(f"Updated model {model_name}:{version} status to {status}")
def promote_to_active(self, model_name: str, version: str):
"""
Promote a model version to active (100% traffic)
Args:
model_name: Name of the model
version: Version to promote
"""
# Get current active version
try:
current_active = self.get_active_version(model_name)
# Deprecate current active
self.set_model_status(model_name, current_active, 'deprecated', 0.0)
except ValueError:
# No current active version
pass
# Promote new version
self.set_model_status(model_name, version, 'active', 100.0)
logger.info(f"Promoted {model_name}:{version} to active")
def rollback_to_version(self, model_name: str, version: str):
"""
Rollback to a previous model version
Args:
model_name: Name of the model
version: Version to rollback to
"""
# Verify version exists and is not archived
_, metadata = self.load_model(model_name, version, use_cache=False)
if metadata.status == 'archived':
raise ValueError(f"Cannot rollback to archived version {version}")
# Promote to active
self.promote_to_active(model_name, version)
logger.info(f"Rolled back {model_name} to version {version}")
def setup_ab_test(
self,
model_name: str,
version_a: str,
version_b: str,
traffic_split: float = 0.5
):
"""
Setup A/B test between two model versions
Args:
model_name: Name of the model
version_a: First version (gets traffic_split percentage)
version_b: Second version (gets 1-traffic_split percentage)
traffic_split: Percentage of traffic for version_a (0.0 to 1.0)
"""
if not 0.0 <= traffic_split <= 1.0:
raise ValueError("traffic_split must be between 0.0 and 1.0")
# Set both versions to testing status
self.set_model_status(
model_name, version_a, 'testing',
traffic_percentage=traffic_split * 100
)
self.set_model_status(
model_name, version_b, 'testing',
traffic_percentage=(1 - traffic_split) * 100
)
logger.info(
f"Setup A/B test for {model_name}: "
f"{version_a} ({traffic_split*100}%) vs {version_b} ({(1-traffic_split)*100}%)"
)
def get_model_for_request(
self,
model_name: str,
request_id: str
) -> Tuple[Any, ModelMetadata]:
"""
Get model for a request (handles A/B testing)
Args:
model_name: Name of the model
request_id: Unique request identifier for consistent routing
Returns:
Tuple of (model_object, metadata)
"""
# Get all testing and active versions
response = self.table.query(
KeyConditionExpression='model_name = :name',
FilterExpression='#status IN (:active, :testing)',
ExpressionAttributeNames={'#status': 'status'},
ExpressionAttributeValues={
':name': model_name,
':active': 'active',
':testing': 'testing'
}
)
versions = response['Items']
if not versions:
raise ValueError(f"No active or testing versions for model {model_name}")
# If only one version, use it
if len(versions) == 1:
version = versions[0]['version']
return self.load_model(model_name, version)
# A/B testing: use consistent hashing for request routing
request_hash = int(hashlib.md5(request_id.encode()).hexdigest(), 16)
random_value = (request_hash % 100) / 100.0 # 0.0 to 1.0
# Sort versions by traffic percentage
versions.sort(key=lambda x: x['traffic_percentage'], reverse=True)
# Select version based on traffic allocation
cumulative = 0.0
for version_data in versions:
cumulative += version_data['traffic_percentage'] / 100.0
if random_value <= cumulative:
version = version_data['version']
return self.load_model(model_name, version)
# Fallback to first version
version = versions[0]['version']
return self.load_model(model_name, version)
def list_versions(
self,
model_name: str,
status_filter: Optional[str] = None
) -> List[ModelMetadata]:
"""
List all versions of a model
Args:
model_name: Name of the model
status_filter: Optional status filter
Returns:
List of ModelMetadata objects
"""
if status_filter:
response = self.table.query(
KeyConditionExpression='model_name = :name',
FilterExpression='#status = :status',
ExpressionAttributeNames={'#status': 'status'},
ExpressionAttributeValues={
':name': model_name,
':status': status_filter
}
)
else:
response = self.table.query(
KeyConditionExpression='model_name = :name',
ExpressionAttributeValues={':name': model_name}
)
versions = [
ModelMetadata(**{k: v for k, v in item.items() if k in ModelMetadata.__annotations__})
for item in response['Items']
]
return versions
def get_model_metrics(
self,
model_name: str,
version: str
) -> Dict[str, float]:
"""
Get performance metrics for a model version
Args:
model_name: Name of the model
version: Version string
Returns:
Dictionary of metrics
"""
response = self.table.get_item(
Key={
'model_name': model_name,
'version': version
}
)
if 'Item' not in response:
raise ValueError(f"Model {model_name} version {version} not found")
return response['Item'].get('metrics', {})
def update_model_metrics(
self,
model_name: str,
version: str,
metrics: Dict[str, float]
):
"""
Update performance metrics for a model version
Args:
model_name: Name of the model
version: Version string
metrics: Updated metrics dictionary
"""
self.table.update_item(
Key={
'model_name': model_name,
'version': version
},
UpdateExpression="SET metrics = :metrics",
ExpressionAttributeValues={':metrics': metrics}
)
logger.info(f"Updated metrics for {model_name}:{version}")