modelexpress-client 0.7.0

Client library for Model Express gRPC server
Documentation
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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import time
from concurrent import futures
from unittest.mock import MagicMock

import grpc
import modelexpress_rl.train.client as client_module
import modelexpress_rl.train.runtime as runtime_module
import pytest
from modelexpress_rl import (
    FSDPTrainerContext,
    ModelExpressTrainerClient,
    ModelExpressTrainerConfig,
    TrainerStagingMode,
    WeightPayloadFormat,
    WeightVersionRef,
    refit_pb2,
    refit_pb2_grpc,
)
from modelexpress_rl.train.adapter import (
    CompletionFence,
    StagedWeightVersionShardData,
    TrainerEngineAdapter,
    WeightVersionShardManifest,
)
from modelexpress_rl.train.manifest import WeightVersionShardManifestService


class _RefitService(refit_pb2_grpc.RefitServiceServicer):
    def __init__(self):
        self.registrations = {}
        self.registration_count = 0
        self.shards = []
        self.deleted_shards = []

    def RegisterWorker(self, request, _context):
        self.registration_count += 1
        worker = request.worker
        worker.expires_at_unix_ms = 1234
        self.registrations[worker.worker_id] = worker
        return refit_pb2.RegisterWorkerResponse(worker=worker)

    def CreateWeightVersionShard(self, request, context):
        shard = request.shard
        if shard.worker_id not in self.registrations:
            context.abort(grpc.StatusCode.FAILED_PRECONDITION, "worker not registered")
        self.shards.append(shard)
        return refit_pb2.CreateWeightVersionShardResponse(
            shard=shard,
            version=refit_pb2.WeightVersion(
                uid=shard.version_id,
                state=refit_pb2.WEIGHT_VERSION_STATE_READY,
            ),
        )

    def DeleteWeightVersionShard(self, request, _context):
        self.deleted_shards.append(request)
        return refit_pb2.DeleteWeightVersionShardResponse(deleted=True)


class _Manager:
    listen_port = 19000


class _Adapter(TrainerEngineAdapter):
    source_slot_id = "rank:0"
    supported_staging_modes = frozenset({TrainerStagingMode.COPY_TO_DEVICE})
    supported_payload_formats = frozenset({WeightPayloadFormat.FULL_TENSOR})

    def __init__(self):
        self.calls = []

    def bind_tensors(self, tensors):
        if tensors is None:
            raise ValueError("tensors must not be None")
        return self.source_slot_id

    def stage_shard(self, *, tensors, staging_mode, payload_format):
        self.calls.append((tensors, staging_mode, payload_format))

        return StagedWeightVersionShardData(
            manifest=WeightVersionShardManifest(
                data=b"manifest",
                tensor_count=2,
                total_bytes=128,
                transport="NIXL",
            ),
            publish_ready=CompletionFence(lambda: None),
            buffer_owner=tensors,
        )


def _patch_resources(monkeypatch, *, manager, manifest_service, worker_endpoint):
    resources = MagicMock(
        manager=manager,
        manifest_service=manifest_service,
        worker_endpoint=worker_endpoint,
    )
    initialize_resources = MagicMock(return_value=resources)
    monkeypatch.setattr(
        runtime_module._TrainerResources,
        "initialize",
        initialize_resources,
    )
    return resources


@pytest.mark.parametrize(
    ("setting", "value", "message"),
    [
        ("registration_ttl_seconds", 0, "registration_ttl_seconds must be positive"),
        (
            "rpc_timeout_seconds",
            float("nan"),
            "rpc_timeout_seconds must be finite and positive",
        ),
    ],
)
def test_trainer_config_rejects_invalid_numeric_settings(setting, value, message):
    with pytest.raises(ValueError, match=message):
        ModelExpressTrainerConfig(**{setting: value})


def test_trainer_config_rejects_unspecified_payload_format():
    with pytest.raises(ValueError, match="payload_format must be specified"):
        ModelExpressTrainerConfig(payload_format=WeightPayloadFormat.UNSPECIFIED)


def test_trainer_config_preserves_original_positional_field_order():
    config = ModelExpressTrainerConfig(2, "trainer-agent", "test/model")

    assert config.device_id == 2
    assert config.agent_name == "trainer-agent"
    assert config.model_name == "test/model"
    assert config.engine_context is None


