-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathconftest.py
More file actions
4876 lines (4455 loc) · 176 KB
/
Copy pathconftest.py
File metadata and controls
4876 lines (4455 loc) · 176 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import OrderedDict, defaultdict
from dataclasses import dataclass
from datetime import datetime
from typing import (
IO,
Any,
AsyncIterable,
DefaultDict,
Dict,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
)
from unittest import mock
from unittest.mock import mock_open
from uuid import uuid4
import pytest
from model_engine_server.api.dependencies import ExternalInterfaces
from model_engine_server.common.constants import DEFAULT_CELERY_TASK_NAME
from model_engine_server.common.dtos.batch_jobs import CreateDockerImageBatchJobResourceRequests
from model_engine_server.common.dtos.docker_repository import BuildImageRequest, BuildImageResponse
from model_engine_server.common.dtos.endpoint_builder import BuildEndpointRequest
from model_engine_server.common.dtos.model_bundles import ModelBundleOrderBy
from model_engine_server.common.dtos.model_endpoints import (
BrokerType,
CpuSpecificationType,
GpuType,
ModelEndpointOrderBy,
StorageSpecificationType,
)
from model_engine_server.common.dtos.resource_manager import CreateOrUpdateResourcesRequest
from model_engine_server.common.dtos.tasks import (
CreateAsyncTaskV1Response,
EndpointPredictV1Request,
GetAsyncTaskV1Response,
SyncEndpointPredictV1Request,
SyncEndpointPredictV1Response,
TaskStatus,
)
from model_engine_server.common.settings import generate_destination
from model_engine_server.core.fake_notification_gateway import FakeNotificationGateway
from model_engine_server.core.tracing.live_tracing_gateway import LiveTracingGateway
from model_engine_server.db.endpoint_row_lock import get_lock_key
from model_engine_server.db.models import BatchJob as OrmBatchJob
from model_engine_server.db.models import Endpoint as OrmModelEndpoint
from model_engine_server.domain.entities import (
BatchJob,
BatchJobProgress,
BatchJobRecord,
BatchJobSerializationFormat,
BatchJobStatus,
CallbackAuth,
CallbackBasicAuth,
CloudpickleArtifactFlavor,
CustomFramework,
FileMetadata,
FineTuneHparamValueType,
LLMFineTuneEvent,
ModelBundle,
ModelBundleEnvironmentParams,
ModelBundleFlavors,
ModelBundleFrameworkType,
ModelBundlePackagingType,
ModelEndpoint,
ModelEndpointConfig,
ModelEndpointDeploymentState,
ModelEndpointInfraState,
ModelEndpointRecord,
ModelEndpointResourceState,
ModelEndpointsSchema,
ModelEndpointStatus,
ModelEndpointType,
ModelEndpointUserConfigState,
PytorchFramework,
RunnableImageFlavor,
StreamingEnhancedRunnableImageFlavor,
TensorflowFramework,
Trigger,
TritonEnhancedRunnableImageFlavor,
ZipArtifactFlavor,
)
from model_engine_server.domain.entities.batch_job_entity import DockerImageBatchJob
from model_engine_server.domain.entities.docker_image_batch_job_bundle_entity import (
DockerImageBatchJobBundle,
)
from model_engine_server.domain.entities.llm_fine_tune_entity import LLMFineTuneTemplate
from model_engine_server.domain.exceptions import (
EndpointResourceInfraException,
ObjectNotFoundException,
)
from model_engine_server.domain.gateways import (
AsyncModelEndpointInferenceGateway,
CronJobGateway,
DockerImageBatchJobGateway,
FileStorageGateway,
InferenceAutoscalingMetricsGateway,
LLMArtifactGateway,
StreamingModelEndpointInferenceGateway,
SyncModelEndpointInferenceGateway,
TaskQueueGateway,
)
from model_engine_server.domain.repositories import (
DockerImageBatchJobBundleRepository,
DockerRepository,
LLMFineTuneEventsRepository,
ModelBundleRepository,
TokenizerRepository,
TriggerRepository,
)
from model_engine_server.domain.services import (
LLMFineTuningService,
LLMModelEndpointService,
ModelEndpointService,
)
from model_engine_server.inference.domain.gateways.streaming_storage_gateway import (
StreamingStorageGateway,
)
from model_engine_server.infra.gateways import (
BatchJobOrchestrationGateway,
LiveBatchJobProgressGateway,
LiveModelEndpointsSchemaGateway,
ModelEndpointInfraGateway,
)
from model_engine_server.infra.gateways.fake_model_primitive_gateway import (
FakeModelPrimitiveGateway,
)
from model_engine_server.infra.gateways.fake_monitoring_metrics_gateway import (
FakeMonitoringMetricsGateway,
)
from model_engine_server.infra.gateways.filesystem_gateway import FilesystemGateway
from model_engine_server.infra.gateways.resources.endpoint_resource_gateway import (
EndpointResourceGateway,
EndpointResourceGatewayCreateOrUpdateResourcesResponse,
QueueInfo,
)
from model_engine_server.infra.gateways.resources.image_cache_gateway import (
CachedImages,
ImageCacheGateway,
)
from model_engine_server.infra.repositories import (
BatchJobRecordRepository,
FeatureFlagRepository,
LLMFineTuneRepository,
ModelEndpointCacheRepository,
ModelEndpointRecordRepository,
)
from model_engine_server.infra.repositories.db_model_bundle_repository import (
translate_kwargs_to_model_bundle_orm,
translate_model_bundle_orm_to_model_bundle,
)
from model_engine_server.infra.services import LiveBatchJobService, LiveModelEndpointService
from model_engine_server.infra.services.fake_llm_batch_completions_service import (
FakeLLMBatchCompletionsService,
)
from model_engine_server.infra.services.image_cache_service import ImageCacheService
from model_engine_server.infra.services.live_llm_batch_completions_service import (
LiveLLMBatchCompletionsService,
)
from model_engine_server.infra.services.live_llm_model_endpoint_service import (
LiveLLMModelEndpointService,
)
from transformers import AutoTokenizer
def _translate_fake_model_endpoint_orm_to_model_endpoint_record(
model_endpoint_orm: OrmModelEndpoint, current_model_bundle: ModelBundle
) -> ModelEndpointRecord:
# Needed since the orm model has a column `endpoint_metadata` that turns into `metadata` in our model
return ModelEndpointRecord(
id=model_endpoint_orm.id,
name=model_endpoint_orm.name,
created_by=model_endpoint_orm.created_by,
owner=model_endpoint_orm.owner,
created_at=model_endpoint_orm.created_at,
last_updated_at=model_endpoint_orm.last_updated_at,
metadata=model_endpoint_orm.endpoint_metadata,
creation_task_id=model_endpoint_orm.creation_task_id,
endpoint_type=ModelEndpointType(model_endpoint_orm.endpoint_type),
destination="test_destination",
status=ModelEndpointStatus(model_endpoint_orm.endpoint_status),
current_model_bundle=current_model_bundle,
)
def _translate_fake_batch_job_orm_to_batch_job_record(
batch_job_orm: OrmBatchJob, model_bundle: ModelBundle
) -> BatchJobRecord:
return BatchJobRecord(
id=batch_job_orm.id,
created_at=batch_job_orm.created_at,
completed_at=batch_job_orm.completed_at,
status=BatchJobStatus(batch_job_orm.batch_job_status),
created_by=batch_job_orm.created_by,
owner=batch_job_orm.owner,
model_bundle=model_bundle,
model_endpoint_id=batch_job_orm.model_endpoint_id,
task_ids_location=batch_job_orm.task_ids_location,
result_location=batch_job_orm.result_location,
)
class FakeModelBundleRepository(ModelBundleRepository):
def __init__(self, contents: Optional[Dict[str, ModelBundle]] = None):
if contents:
self.db = contents
self.unique_owner_name_versions = set()
for model_bundle in self.db.values():
self.unique_owner_name_versions.add((model_bundle.owner, model_bundle.name))
else:
self.db = {}
self.unique_owner_name_versions = set()
def add_model_bundle(self, model_bundle: ModelBundle):
self.db[model_bundle.id] = model_bundle
async def create_model_bundle(
self,
*,
name: str,
created_by: str,
owner: str,
model_artifact_ids: List[str],
schema_location: Optional[str],
metadata: Dict[str, Any],
flavor: ModelBundleFlavors,
# LEGACY FIELDS
location: str,
requirements: List[str],
env_params: Dict[str, Any],
packaging_type: ModelBundlePackagingType,
app_config: Optional[Dict[str, Any]],
) -> ModelBundle:
orm_model_bundle = translate_kwargs_to_model_bundle_orm(
name=name,
created_by=created_by,
owner=owner,
model_artifact_ids=model_artifact_ids,
schema_location=schema_location,
metadata=metadata,
flavor=flavor,
# LEGACY FIELDS
location=location,
requirements=requirements,
env_params=env_params,
packaging_type=packaging_type,
app_config=app_config,
)
orm_model_bundle.created_at = datetime.now()
model_bundle = translate_model_bundle_orm_to_model_bundle(orm_model_bundle)
self.db[model_bundle.id] = model_bundle
return self.db[model_bundle.id]
async def list_model_bundles(
self, owner: str, name: Optional[str], order_by: Optional[ModelBundleOrderBy]
) -> Sequence[ModelBundle]:
model_bundles = [
mb for mb in self.db.values() if mb.owner == owner and (not name or mb.name == name)
]
if order_by == ModelBundleOrderBy.NEWEST:
model_bundles.sort(key=lambda x: x.created_at, reverse=True)
elif order_by == ModelBundleOrderBy.OLDEST:
model_bundles.sort(key=lambda x: x.created_at, reverse=False)
return model_bundles
async def get_latest_model_bundle_by_name(self, owner: str, name: str) -> Optional[ModelBundle]:
model_bundles = await self.list_model_bundles(owner, name, ModelBundleOrderBy.NEWEST)
if not model_bundles:
return None
return model_bundles[0]
async def get_model_bundle(self, model_bundle_id: str) -> Optional[ModelBundle]:
return self.db.get(model_bundle_id)
class FakeBatchJobRecordRepository(BatchJobRecordRepository):
db: Dict[str, BatchJobRecord]
model_bundle_repository: ModelBundleRepository
def __init__(
self,
contents: Optional[Dict[str, BatchJobRecord]] = None,
model_bundle_repository: Optional[ModelBundleRepository] = None,
):
if contents:
self.db = contents
else:
self.db = {}
if model_bundle_repository is None:
model_bundle_repository = FakeModelBundleRepository()
self.model_bundle_repository = model_bundle_repository
def add_batch_job_record(self, batch_job_record: BatchJobRecord):
self.db[batch_job_record.id] = batch_job_record
async def create_batch_job_record(
self,
*,
status: BatchJobStatus,
created_by: str,
owner: str,
model_bundle_id: str,
) -> BatchJobRecord:
orm_batch_job = OrmBatchJob(
batch_job_status=status,
created_by=created_by,
owner=owner,
model_bundle_id=model_bundle_id,
)
orm_batch_job.created_at = datetime.now()
model_bundle = await self.model_bundle_repository.get_model_bundle(model_bundle_id)
assert model_bundle is not None
batch_job = _translate_fake_batch_job_orm_to_batch_job_record(
orm_batch_job, model_bundle=model_bundle
)
self.db[batch_job.id] = batch_job
return batch_job
@staticmethod
def update_batch_job_record_in_place(
batch_job_record: BatchJobRecord,
**kwargs,
):
if kwargs["status"] is not None:
batch_job_record.status = kwargs["status"]
if kwargs["model_endpoint_id"] is not None:
batch_job_record.model_endpoint_id = kwargs["model_endpoint_id"]
if kwargs["task_ids_location"] is not None:
batch_job_record.task_ids_location = kwargs["task_ids_location"]
if kwargs["result_location"] is not None:
batch_job_record.result_location = kwargs["result_location"]
async def update_batch_job_record(
self,
*,
batch_job_id: str,
status: Optional[BatchJobStatus] = None,
model_endpoint_id: Optional[str] = None,
task_ids_location: Optional[str] = None,
result_location: Optional[str] = None,
completed_at: Optional[datetime] = None,
) -> Optional[BatchJobRecord]:
batch_job_record = await self.get_batch_job_record(batch_job_id=batch_job_id)
self.update_batch_job_record_in_place(**locals())
return batch_job_record
async def get_batch_job_record(self, batch_job_id: str) -> Optional[BatchJobRecord]:
return self.db.get(batch_job_id)
async def list_batch_job_records(self, owner: Optional[str]) -> List[BatchJobRecord]:
def filter_fn(m: BatchJobRecord) -> bool:
return not owner or m.owner == owner
batch_jobs = list(filter(filter_fn, self.db.values()))
return batch_jobs
async def unset_model_endpoint_id(self, batch_job_id: str) -> Optional[BatchJobRecord]:
batch_job_record = await self.get_batch_job_record(batch_job_id)
if batch_job_record:
batch_job_record.model_endpoint_id = None
return batch_job_record
class FakeModelEndpointRecordRepository(ModelEndpointRecordRepository):
db: Dict[str, ModelEndpointRecord]
model_bundle_repository: ModelBundleRepository
def __init__(
self,
contents: Optional[Dict[str, ModelEndpointRecord]] = None,
model_bundle_repository: Optional[ModelBundleRepository] = None,
):
if contents:
self.db = contents
self.unique_owner_name_versions = set()
for model_endpoint in self.db.values():
self.unique_owner_name_versions.add((model_endpoint.owner, model_endpoint.name))
else:
self.db = {}
self.unique_owner_name_versions = set()
if model_bundle_repository is None:
model_bundle_repository = FakeModelBundleRepository()
self.model_bundle_repository = model_bundle_repository
self._lock_db: DefaultDict[int, bool] = defaultdict(bool)
class FakeLockContext(ModelEndpointRecordRepository.LockContext):
def __init__(self, lock_id: int, lock_db: DefaultDict[int, bool]):
self._lock_id = lock_id
self._lock_db = lock_db
self._lock_acquired = False
async def __aenter__(self):
if not self._lock_db[self._lock_id]:
self._lock_db[self._lock_id] = True
self._lock_acquired = True
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self._lock_acquired:
self._lock_db[self._lock_id] = False
self._lock_acquired = False
def lock_acquired(self) -> bool:
return self._lock_acquired
def force_lock_model_endpoint(self, model_endpoint_record: ModelEndpointRecord):
lock_id = get_lock_key(
user_id=model_endpoint_record.created_by,
endpoint_name=model_endpoint_record.name,
)
self._lock_db[lock_id] = True
def force_unlock_model_endpoint(self, model_endpoint_record: ModelEndpointRecord):
lock_id = get_lock_key(
user_id=model_endpoint_record.created_by,
endpoint_name=model_endpoint_record.name,
)
self._lock_db[lock_id] = False
def get_lock_context(
self, model_endpoint_record: ModelEndpointRecord
) -> ModelEndpointRecordRepository.LockContext:
lock_id = get_lock_key(
user_id=model_endpoint_record.created_by,
endpoint_name=model_endpoint_record.name,
)
return self.FakeLockContext(lock_id=lock_id, lock_db=self._lock_db)
def add_model_endpoint_record(self, model_endpoint_record: ModelEndpointRecord):
self.db[model_endpoint_record.id] = model_endpoint_record
async def create_model_endpoint_record(
self,
*,
name: str,
created_by: str,
model_bundle_id: str,
metadata: Optional[Dict[str, Any]],
endpoint_type: str,
destination: str,
creation_task_id: str,
status: str,
owner: str,
public_inference: Optional[bool] = False,
) -> ModelEndpointRecord:
orm_model_endpoint = OrmModelEndpoint(
name=name,
created_by=created_by,
current_bundle_id=model_bundle_id,
endpoint_metadata=metadata,
endpoint_type=endpoint_type,
destination=destination,
creation_task_id=creation_task_id,
endpoint_status=status,
owner=owner,
public_inference=public_inference,
)
orm_model_endpoint.created_at = datetime.now()
orm_model_endpoint.last_updated_at = datetime.now()
model_bundle = await self.model_bundle_repository.get_model_bundle(model_bundle_id)
assert model_bundle is not None
model_endpoint = _translate_fake_model_endpoint_orm_to_model_endpoint_record(
orm_model_endpoint, current_model_bundle=model_bundle
)
self.db[model_endpoint.id] = model_endpoint
return model_endpoint
@staticmethod
def update_model_endpoint_record_in_place(
model_endpoint_record: ModelEndpointRecord,
**kwargs,
):
if kwargs["current_model_bundle"] is not None:
model_endpoint_record.current_model_bundle = kwargs["current_model_bundle"]
if kwargs["metadata"] is not None:
model_endpoint_record.metadata = kwargs["metadata"]
if kwargs["creation_task_id"] is not None:
model_endpoint_record.creation_task_id = kwargs["creation_task_id"]
if kwargs["status"] is not None:
model_endpoint_record.status = kwargs["status"]
async def update_model_endpoint_record(
self,
*,
model_endpoint_id: str,
model_bundle_id: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
creation_task_id: Optional[str] = None,
destination: Optional[str] = None,
status: Optional[str] = None,
public_inference: Optional[bool] = None,
) -> Optional[ModelEndpointRecord]:
model_endpoint_record = await self.get_model_endpoint_record(
model_endpoint_id=model_endpoint_id
)
current_model_bundle = None
if model_bundle_id is not None:
current_model_bundle = await self.model_bundle_repository.get_model_bundle(
model_bundle_id
)
self.update_model_endpoint_record_in_place(**locals())
return model_endpoint_record
async def get_model_endpoint_record(
self, model_endpoint_id: str
) -> Optional[ModelEndpointRecord]:
return self.db.get(model_endpoint_id)
async def get_llm_model_endpoint_record(
self, model_endpoint_name: str
) -> Optional[ModelEndpointRecord]:
def filter_fn(m: ModelEndpointRecord) -> bool:
return "_llm" in m.metadata and m.name == model_endpoint_name
model_endpoints = list(filter(filter_fn, self.db.values()))
assert len(model_endpoints) <= 1
if len(model_endpoints) == 0:
return None
else:
return model_endpoints[0]
async def list_model_endpoint_records(
self,
owner: Optional[str],
name: Optional[str],
order_by: Optional[ModelEndpointOrderBy],
) -> List[ModelEndpointRecord]:
def filter_fn(m: ModelEndpointRecord) -> bool:
return (not owner or m.owner == owner) and (not name or m.name == name)
model_endpoints = list(filter(filter_fn, self.db.values()))
if order_by == ModelEndpointOrderBy.NEWEST:
model_endpoints.sort(key=lambda x: x.created_at, reverse=True)
elif order_by == ModelEndpointOrderBy.OLDEST:
model_endpoints.sort(key=lambda x: x.created_at, reverse=False)
return model_endpoints
async def list_llm_model_endpoint_records(
self,
owner: Optional[str],
name: Optional[str],
order_by: Optional[ModelEndpointOrderBy],
) -> List[ModelEndpointRecord]:
def filter_fn(m: ModelEndpointRecord) -> bool:
return ("_llm" in m.metadata) and (
((not owner or m.owner == owner) and (not name or m.name == name))
or (m.public_inference is True)
)
model_endpoints = list(filter(filter_fn, self.db.values()))
if order_by == ModelEndpointOrderBy.NEWEST:
model_endpoints.sort(key=lambda x: x.created_at, reverse=True)
elif order_by == ModelEndpointOrderBy.OLDEST:
model_endpoints.sort(key=lambda x: x.created_at, reverse=False)
return model_endpoints
async def delete_model_endpoint_record(self, model_endpoint_id: str) -> bool:
if model_endpoint_id not in self.db:
return False
del self.db[model_endpoint_id]
return True
class FakeDockerImageBatchJobBundleRepository(DockerImageBatchJobBundleRepository):
def __init__(self, contents: Optional[Dict[str, DockerImageBatchJobBundle]] = None):
if contents:
self.db = contents
else:
self.db = {}
self.next_id = 0
def _get_new_id(self):
current_ids = {bun.id for bun in self.db.values()}
while str(self.next_id) in current_ids:
self.next_id += 1
return str(self.next_id)
def add_docker_image_batch_job_bundle(self, batch_bundle: DockerImageBatchJobBundle):
new_id = batch_bundle.id
if new_id in {bun.id for bun in self.db.values()}:
raise ValueError(f"Error in test set up, batch bundle with {new_id} already present")
self.db[new_id] = batch_bundle
async def create_docker_image_batch_job_bundle(
self,
*,
name: str,
created_by: str,
owner: str,
image_repository: str,
image_tag: str,
command: List[str],
env: Dict[str, str],
mount_location: Optional[str],
cpus: Optional[str],
memory: Optional[str],
storage: Optional[str],
gpus: Optional[int],
gpu_type: Optional[GpuType],
public: Optional[bool],
) -> DockerImageBatchJobBundle:
bun_id = self._get_new_id()
batch_bundle = DockerImageBatchJobBundle(
id=bun_id,
created_at=datetime.now(),
name=name,
created_by=created_by,
owner=owner,
image_repository=image_repository,
image_tag=image_tag,
command=command,
env=env,
mount_location=mount_location,
cpus=cpus,
memory=memory,
storage=storage,
gpus=gpus,
gpu_type=gpu_type,
public=public,
)
self.db[bun_id] = batch_bundle
return batch_bundle
async def list_docker_image_batch_job_bundles(
self, owner: str, name: Optional[str], order_by: Optional[ModelBundleOrderBy]
) -> Sequence[DockerImageBatchJobBundle]:
def filter_fn(dibun: DockerImageBatchJobBundle):
return (dibun.owner == owner) and (name is None or dibun.name == name)
buns = [dibun for dibun in self.db.values() if filter_fn(dibun)]
if order_by == ModelBundleOrderBy.NEWEST:
buns.sort(key=lambda x: x.created_at, reverse=True)
elif order_by == ModelBundleOrderBy.OLDEST:
buns.sort(key=lambda x: x.created_at, reverse=False)
return buns
async def get_docker_image_batch_job_bundle(
self, docker_image_batch_job_bundle_id: str
) -> Optional[DockerImageBatchJobBundle]:
return self.db.get(docker_image_batch_job_bundle_id)
async def get_latest_docker_image_batch_job_bundle(
self, owner: str, name: str
) -> Optional[DockerImageBatchJobBundle]:
def filter_fn(dibun: DockerImageBatchJobBundle):
return (dibun.owner == owner) and (dibun.name == name)
buns = [dibun for dibun in self.db.values() if filter_fn(dibun)]
if len(buns) == 0:
return None
return max(buns, key=lambda bun: bun.created_at)
class FakeDockerRepository(DockerRepository):
def __init__(self, image_always_exists: bool, raises_error: bool):
self.image_always_exists = image_always_exists
self.raises_error = raises_error
def image_exists(
self, image_tag: str, repository_name: str, aws_profile: Optional[str] = None
) -> bool:
return self.image_always_exists
def get_image_url(self, image_tag: str, repository_name: str) -> str:
return f"{repository_name}:{image_tag}"
def build_image(self, image_params: BuildImageRequest) -> BuildImageResponse:
if self.raises_error:
raise Exception("I hope you're handling this!")
return BuildImageResponse(status=True, logs="", job_name="test-job-name")
def get_latest_image_tag(self, repository_name: str) -> str:
return "fake_docker_repository_latest_image_tag"
class FakeModelEndpointCacheRepository(ModelEndpointCacheRepository):
def __init__(self):
self.db = {}
async def write_endpoint_info(
self,
endpoint_id: str,
endpoint_info: ModelEndpointInfraState,
ttl_seconds: float,
):
self.db[endpoint_id] = endpoint_info
async def read_endpoint_info(
self, endpoint_id: str, deployment_name: str
) -> Optional[ModelEndpointInfraState]:
return self.db.get(endpoint_id, None)
def force_expire_key(self, endpoint_id: str):
"""
Use to simulate key expiring
"""
if endpoint_id in self.db:
del self.db[endpoint_id]
class FakeFeatureFlagRepository(FeatureFlagRepository):
def __init__(self):
self.db = {}
async def write_feature_flag_bool(
self,
key: str,
value: bool,
):
self.db[key] = value
async def read_feature_flag_bool(
self,
key: str,
) -> Optional[bool]:
return self.db.get(key, None)
class FakeLLMFineTuneRepository(LLMFineTuneRepository):
def __init__(self, db: Optional[Dict[Tuple[str, str], LLMFineTuneTemplate]] = None):
self.db = db
if self.db is None:
self.db = {}
async def get_job_template_for_model(
self, model_name: str, fine_tuning_method: str
) -> Optional[LLMFineTuneTemplate]:
return self.db.get((model_name, fine_tuning_method), None)
async def write_job_template_for_model(
self,
model_name: str,
fine_tuning_method: str,
job_template: LLMFineTuneTemplate,
):
self.db[(model_name, fine_tuning_method)] = job_template
class FakeLLMFineTuneEventsRepository(LLMFineTuneEventsRepository):
def __init__(self):
self.initialized_events = []
self.all_events_list = [LLMFineTuneEvent(timestamp=1, message="message", level="info")]
async def get_fine_tune_events(self, user_id: str, model_endpoint_name: str):
if (user_id, model_endpoint_name) in self.initialized_events:
return self.all_events_list
raise ObjectNotFoundException
async def initialize_events(self, user_id: str, model_endpoint_name: str):
self.initialized_events.append((user_id, model_endpoint_name))
class FakeLLMArtifactGateway(LLMArtifactGateway):
def __init__(self):
self.existing_models = []
self.s3_bucket = {
"fake-checkpoint": [
"model-fake.bin, model-fake2.bin",
"model-fake.safetensors",
],
"llama-7b/tokenizer.json": ["llama-7b/tokenizer.json"],
"llama-7b/tokenizer_config.json": ["llama-7b/tokenizer_config.json"],
"llama-7b/special_tokens_map.json": ["llama-7b/special_tokens_map.json"],
"llama-2-7b": ["model-fake.safetensors"],
"mpt-7b": ["model-fake.safetensors"],
"llama-3-70b": ["model-fake.safetensors"],
"llama-3-1-405b-instruct": ["model-fake.safetensors"],
}
self.urls = {"filename": "https://test-bucket.s3.amazonaws.com/llm/llm-1.0.0.tar.gz"}
self.model_config = {
"_name_or_path": "meta-llama/Llama-2-7b-hf",
"architectures": ["LlamaForCausalLM"],
"bos_token_id": 1,
"eos_token_id": 2,
"hidden_act": "silu",
"hidden_size": 4096,
"initializer_range": 0.02,
"intermediate_size": 11008,
"max_position_embeddings": 4096,
"model_type": "llama",
"num_attention_heads": 32,
"num_hidden_layers": 32,
"num_key_value_heads": 32,
"pretraining_tp": 1,
"rms_norm_eps": 1e-05,
"rope_scaling": None,
"tie_word_embeddings": False,
"torch_dtype": "float16",
"transformers_version": "4.31.0.dev0",
"use_cache": True,
"vocab_size": 32000,
}
self.tokenizer_config = {
"add_bos_token": True,
"add_eos_token": False,
"add_prefix_space": None,
"added_tokens_decoder": {
"0": {
"content": "<unk>",
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
"special": True,
},
"1": {
"content": "<s>",
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
"special": True,
},
"2": {
"content": "</s>",
"lstrip": False,
"normalized": False,
"rstrip": False,
"single_word": False,
"special": True,
},
},
"additional_special_tokens": [],
"bos_token": "<s>",
"chat_template": "{%- if messages[0]['role'] == 'system' %}\n {%- set system_message = messages[0]['content'] %}\n {%- set loop_messages = messages[1:] %}\n{%- else %}\n {%- set loop_messages = messages %}\n{%- endif %}\n\n{{- bos_token }}\n{%- for message in loop_messages %}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}\n {{- raise_exception('After the optional system message, conversation roles must alternate user/assistant/user/assistant/...') }}\n {%- endif %}\n {%- if message['role'] == 'user' %}\n {%- if loop.first and system_message is defined %}\n {{- ' [INST] ' + system_message + '\\n\\n' + message['content'] + ' [/INST]' }}\n {%- else %}\n {{- ' [INST] ' + message['content'] + ' [/INST]' }}\n {%- endif %}\n {%- elif message['role'] == 'assistant' %}\n {{- ' ' + message['content'] + eos_token}}\n {%- else %}\n {{- raise_exception('Only user and assistant roles are supported, with the exception of an initial optional system message!') }}\n {%- endif %}\n{%- endfor %}\n",
"clean_up_tokenization_spaces": False,
"eos_token": "</s>",
"legacy": False,
"model_max_length": 1000000000000000019884624838656,
"pad_token": None,
"sp_model_kwargs": {},
"spaces_between_special_tokens": False,
"tokenizer_class": "LlamaTokenizer",
"unk_token": "<unk>",
"use_default_system_prompt": False,
}
def _add_model(self, owner: str, model_name: str):
self.existing_models.append((owner, model_name))
def list_files(self, path: str, **kwargs) -> List[str]:
path = path.lstrip("s3://")
if path in self.s3_bucket:
return self.s3_bucket[path]
def download_files(self, path: str, target_path: str, overwrite=False, **kwargs) -> List[str]:
path = path.lstrip("s3://")
if path in self.s3_bucket:
return self.s3_bucket[path]
def upload_files(self, local_path: str, remote_path: str, **kwargs) -> None:
pass
def get_model_weights_urls(self, owner: str, model_name: str):
if (owner, model_name) in self.existing_models:
return self.urls
raise ObjectNotFoundException
def get_model_config(self, path: str, **kwargs) -> Dict[str, Any]:
return self.model_config
class FakeTriggerRepository(TriggerRepository): # pragma: no cover
def __init__(self, contents: Optional[Dict[str, Trigger]] = None):
self.db = {} if contents is None else contents
self.next_id = 0
def _get_new_id(self):
new_id = f"trig_{self.next_id}"
self.next_id += 1
return new_id
async def create_trigger(
self,
*,
name: str,
created_by: str,
owner: str,
cron_schedule: str,
docker_image_batch_job_bundle_id: str,
default_job_config: Optional[Dict[str, Any]],
default_job_metadata: Optional[Dict[str, str]],
) -> Trigger:
trigger_id = self._get_new_id()
trigger = Trigger(
id=trigger_id,
name=name,
owner=owner,
created_by=created_by,
created_at=datetime.now(),
cron_schedule=cron_schedule,
docker_image_batch_job_bundle_id=docker_image_batch_job_bundle_id,
default_job_config=default_job_config,
default_job_metadata=default_job_metadata,
)
self.db[trigger_id] = trigger
return trigger
async def list_triggers(
self,
owner: str,
) -> Sequence[Trigger]:
def filter_fn(trig: Trigger) -> bool:
return trig.owner == owner
return list(filter(filter_fn, self.db.values()))
async def get_trigger(
self,
trigger_id: str,
) -> Optional[Trigger]:
return self.db.get(trigger_id)
async def update_trigger(
self,
trigger_id: str,
cron_schedule: str,
) -> bool:
if trigger_id not in self.db:
return False
self.db[trigger_id].cron_schedule = cron_schedule
return True
async def delete_trigger(
self,
trigger_id: str,
) -> bool:
if trigger_id not in self.db:
return False
del self.db[trigger_id]
return True
class FakeImageCacheGateway(ImageCacheGateway):
def __init__(self):
self.cached_images = CachedImages(
cpu=[], a10=[], a100=[], t4=[], h100=[], h100_1g20gb=[], h100_3g40gb=[]
)
async def create_or_update_image_cache(self, cached_images: CachedImages) -> None:
self.cached_images = cached_images
class FakeBatchJobOrchestrationGateway(BatchJobOrchestrationGateway):
def __init__(self):
self.db = {}
async def create_batch_job_orchestrator(
self,
job_id: str,
resource_group_name: str,
owner: str,
input_path: str,
serialization_format: BatchJobSerializationFormat,
labels: Dict[str, str],
timeout_seconds: float,
) -> None:
self.db[resource_group_name] = {
"id": job_id,
"resource_group_name": resource_group_name,
"owner": owner,
"input_path": input_path,
"serialization_format": serialization_format,
"labels": labels,
}
async def delete_batch_job_orchestrator(self, resource_group_name: str) -> bool:
del self.db[resource_group_name]
return True
class FakeFilesystemGateway(FilesystemGateway):
def __init__(self, read_data: Optional[str] = None):
self.read_data = read_data or ""
self.mock_open = mock_open(read_data=self.read_data)
def open(self, uri: str, mode: str = "rt", **kwargs) -> IO:
self.mock_open = mock_open(read_data=self.read_data)
return self.mock_open(uri, mode=mode, **kwargs)
def generate_signed_url(self, uri: str, expiration: int = 3600, **kwargs) -> str:
return uri