forked from Ascend/TransferQueue
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontroller.py
More file actions
2130 lines (1734 loc) · 88.5 KB
/
controller.py
File metadata and controls
2130 lines (1734 loc) · 88.5 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
# Copyright 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
# Copyright 2025 The TransferQueue Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import os
import time
from collections import defaultdict
from dataclasses import dataclass, field
from itertools import groupby
from operator import itemgetter
from threading import Lock, Thread
from typing import Any, Optional
from uuid import uuid4
import numpy as np
import ray
import torch
import zmq
from omegaconf import DictConfig
from torch import Tensor
from transfer_queue.metadata import (
BatchMeta,
)
from transfer_queue.sampler import BaseSampler, SequentialSampler
from transfer_queue.utils.enum_utils import TransferQueueRole
from transfer_queue.utils.logging_utils import get_logger
from transfer_queue.utils.perf_utils import IntervalPerfMonitor
from transfer_queue.utils.zmq_utils import (
ZMQMessage,
ZMQRequestType,
ZMQServerInfo,
create_zmq_socket,
format_zmq_address,
get_free_port,
get_node_ip_address_raw,
)
logger = get_logger(__name__)
TQ_CONTROLLER_GET_METADATA_TIMEOUT = int(os.environ.get("TQ_CONTROLLER_GET_METADATA_TIMEOUT", 1))
TQ_CONTROLLER_GET_METADATA_CHECK_INTERVAL = int(os.environ.get("TQ_CONTROLLER_GET_METADATA_CHECK_INTERVAL", 5))
# Sample pre-allocation for StreamingDataLoader compatibility.
# By pre-allocating sample indices (typically global_batch_size), consumers can accurately
# determine consumption status even before producers have generated the samples.
class PartitionIndexManager:
"""
Manages the mapping relationship between partitions and global indexes,
responsible for index allocation and reuse.
"""
def __init__(self):
# Records the set of global_indexes used by each partition
self.partition_to_indexes = defaultdict(set)
# Reusable global_index pool - stored using list
self.reusable_indexes = []
# Global index counter for allocating new indexes
self.global_index_counter = 0
# Track all active indexes
self.allocated_indexes = set()
def allocate_indexes(self, partition_id, count=1) -> list[int]:
"""
Allocate global_indexes for the specified partition.
Prioritizes obtaining from reusable pool, allocates new indexes when insufficient.
Args:
partition_id: Partition ID
count: Number of indexes needed
Returns:
list: List of allocated global_indexes
"""
if count <= 0:
raise ValueError(f"Number of indexes needed must be larger than 0, but got {count}")
indexes = []
# Get indexes from reusable pool
if self.reusable_indexes:
# Calculate number of indexes needed from reusable pool
num_reuse = min(count, len(self.reusable_indexes))
# Use slice operation to get multiple elements at once (FIFO principle)
indexes.extend(self.reusable_indexes[:num_reuse])
del self.reusable_indexes[:num_reuse]
# If reusable pool doesn't have enough indexes, allocate new ones
if len(indexes) < count:
# Ensure newly allocated indexes don't conflict with existing ones
needed = count - len(indexes)
# Batch allocate consecutive index ranges
start_index = self.global_index_counter
end_index = start_index + needed
# Directly generate consecutive index list
new_indexes = list(range(start_index, end_index))
# Batch update status
self.allocated_indexes.update(new_indexes)
self.global_index_counter = end_index
indexes.extend(new_indexes)
# Record partition-index relationship
self.partition_to_indexes[partition_id].update(indexes)
return indexes
def release_partition(self, partition_id) -> list[int]:
"""
Release all global_indexes of the specified partition, adding them to reusable pool.
Args:
partition_id: Partition ID
Returns:
list: List of released global_indexes
"""
if partition_id in self.partition_to_indexes:
indexes = self.partition_to_indexes.pop(partition_id)
# Add released indexes to reusable pool
self.reusable_indexes.extend(indexes)
# Remove these indexes from allocated_indexes
for idx in indexes:
self.allocated_indexes.discard(idx)
return list(indexes)
return []
def release_indexes(self, partition_id: str, indexes_to_release: list[int]):
"""
Release specific global_indexes for a partition, adding them to reusable pool.
Args:
partition_id: Partition ID
indexes_to_release: List of specific indexes to release
"""
if partition_id not in self.partition_to_indexes:
return []
partition_indexes = self.partition_to_indexes[partition_id]
if not set(indexes_to_release).issubset(partition_indexes):
raise ValueError("Some indexes to release do not belong to the specified partition.")
partition_indexes.difference_update(indexes_to_release)
self.reusable_indexes.extend(indexes_to_release)
self.allocated_indexes.difference_update(indexes_to_release)
# If partition has no more indexes, remove it from the mapping
if not partition_indexes:
self.partition_to_indexes.pop(partition_id, None)
def get_indexes_for_partition(self, partition_id) -> list[int]:
"""
Get all global_indexes for the specified partition.
Args:
partition_id: Partition ID
Returns:
list: List of global_indexes for this partition
"""
return list(self.partition_to_indexes.get(partition_id, set()).copy())
@dataclass
class FieldMeta:
"""
Single source of truth for one field's metadata in a partition.
Field-level attributes (dtype/shape/is_nested/is_non_tensor) are shared across all samples, O(1) storage.
Sample-level attributes (per_sample_shapes) are only needed for nested tensors,
indexed by global_idx, O(B_nested) storage.
"""
global_indexes: set[int] = field(default_factory=set)
dtype: Optional[Any] = None
shape: Optional[tuple] = None # None when is_nested=True
is_nested: Optional[bool] = None
is_non_tensor: Optional[bool] = None
per_sample_shapes: dict[int, tuple] = field(default_factory=dict) # {global_idx: shape}
# TODO: FieldMeta needs to be refactored to prevent these complicated and fragile logics
def update(self, incoming: dict[str, Any], incoming_global_indexes: list[int]) -> None:
"""Update this field's metadata from an incoming schema dict.
Encapsulates dtype consistency check, shape conflict detection,
and automatic is_nested inference.
Args:
incoming: Schema dict with optional keys:
global_indexes, dtype, shape, is_nested, is_non_tensor, per_sample_shapes
incoming_global_indexes: global indexes of the input meta
Raises:
ValueError: If incoming dtype conflicts with existing dtype.
"""
# dtype consistency check
new_dtype = incoming.get("dtype")
if new_dtype is not None:
if self.dtype is None:
self.dtype = new_dtype
elif self.dtype != new_dtype:
raise ValueError(
f"dtype mismatch: existing={self.dtype}, incoming={new_dtype}. "
f"All batches for the same field must have the same dtype."
)
new_is_nested = incoming.get("is_nested")
new_is_non_tensor = incoming.get("is_non_tensor")
if new_is_nested:
new_per_sample_shapes = incoming.get("per_sample_shapes", None)
if new_per_sample_shapes is None:
raise ValueError("Receiving a nested field without 'per_sample_shapes'!")
if self.is_nested is not None and not self.is_nested:
# new input is nested, but original is regular tensor.
# We need to write old shape into per_sample_shapes
assert self.shape is not None
for gi in self.global_indexes:
self.per_sample_shapes[gi] = self.shape
self.is_nested = True
self.shape = None
# Update newly provided per_sample_shapes
self.per_sample_shapes.update(new_per_sample_shapes)
else:
if not new_is_non_tensor:
# newly input is regular tensor
new_shape = incoming.get("shape", None)
if new_shape is None:
raise ValueError("Receiving a regular tensor without 'shape'!")
if self.is_nested:
# we need to update incoming shape into per_sample_shapes
for gi in incoming_global_indexes:
self.per_sample_shapes[gi] = new_shape
else:
if self.is_non_tensor is not None and not self.is_non_tensor:
# original data is also regular tensor
assert self.shape is not None
if self.shape != new_shape:
for gi in self.global_indexes:
self.per_sample_shapes[gi] = self.shape
for gi in incoming_global_indexes:
self.per_sample_shapes[gi] = new_shape
self.shape = None
self.is_nested = True
self.global_indexes.update(incoming_global_indexes)
def remove_samples(self, indexes: list[int]):
"""Remove sample-level data for the given indexes."""
for idx in indexes:
self.per_sample_shapes.pop(idx, None)
self.global_indexes.discard(idx)
# After removing samples, check if we can update is_nested and shape
if len(self.global_indexes) == 0:
# If no samples remain, fully reset field-level metadata.
self.is_nested = None
self.is_non_tensor = None
self.shape = None
self.dtype = None
self.per_sample_shapes.clear()
else:
if self.is_nested:
# Check if all remaining shapes are the same
remaining_shapes = set(
tuple(shape) if isinstance(shape, list) else shape for shape in self.per_sample_shapes.values()
)
if len(remaining_shapes) == 1:
# All remaining samples have the same shape - update to non-nested
self.is_nested = False
self.shape = next(iter(remaining_shapes))
# Clear per-sample shapes since we are no longer nested
self.per_sample_shapes.clear()
def to_batch_schema(self, batch_global_indexes: list[int]) -> dict[str, Any]:
"""Export as a BatchMeta.field_schema-compatible dict for generate_batch_meta."""
schema = {
"dtype": self.dtype,
"shape": self.shape,
"is_nested": self.is_nested,
"is_non_tensor": self.is_non_tensor,
}
if self.is_nested and self.per_sample_shapes:
schema["per_sample_shapes"] = [self.per_sample_shapes.get(gi) for gi in batch_global_indexes]
return schema
@dataclass
class DataPartitionStatus:
"""
Robust status information for a data partition with dynamic expansion support.
This class tracks the production and consumption status of data within a specific
partition (e.g., "train@global_batch_0", "inference@kv_cache_1") with full support
for dynamic row and column expansion.
"""
partition_id: str
created_at: float = field(default_factory=time.time)
# Production status tensor - dynamically expandable
# Values: 0 = not produced, 1 = ready for consumption
TQ_PRE_ALLOC_SAMPLE_NUM = int(os.environ.get("TQ_PRE_ALLOC_SAMPLE_NUM", 1))
production_status: Tensor = torch.zeros(TQ_PRE_ALLOC_SAMPLE_NUM, 1, dtype=torch.int8)
# Consumption status per task - task_name -> consumption_tensor
# Each tensor tracks which samples have been consumed by that task
consumption_status: dict[str, Tensor] = field(default_factory=dict)
# Global indexes
global_indexes: set[int] = field(
default_factory=set
) # set of global indexes that have been added to this partition
pre_allocated_global_indexes: set[int] = field(
default_factory=set
) # set of global indexes that pre-allocated, but not active in this partition
# Metadata
field_name_mapping: dict[str, int] = field(default_factory=dict) # field_name -> column_index
# O(F) columnar field metadata: field_name -> FieldMeta
field_metadata: dict[str, FieldMeta] = field(default_factory=dict)
field_custom_backend_meta: dict[int, dict[str, Any]] = field(
default_factory=dict
) # global_idx -> {field: custom_backend_meta}
# User-defined metadata that may not apply to field level
custom_meta: dict[int, dict[str, Any]] = field(default_factory=dict) # global_idx -> {}
# User-defined Keys
keys_mapping: dict[str, int] = field(default_factory=dict) # key -> global_idx
revert_keys_mapping: dict[int, str] = field(default_factory=dict) # global_idx -> key
# Threading lock for concurrency control; only for preventing mask operation error when expanding production_status.
# No need to strictly lock for every read/write operation since freshness is not critical.
data_status_lock: Lock = field(default_factory=Lock)
# Dynamic configuration - these are computed from the current state
@property
def total_samples_num(self) -> int:
"""Current number of samples in the partition."""
return len(self.global_indexes)
@property
def total_fields_num(self) -> int:
"""Current number of fields (columns) in the partition."""
return len(self.field_name_mapping)
@property
def allocated_fields_num(self) -> int:
"""Current number of allocated columns in the tensor."""
return self.production_status.shape[1]
@property
def allocated_samples_num(self) -> int:
"""Current number of allocated rows in the tensor."""
return self.production_status.shape[0]
# ==================== Index Pre-Allocation Methods ====================
def register_pre_allocated_indexes(self, allocated_indexes: list[int]):
"""
Register pre-allocated sample indexes to this partition.
These indexes are reserved before actual data production, allowing consumers
to see the expected total sample count via get_consumption_status even when
producers haven't generated all samples yet.
Args:
allocated_indexes: List of global indexes to pre-allocate
"""
if len(allocated_indexes) < 1:
logger.info("Trying to pre-allocate global_indexes with empty list!")
return
self.pre_allocated_global_indexes.update(allocated_indexes)
# Expand the state matrices
max_sample_idx = max(allocated_indexes)
required_samples = max_sample_idx + 1
with self.data_status_lock:
self.ensure_samples_capacity(required_samples)
logger.debug(f"Pre-allocated indexes in {self.partition_id}: {allocated_indexes}")
def activate_pre_allocated_indexes(self, sample_num: int) -> list[int]:
"""
Activate and retrieve pre-allocated indexes for use in data insertion.
This method consumes pre-allocated indexes and marks them as active in global_indexes.
If pre-allocated indexes are insufficient, returns all available ones.
Args:
sample_num: Number of indexes needed
Returns:
List of retrieved global indexes
"""
available_indexes = len(self.pre_allocated_global_indexes)
if available_indexes < sample_num:
global_index_to_allocate = list(self.pre_allocated_global_indexes)
logger.debug(
f"Not enough pre-allocated indexes in partition {self.partition_id}. "
f"Returning {available_indexes} of {sample_num} requested."
)
else:
global_index_to_allocate = list(sorted(self.pre_allocated_global_indexes))[:sample_num]
self.global_indexes.update(global_index_to_allocate)
self.pre_allocated_global_indexes.difference_update(set(global_index_to_allocate))
return global_index_to_allocate
# ==================== Dynamic Expansion Methods ====================
def ensure_samples_capacity(self, required_samples: int) -> None:
"""
Ensure the production status tensor has enough rows for the required samples.
Args:
required_samples: Minimum number of samples needed
"""
current_sample_space = self.allocated_samples_num
if required_samples > current_sample_space:
# Expand rows
expansion_needed = required_samples - current_sample_space
new_samples = current_sample_space + expansion_needed
new_fields = self.production_status.shape[1]
expanded_tensor = torch.zeros(new_samples, new_fields, dtype=torch.int8)
expanded_tensor[:current_sample_space, :] = self.production_status
self.production_status = expanded_tensor
# Update consumption tensors for all tasks
for task_name, consumption_tensor in self.consumption_status.items():
expanded_consumption = torch.zeros(new_samples, dtype=torch.int8)
expanded_consumption[:current_sample_space] = consumption_tensor
self.consumption_status[task_name] = expanded_consumption
logger.debug(f"Expanded partition {self.partition_id} from {current_sample_space} to {new_samples} samples")
def ensure_fields_capacity(self, required_fields: int) -> None:
"""
Ensure the production status tensor has enough columns for the required fields.
Args:
required_fields: Minimum number of fields needed
"""
current_fields = self.production_status.shape[1]
if required_fields > current_fields:
# Expand columns
expansion_needed = required_fields - current_fields
new_fields = current_fields + expansion_needed
new_samples = self.production_status.shape[0]
expanded_tensor = torch.zeros(new_samples, new_fields, dtype=torch.int8)
expanded_tensor[:, :current_fields] = self.production_status
self.production_status = expanded_tensor
logger.debug(f"Expanded partition {self.partition_id} from {current_fields} to {new_fields} fields")
# ==================== Production Status Interface ====================
def update_production_status(
self,
global_indices: list[int],
field_names: list[str],
field_schema: dict[str, dict[str, Any]],
custom_backend_meta: Optional[dict[int, dict[str, Any]]] = None,
) -> bool:
"""
Update production status for specific samples and fields.
Handles dynamic expansion of both samples and fields.
Note: field_names is derived from field_schema.keys() internally.
The parameter is kept for backward compatibility but ignored;
callers should ensure field_schema contains all intended fields.
Args:
global_indices: List of sample indices to update
field_names: List of field names (ignored; derived from field_schema.keys())
field_schema: Columnar field schema {field_name: {dtype, shape, is_nested, ...}}
custom_backend_meta: Optional per-sample per-field
custom metadata provided by storage backend
Returns:
True if update was successful, False on error
"""
try:
# Derive field_names from field_schema to guarantee consistency
field_names = list(field_schema.keys())
# Determine required capacity
max_sample_idx = max(global_indices) if global_indices else -1
required_samples = max_sample_idx + 1
with self.data_status_lock:
# Ensure we have enough rows
self.ensure_samples_capacity(required_samples)
# Register new fields if needed
new_fields = [f for f in field_names if f not in self.field_name_mapping]
if new_fields:
# Add new fields to mapping
for f in new_fields:
self.field_name_mapping[f] = len(self.field_name_mapping)
required_fields = len(self.field_name_mapping)
with self.data_status_lock:
self.ensure_fields_capacity(required_fields)
with self.data_status_lock:
# Update production status
if self.production_status is not None and global_indices and field_names:
field_indices = [self.field_name_mapping.get(f) for f in field_names]
self.production_status[torch.tensor(global_indices)[:, None], torch.tensor(field_indices)] = 1
# Update field metadata
self._update_field_metadata(global_indices, field_schema, custom_backend_meta)
# Save these global_indexes
self.global_indexes.update(global_indices)
return True
except Exception as e:
logger.error(f"Error updating production status for partition {self.partition_id}: {e}")
return False
def _update_field_metadata(
self,
global_indexes: list[int],
field_schema: dict[str, dict[str, Any]],
custom_backend_meta: Optional[dict[int, dict[str, Any]]] = None,
):
"""Update field metadata from columnar field_schema."""
if not global_indexes:
return
for field_name, meta in field_schema.items():
if field_name not in self.field_metadata:
self.field_metadata[field_name] = FieldMeta(
global_indexes=set(global_indexes),
dtype=meta.get("dtype"),
shape=meta.get("shape"),
is_nested=meta.get("is_nested", False),
is_non_tensor=meta.get("is_non_tensor", False),
per_sample_shapes=meta.get("per_sample_shapes", {}),
)
else:
self.field_metadata[field_name].update(meta, global_indexes)
# custom_backend_meta remains row-oriented storage
if custom_backend_meta:
for global_idx, per_field_meta in custom_backend_meta.items():
if global_idx not in self.field_custom_backend_meta:
self.field_custom_backend_meta[global_idx] = {}
self.field_custom_backend_meta[global_idx].update(per_field_meta)
def mark_consumed(self, task_name: str, global_indices: list[int]):
"""
Mark specific samples as consumed by a task.
Args:
task_name: Name of the consumer task
global_indices: List of sample indices to mark as consumed
"""
try:
_, consumption_status = self.get_consumption_status(task_name, mask=False)
if consumption_status.numel() > 0 and global_indices:
consumption_status[global_indices] = 1
except Exception as e:
logger.error(
f"Error marking samples consumed for partition {self.partition_id}, task {task_name}: {e}. "
f"Target global_indices {global_indices}, but current consumption_status has "
f"shape {consumption_status.shape}"
)
# ==================== Consumption Status Interface ====================
def get_consumption_status(self, task_name: str, mask: bool = False) -> tuple[Tensor, Tensor]:
"""
Get or create consumption status for a specific task.
Handles dynamic expansion when new samples are added.
Args:
task_name: Name of the consumer task
mask: Whether to return only the status for current partition samples
Returns:
Tuple of:
- Partition global index tensor
- Consumption status tensor for the specified task. 1 for consumed, 0 for not consumed.
"""
if task_name not in self.consumption_status:
if self.production_status is not None:
self.consumption_status[task_name] = torch.zeros(self.allocated_samples_num, dtype=torch.int8)
else:
self.consumption_status[task_name] = torch.zeros(0, dtype=torch.int8)
# Get consumption status for requested task
partition_global_index = torch.tensor(
sorted(self.global_indexes | self.pre_allocated_global_indexes), dtype=torch.long
)
if mask:
if partition_global_index.numel() == 0:
empty_status = self.consumption_status[task_name].new_zeros(0)
return partition_global_index, empty_status
with self.data_status_lock:
self.ensure_samples_capacity(max(partition_global_index) + 1)
consumption_status = self.consumption_status[task_name][partition_global_index]
else:
consumption_status = self.consumption_status[task_name]
return partition_global_index, consumption_status
def reset_consumption(self, task_name: Optional[str] = None):
"""
Reset consumption status for a specific task or all tasks.
This allows the same data to be re-consumed without clearing the actual data.
Useful for debugging scenarios where the same rollout data needs to be
trained multiple times.
Args:
task_name: Name of the task to reset consumption for.
If None, resets consumption status for all tasks.
"""
if task_name is not None:
# Reset specific task
if task_name in self.consumption_status:
self.consumption_status[task_name].zero_()
logger.debug(f"Reset consumption status for task '{task_name}' in partition {self.partition_id}")
else:
# Reset all tasks
for name, status_tensor in self.consumption_status.items():
status_tensor.zero_()
logger.debug(f"Reset consumption status for all tasks in partition {self.partition_id}")
# ==================== Production Status Interface ====================
def get_production_status_for_fields(
self, field_names: list[str], mask: bool = False
) -> tuple[Optional[Tensor], Optional[Tensor]]:
"""
Check if all samples for specified fields are fully produced and ready.
Args:
field_names: List of field names to check production status for
mask: Whether to return only the status for current partition samples
Returns:
Tuple of:
- Partition global index tensor
- Production status tensor for the specified task. 1 for ready, 0 for not ready.
"""
if field_names is None or len(field_names) == 0:
return None, None
# Check if all requested fields are registered
for field_name in field_names:
if field_name not in self.field_name_mapping:
return None, None
# Create column mask for requested fields
col_mask = torch.zeros(self.allocated_fields_num, dtype=torch.bool)
field_indices = [self.field_name_mapping[field] for field in field_names]
if field_indices:
col_mask[field_indices] = True
production_status = self.production_status[:, col_mask]
partition_global_index = torch.tensor(
sorted(self.global_indexes | self.pre_allocated_global_indexes), dtype=torch.long
)
if mask:
production_status = production_status[partition_global_index]
return partition_global_index, production_status
# ==================== Data Scanning and Query Methods ====================
def scan_data_status(self, field_names: list[str], task_name: str) -> list[int]:
"""
Scan data status to find samples ready for consumption.
This replaces the original _scan_data_status functionality.
Args:
field_names: List of required field names
task_name: Name of the consumer task
Returns:
List of sample indices that are ready for consumption
"""
# Check if all requested fields are registered
for field_name in field_names:
if field_name not in self.field_name_mapping:
return []
with self.data_status_lock:
row_mask = torch.ones(self.allocated_samples_num, dtype=torch.bool)
# Apply consumption filter (exclude already consumed samples)
_, consumption_status = self.get_consumption_status(task_name, mask=False)
if consumption_status is not None:
unconsumed_mask = consumption_status == 0
row_mask &= unconsumed_mask
# Create column mask for requested fields
col_mask = torch.zeros(self.allocated_fields_num, dtype=torch.bool)
field_indices = [self.field_name_mapping[field] for field in field_names]
if field_indices:
col_mask[field_indices] = True
# Filter production status by masks
relevant_status = self.production_status[row_mask][:, col_mask]
# Check if all required fields are ready for each sample
all_fields_ready = torch.all(relevant_status, dim=1)
ready_indices_in_filtered = torch.nonzero(all_fields_ready, as_tuple=False).flatten()
# Map back to original sample indices
all_indices = torch.where(row_mask)[0]
ready_sample_indices = all_indices[ready_indices_in_filtered].tolist()
return ready_sample_indices
# ==================== Metadata Methods ====================
def get_field_schema(
self, field_names: list[str], batch_global_indexes: list[int] | None = None
) -> dict[str, dict[str, Any]]:
"""Return field_schema from the FieldMeta store."""
gi = batch_global_indexes or []
return {f: self.field_metadata[f].to_batch_schema(gi) for f in field_names if f in self.field_metadata}
def get_field_custom_backend_meta(
self, global_indices: list[int], field_names: list[str]
) -> dict[int, dict[str, Any]]:
"""
Get custom_backend_meta for multiple samples and fields.
This method retrieves backend-specific metadata stored at per-sample per-field level.
The returned dictionary maps global_index to a dictionary of field_name to metadata.
Args:
global_indices: List of global sample indices to retrieve metadata for
field_names: List of field names to filter by. Only metadata for these
fields will be included in the result.
Returns:
Dictionary mapping global_index to field-name-to-metadata mapping.
Only includes indices that have custom_backend_meta set.
Example:
>>> partition.get_field_custom_backend_meta([0, 1], ["field_a", "field_b"])
{0: {'field_a': {'meta1': 'xxx'}, 'field_b': {'meta1': 'xxx'}}, 1: {...}}
"""
return {
idx: {f: v for f, v in self.field_custom_backend_meta[idx].items() if f in field_names}
for idx in global_indices
if idx in self.field_custom_backend_meta
}
def get_custom_meta(self, global_indices: list[int]) -> dict[int, dict]:
"""
Get custom_meta for multiple samples.
This method retrieves user-defined per-sample metadata.
Args:
global_indices: List of global sample indices to retrieve metadata for
Returns:
Dictionary mapping global_index to custom metadata dict.
Only includes indices that have custom_meta set.
Example:
>>> partition.get_custom_meta([0, 2])
{0: {'score': 0.9}, 2: {'label': 'positive'}}
"""
return {idx: self.custom_meta[idx] for idx in global_indices if idx in self.custom_meta}
def set_custom_meta(self, custom_meta: dict[int, dict]) -> None:
"""
Set custom_meta for multiple samples.
This method sets or updates user-defined per-sample metadata.
Args:
custom_meta: Dictionary mapping global_index to custom metadata dict.
Existing entries will be overwritten.
"""
self.custom_meta.update(custom_meta)
# ==================== Statistics and Monitoring ====================
def get_statistics(self) -> dict[str, Any]:
"""Get detailed statistics for this partition."""
stats = {
"partition_id": self.partition_id,
"created_at": self.created_at,
"total_samples_num": self.total_samples_num,
"total_fields_num": self.total_fields_num,
"allocated_samples_num": self.allocated_samples_num,
"allocated_fields_num": self.allocated_fields_num,
"registered_tasks": list(self.consumption_status.keys()),
}
if self.production_status is not None:
produced_samples = torch.any(self.production_status == 1, dim=1).sum().item()
stats["produced_samples"] = produced_samples
stats["production_progress"] = (
produced_samples / self.total_samples_num if self.total_samples_num > 0 else 0
)
# Field-wise production statistics
field_stats = {}
for field_name, field_idx in self.field_name_mapping.items():
field_produced = (self.production_status[:, field_idx] == 1).sum().item()
field_stats[field_name] = {
"produced_samples": field_produced,
"production_progress": (
field_produced / self.total_samples_num if self.total_samples_num > 0 else 0
),
}
stats["field_statistics"] = field_stats
# Consumption statistics per task
consumption_stats = {}
for task_name, consumption_tensor in self.consumption_status.items():
consumed_samples = (consumption_tensor == 1).sum().item()
consumption_stats[task_name] = {
"consumed_samples": consumed_samples,
"consumption_progress": (
consumed_samples / self.total_samples_num if self.total_samples_num > 0 else 0
),
}
stats["consumption_statistics"] = consumption_stats
return stats
# ==================== Serialization ====================
def to_snapshot(self):
"""
Get a snapshot of partition status information.
Returns:
DataPartitionStatus object without threading.Lock()
"""
def _perform_copy():
cls = self.__class__
snapshot = cls.__new__(cls)
for name, value in self.__dict__.items():
if name == "data_status_lock":
continue
if isinstance(value, Tensor):
new_val = value.clone().detach()
else:
new_val = copy.deepcopy(value)
setattr(snapshot, name, new_val)
return snapshot
lock_obj = getattr(self, "data_status_lock", None)
if lock_obj:
with lock_obj:
return _perform_copy()
else:
return _perform_copy()
def clear_data(self, indexes_to_release: list[int], clear_consumption: bool = True):
"""Clear all production and optionally consumption data for given global_indexes."""
try:
if self.production_status is not None:
self.production_status[indexes_to_release, :] = 0
if clear_consumption:
for consumption_tensor in self.consumption_status.values():
consumption_tensor[indexes_to_release] = 0
self.global_indexes.difference_update(indexes_to_release)
empty_fields = []
for field_name, field_meta in self.field_metadata.items():
field_meta.remove_samples(indexes_to_release)
if len(field_meta.global_indexes) == 0:
empty_fields.append(field_name)
if len(self.global_indexes) == 0:
# clear the whole field_meta if the whole partition is empty
self.field_metadata.clear()
else:
# only clear empty fields
for field_name in empty_fields:
self.field_metadata.pop(field_name)
for idx in indexes_to_release:
self.field_custom_backend_meta.pop(idx, None)
self.custom_meta.pop(idx, None)
if idx in self.revert_keys_mapping:
self.keys_mapping.pop(self.revert_keys_mapping[idx], None)
self.revert_keys_mapping.pop(idx, None)
except Exception as e:
logger.error(
f"Error clearing data for partition {self.partition_id}: {e}. "
f"Attempted to clear global_indexes: {indexes_to_release}"
)
def kv_retrieve_indexes(self, keys: list[str]) -> list[int | None]:
"""Translate the user-specified keys to global_indexes"""
global_indexes = [self.keys_mapping.get(k, None) for k in keys]
return global_indexes
def kv_retrieve_keys(self, global_indexes: list[int]) -> list[str | None]:
"""Translate the global_indexes to keys"""
keys = [self.revert_keys_mapping.get(idx, None) for idx in global_indexes]
return keys
@ray.remote(num_cpus=1)
class TransferQueueController:
"""
TransferQueue Controller with partition-based data management.
This refactored controller manages data through dynamic partitions instead of
fixed global batches. Each partition represents a logical data container
(e.g., "train@global_batch_0", "inference@kv_cache_1") that can be created
on-demand and managed independently.
Key improvements:
- Dynamic partition creation on-demand
- No dependency on training-specific parameters (global_batch_size, etc.)
- Support for diverse use cases (KV cache migration, model resharding, etc.)
- Flexible data organization through partition-based addressing
"""
def __init__(
self,
sampler: BaseSampler | type[BaseSampler] = SequentialSampler,
polling_mode: bool = False,
) -> None:
"""Initialize the TransferQueue Controller.
Args:
sampler: Sampler instance or sampler class to use for data sampling.
- If a BaseSampler instance is provided, it will be used directly
- If a BaseSampler subclass is provided, it will be instantiated
- Defaults to SequentialSampler for simple sequential sampling
- Example: sampler=GRPOGroupNSampler() (instance)
- Example: sampler=SequentialSampler (class)
polling_mode: Whether to use polling mode for TransferQueue controller.
- If False, the controller will raise an error when no enough data is available.
- If True, the controller will return an empty BatchMeta when no enough data is available.
The user side is responsible for handling this empty case (retrying later).
"""
if isinstance(sampler, BaseSampler):
self.sampler = sampler
elif isinstance(sampler, type) and issubclass(sampler, BaseSampler):