def test_refit_shard_keeps_only_its_nixl_manifest_endpoint():
    shard = refit_pb2.WeightVersionShard(manifest_endpoint="trainer:9000")

    assert shard.manifest_endpoint == "trainer:9000"
    assert (
        refit_pb2.WeightVersion.DESCRIPTOR.fields_by_name["object_storage"].number == 10
    )
    assert list(refit_pb2.ObjectStorageSource.DESCRIPTOR.fields_by_name) == [
        "uri",
        "storage_type",
    ]
    assert refit_pb2.OBJECT_STORAGE_TYPE_S3 == 1


def test_refit_service_uses_named_response_messages():
    service = refit_pb2.DESCRIPTOR.services_by_name["RefitService"]

    assert len(service.methods) == 10
    assert all(
        method.output_type.name.endswith("Response") for method in service.methods
    )


def test_released_manifests_do_not_accumulate():
    service = WeightVersionShardManifestService(endpoint="trainer:9000")
    manifest = WeightVersionShardManifest(
        data=b"manifest",
        tensor_count=1,
        total_bytes=2,
        transport="NIXL",
    )

    for index in range(1000):
        version_id = f"version-{index}"
        service.publish_manifest(
            version_id=version_id,
            source_slot_id="rank:0",
            manifest=manifest,
        )
        service.release_manifest(
            version_id=version_id,
            source_slot_id="rank:0",
        )

    assert service._manifests == {}


def test_trainer_stages_then_publishes_one_rank_local_shard(monkeypatch):
    service = _RefitService()
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=2))
    refit_pb2_grpc.add_RefitServiceServicer_to_server(service, server)
    port = server.add_insecure_port("127.0.0.1:0")
    manifest_service = WeightVersionShardManifestService(endpoint=f"127.0.0.1:{port}")
    refit_pb2_grpc.add_RefitWorkerServiceServicer_to_server(manifest_service, server)
    server.start()
    adapter = _Adapter()
    monkeypatch.setattr(
        runtime_module, "_create_trainer_adapter", lambda *_args, **_kwargs: adapter
    )
    monkeypatch.setenv("MODEL_NAME", "test/model")
    monkeypatch.setenv("MX_TRAINER_STAGING_MODE", "COPY_TO_DEVICE")
    monkeypatch.setenv("MX_WEIGHT_PAYLOAD_FORMAT", "FULL_TENSOR")
    monkeypatch.setenv("MX_WORKER_HOST", "127.0.0.1")
    monkeypatch.setenv("MX_WORKER_GRPC_PORT", str(port))
    _patch_resources(
        monkeypatch,
        manager=_Manager(),
        manifest_service=manifest_service,
        worker_endpoint=f"127.0.0.1:{port}",
    )

    try:
        trainer = ModelExpressTrainerClient.initialize(
            ModelExpressTrainerConfig(
                engine_context=FSDPTrainerContext(),
                device_id=0,
                worker_id="trainer-0",
                server_url=f"127.0.0.1:{port}",
                registration_ttl_seconds=1,
            )
        )
        deadline = time.monotonic() + 10.0
        while service.registration_count < 2 and time.monotonic() < deadline:
            time.sleep(0.02)
        assert service.registration_count >= 2
        with pytest.raises(ValueError, match="must not be None"):
            trainer.bind_tensors(None)
        assert trainer.bind_tensors("model") == "rank:0"
        with pytest.raises(RuntimeError, match="already bound"):
            trainer.bind_tensors("replacement")
        assert service.shards == []
        trainer.publish_version(version=WeightVersionRef("version-a"))
        metrics = trainer.pop_metrics()
        assert metrics["trainer_refit_e2e_s"] >= 0
        assert metrics["publication_rpc_s"] >= 0

        worker_stub = refit_pb2_grpc.RefitWorkerServiceStub(
            grpc.insecure_channel(service.shards[0].manifest_endpoint)
        )
        fetched = worker_stub.GetWeightVersionShardManifest(
            refit_pb2.GetWeightVersionShardManifestRequest(
                version_id="version-a",
                source_slot_id="rank:0",
            )
        )
        second = trainer.stage_shard(
            version=WeightVersionRef("version-a"),
            tensors="model-2",
        )
        second.publish()
        second.publish()
        method = trainer._runtime.method
        retained_owners = [
            staged.buffer_owner for staged in method.published["version-a"]
        ]
        trainer.release_version(version=WeightVersionRef("version-a"))
        trainer.release_version(version=WeightVersionRef("version-a"))
        assert "version-a" not in method.published
        with pytest.raises(grpc.RpcError) as released:
            worker_stub.GetWeightVersionShardManifest(
                refit_pb2.GetWeightVersionShardManifestRequest(
                    version_id="version-a",
                    source_slot_id="rank:0",
                )
            )
        assert released.value.code() is grpc.StatusCode.NOT_FOUND
    finally:
        if "trainer" in locals():
            trainer.close()
        server.stop(grace=None).wait()

    assert adapter.calls == [
        (
            "model",
            TrainerStagingMode.COPY_TO_DEVICE,
            WeightPayloadFormat.FULL_TENSOR,
        ),
        (
            "model-2",
            TrainerStagingMode.COPY_TO_DEVICE,
            WeightPayloadFormat.FULL_TENSOR,
        ),
    ]
    assert retained_owners == ["model", "model-2"]
    assert len(service.shards) == 2
    assert len(service.deleted_shards) == 1
    assert service.deleted_shards[0].source_slot_id == "rank:0"
    assert service.registrations["trainer-0"].role == refit_pb2.WORKER_ROLE_TRAINER
    assert "endpoint" not in refit_pb2.WorkerRegistration.DESCRIPTOR.fields_by_name
    assert service.shards[0].version_id == "version-a"
    assert service.shards[0].source_slot_id == "rank:0"
    assert service.shards[0].worker_id == "trainer-0"
    assert service.shards[0].tensor_count == 2
    assert service.shards[0].total_bytes == 128
    assert service.shards[0].manifest_endpoint == f"127.0.0.1:{port}"
    assert fetched.manifest == b"manifest"


def test_trainer_initialization_rejects_unspecified_fixed_settings(monkeypatch):
    monkeypatch.setenv("MX_WORKER_HOST", "trainer")
    with pytest.raises(ValueError, match="staging_mode must be specified"):
        ModelExpressTrainerClient.initialize(
            ModelExpressTrainerConfig(
                engine_context=FSDPTrainerContext(),
                model_name="test/model",
                staging_mode=TrainerStagingMode.UNSPECIFIED,
                payload_format=WeightPayloadFormat.FULL_TENSOR,
            )
        )

    with pytest.raises(ValueError, match="payload_format must be specified"):
        ModelExpressTrainerClient.initialize(
            ModelExpressTrainerConfig(
                engine_context=FSDPTrainerContext(),
                model_name="test/model",
                staging_mode=TrainerStagingMode.COPY_TO_DEVICE,
                payload_format=WeightPayloadFormat.UNSPECIFIED,
            )
        )


def test_trainer_initialization_rejects_adapter_unsupported_mode(monkeypatch):
    adapter = _Adapter()
    monkeypatch.setattr(
        runtime_module, "_create_trainer_adapter", lambda *_args, **_kwargs: adapter
    )
    monkeypatch.setenv("MX_WORKER_HOST", "trainer")
    resources = _patch_resources(
        monkeypatch,
        manager=_Manager(),
        manifest_service=object(),
        worker_endpoint="trainer:9000",
    )
    monkeypatch.setattr(
        ModelExpressTrainerClient, "_register_worker", lambda self: None
    )
    monkeypatch.setattr(client_module.threading.Thread, "start", lambda self: None)
    monkeypatch.setattr(client_module.threading.Thread, "join", lambda self: None)
    trainer = ModelExpressTrainerClient.initialize(
        ModelExpressTrainerConfig(
            engine_context=FSDPTrainerContext(),
            device_id=0,
            model_name="test/model",
            staging_mode=TrainerStagingMode.IN_PLACE,
            payload_format=WeightPayloadFormat.FULL_TENSOR,
        )
    )
    with pytest.raises(ValueError, match="does not support staging mode IN_PLACE"):
        _ = trainer.source_slot_id
    resources.close.assert_called_once_with()


def test_trainer_initialization_requires_explicit_engine_context(monkeypatch):
    monkeypatch.setenv("MX_WORKER_HOST", "trainer")
    resources = _patch_resources(
        monkeypatch,
        manager=_Manager(),
        manifest_service=object(),
        worker_endpoint="trainer:9000",
    )
    monkeypatch.setattr(
        ModelExpressTrainerClient, "_register_worker", lambda self: None
    )
    monkeypatch.setattr(client_module.threading.Thread, "start", lambda self: None)
    monkeypatch.setattr(client_module.threading.Thread, "join", lambda self: None)
    with pytest.raises(ValueError, match="engine_context is required"):
        ModelExpressTrainerClient.initialize(
            ModelExpressTrainerConfig(
                device_id=0,
                model_name="test/model",
                staging_mode=TrainerStagingMode.IN_PLACE,
                payload_format=WeightPayloadFormat.FULL_TENSOR,
            )
        )
    resources.close.assert_not_called()


def test_trainer_client_owns_default_transport_resources(monkeypatch):
    manager = MagicMock(listen_port=19002)
    resources = MagicMock(
        manager=manager,
        manifest_service=MagicMock(),
        worker_endpoint="trainer:19002",
    )
    adapter = _Adapter()
    adapter_factory = MagicMock(return_value=adapter)
    monkeypatch.setenv("MX_WORKER_HOST", "trainer")
    initialize_resources = MagicMock(return_value=resources)
    monkeypatch.setattr(
        runtime_module._TrainerResources,
        "initialize",
        initialize_resources,
    )
    monkeypatch.setattr(runtime_module, "_create_trainer_adapter", adapter_factory)
    monkeypatch.setattr(
        ModelExpressTrainerClient, "_register_worker", lambda self: None
    )
    monkeypatch.setattr(client_module.threading.Thread, "start", lambda self: None)
    monkeypatch.setattr(client_module.threading.Thread, "join", lambda self: None)

    trainer = ModelExpressTrainerClient.initialize(
        ModelExpressTrainerConfig(
            engine_context=FSDPTrainerContext(),
            model_name="test/model",
            device_id=2,
            agent_name="trainer-agent",
            staging_mode=TrainerStagingMode.COPY_TO_DEVICE,
            server_url="mx:8000",
        )
    )
    adapter_factory.assert_not_called()
    assert trainer.source_slot_id == "rank:0"
    assert len(adapter_factory.call_args.args) == 1
    assert isinstance(adapter_factory.call_args.args[0], FSDPTrainerContext)
    assert adapter_factory.call_args.kwargs == {
        "manager": manager,
        "nixl_metadata_endpoint": "trainer:19002",
    }
    initialize_resources.assert_called_once_with(
        device_id=2,
        agent_name="trainer-agent",
    )
    trainer.close()
    resources.close.assert_called_once_with()


def test_trainer_initialization_cleans_up_when_renewal_thread_cannot_start(
    monkeypatch,
):
    manager = MagicMock(listen_port=19002)
    resources = MagicMock(
        manager=manager,
        manifest_service=MagicMock(),
        worker_endpoint="trainer:19002",
    )
    monkeypatch.setenv("MX_WORKER_HOST", "trainer")
    monkeypatch.setattr(
        runtime_module,
        "_create_trainer_adapter",
        lambda *_args, **_kwargs: _Adapter(),
    )
    monkeypatch.setattr(
        runtime_module._TrainerResources,
        "initialize",
        MagicMock(return_value=resources),
    )
    monkeypatch.setattr(
        ModelExpressTrainerClient, "_register_worker", lambda self: None
    )
    monkeypatch.setattr(
        client_module.threading.Thread,
        "start",
        lambda _self: (_ for _ in ()).throw(RuntimeError("thread start failed")),
    )

    with pytest.raises(RuntimeError, match="thread start failed"):
        ModelExpressTrainerClient.initialize(
            ModelExpressTrainerConfig(
                engine_context=FSDPTrainerContext(),
                model_name="test/model",
                device_id=2,
                staging_mode=TrainerStagingMode.COPY_TO_DEVICE,
                server_url="mx:8000",
            )
        )

    resources.close.assert_called_once_with()