FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
TransferQueue/transfer_queue/controller.py at dev · TransferQueue/TransferQueue · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
This repository was archived by the owner on Jan 21, 2026. It is now read-only.
TransferQueue
/
TransferQueue
Public archive
Notifications
You must be signed in to change notification settings
Fork
1
Star
15
Code
Issues
5
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
TransferQueue
/
transfer_queue
/
controller.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1422 lines (1147 loc) · 57.6 KB
Breadcrumbs
TransferQueue
/
transfer_queue
/
controller.py
Copy path
File metadata and controls
1422 lines (1147 loc) · 57.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
logging
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
ray
import
torch
import
zmq
from
ray
.
util
import
get_node_ip_address
from
transfer_queue
.
metadata
import
(
BatchMeta
,
FieldMeta
,
SampleMeta
,
)
from
transfer_queue
.
sampler
import
BaseSampler
,
SequentialSampler
from
transfer_queue
.
utils
.
perf_utils
import
IntervalPerfMonitor
from
transfer_queue
.
utils
.
utils
import
(
ProductionStatus
,
TransferQueueRole
,
)
from
transfer_queue
.
utils
.
zmq_utils
import
(
ZMQMessage
,
ZMQRequestType
,
ZMQServerInfo
,
create_zmq_socket
,
get_free_port
,
)
logger
=
logging
.
getLogger
(
__name__
)
logger
.
setLevel
(
os
.
getenv
(
"TQ_LOGGING_LEVEL"
,
logging
.
WARNING
))
# Ensure logger has a handler (for Ray Actor subprocess)
if
not
logger
.
hasHandlers
():
handler
=
logging
.
StreamHandler
()
handler
.
setFormatter
(
logging
.
Formatter
(
"%(asctime)s - %(levelname)s - %(name)s - %(message)s"
))
logger
.
addHandler
(
handler
)
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"
,
0.2
))
TQ_CONTROLLER_CONNECTION_CHECK_INTERVAL
=
int
(
os
.
environ
.
get
(
"TQ_CONTROLLER_CONNECTION_CHECK_INTERVAL"
,
2
))
TQ_INIT_SAMPLE_NUM
=
int
(
os
.
environ
.
get
(
"TQ_INIT_SAMPLE_NUM"
,
1
))
# Initial number of samples
TQ_INIT_FIELD_NUM
=
int
(
os
.
environ
.
get
(
"TQ_INIT_FIELD_NUM"
,
1
))
# Expansion configuration - Unified approach using minimum expansion sizes
TQ_SAMPLE_MIN_EXPANSION_SIZE
=
int
(
os
.
environ
.
get
(
"TQ_SAMPLE_MIN_EXPANSION_SIZE"
,
1
)
)
# Minimum expansion size for samples (rows)
TQ_FIELD_MIN_EXPANSION_SIZE
=
int
(
os
.
environ
.
get
(
"TQ_FIELD_MIN_EXPANSION_SIZE"
,
1
)
)
# Minimum expansion size for fields (columns)
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
:
"""
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
)
->
set
[
int
]:
"""
Get all global_indexes for the specified partition.
Args:
partition_id: Partition ID
Returns:
set: Set of global_indexes for this partition
"""
return
self
.
partition_to_indexes
.
get
(
partition_id
,
set
()).
copy
()
@
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
production_status
:
Optional
[
torch
.
Tensor
]
=
torch
.
zeros
(
TQ_INIT_SAMPLE_NUM
,
TQ_INIT_FIELD_NUM
,
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
,
torch
.
Tensor
]
=
field
(
default_factory
=
dict
)
# Sample metadata
global_indexes
:
set
[
int
]
=
field
(
default_factory
=
set
)
# set of global indexes that have been added to this partition
# Field metadata
field_name_mapping
:
dict
[
str
,
int
]
=
field
(
default_factory
=
dict
)
# field_name -> column_index
field_dtypes
:
dict
[
int
,
dict
[
str
,
Any
]]
=
field
(
default_factory
=
dict
)
# global_idx -> {field: dtype}
field_shapes
:
dict
[
int
,
dict
[
str
,
Any
]]
=
field
(
default_factory
=
dict
)
# global_idx -> {field: shape}
# 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
]
if
self
.
production_status
is
not
None
else
0
@
property
def
allocated_samples_num
(
self
)
->
int
:
"""Current number of allocated rows in the tensor."""
return
self
.
production_status
.
shape
[
0
]
if
self
.
production_status
is
not
None
else
0
# ==================== Dynamic Expansion Methods ====================
def
ensure_samples_capacity
(
self
,
required_samples
:
int
)
->
bool
:
"""
Ensure the production status tensor has enough rows for the required samples.
Dynamically expands if needed using unified minimum expansion size.
Args:
required_samples: Minimum number of samples needed
"""
current_sample_space
=
self
.
allocated_samples_num
if
required_samples
>
current_sample_space
:
# Expand rows using minimum expansion size for predictable memory usage
expansion_needed
=
required_samples
-
current_sample_space
min_expansion
=
max
(
TQ_SAMPLE_MIN_EXPANSION_SIZE
,
expansion_needed
)
new_samples
=
current_sample_space
+
min_expansion
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
}
"
f"to
{
new_samples
}
samples (added
{
min_expansion
}
samples)"
)
def
ensure_fields_capacity
(
self
,
required_fields
:
int
):
"""
Ensure the production status tensor has enough columns for the required fields.
Dynamically expands if needed using unified minimum expansion size.
Args:
required_fields: Minimum number of fields needed
"""
if
self
.
production_status
is
None
:
# Will be initialized when samples are added
return
current_fields
=
self
.
production_status
.
shape
[
1
]
if
required_fields
>
current_fields
:
# Expand columns using minimum expansion size for predictable memory usage
expansion_needed
=
required_fields
-
current_fields
min_expansion
=
max
(
TQ_FIELD_MIN_EXPANSION_SIZE
,
expansion_needed
)
new_fields
=
current_fields
+
min_expansion
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
}
"
f"to
{
new_fields
}
fields (added
{
min_expansion
}
fields)"
)
# ==================== Production Status Interface ====================
def
update_production_status
(
self
,
global_indices
:
list
[
int
],
field_names
:
list
[
str
],
dtypes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
shapes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
)
->
bool
:
"""
Update production status for specific samples and fields.
Handles dynamic expansion of both samples and fields.
Args:
global_indices: List of sample indices to update
field_names: List of field names to mark as produced
dtypes: Optional per-sample field dtype information
shapes: Optional per-sample field shape information
Returns:
True if update was successful, False on error
"""
try
:
# Determine required capacity
max_sample_idx
=
max
(
global_indices
)
if
global_indices
else
-
1
required_samples
=
max_sample_idx
+
1
# Ensure we have enough rows
with
self
.
data_status_lock
:
self
.
ensure_samples_capacity
(
required_samples
)
# Register new fields if needed
new_fields
=
[
field
for
field
in
field_names
if
field
not
in
self
.
field_name_mapping
]
if
new_fields
:
# Add new fields to mapping
for
field
in
new_fields
:
self
.
field_name_mapping
[
field
]
=
len
(
self
.
field_name_mapping
)
required_fields
=
len
(
self
.
field_name_mapping
)
with
self
.
data_status_lock
:
self
.
ensure_fields_capacity
(
required_fields
)
# Update production status
if
self
.
production_status
is
not
None
and
global_indices
and
field_names
:
field_indices
=
[
self
.
field_name_mapping
.
get
(
field
)
for
field
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
,
dtypes
,
shapes
)
# 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_indices
:
list
[
int
],
dtypes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
shapes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
):
"""Update field dtype and shape metadata."""
if
not
global_indices
:
return
assert
len
(
global_indices
)
==
len
(
dtypes
),
"`global_indices` and `dtypes` length mismatch."
assert
len
(
global_indices
)
==
len
(
shapes
),
"`global_indices` and `shapes` length mismatch."
dtype_value
=
itemgetter
(
*
global_indices
)(
dtypes
)
if
dtypes
else
None
shape_value
=
itemgetter
(
*
global_indices
)(
shapes
)
if
shapes
else
None
if
not
isinstance
(
dtype_value
,
tuple
):
dtype_value
=
(
dtype_value
,)
if
not
isinstance
(
shape_value
,
tuple
):
shape_value
=
(
shape_value
,)
for
i
,
global_idx
in
enumerate
(
global_indices
):
if
global_idx
not
in
self
.
field_dtypes
:
self
.
field_dtypes
[
global_idx
]
=
{}
if
global_idx
not
in
self
.
field_shapes
:
self
.
field_shapes
[
global_idx
]
=
{}
if
dtype_value
is
not
None
:
self
.
field_dtypes
[
global_idx
].
update
(
dtype_value
[
i
])
if
shape_value
is
not
None
:
self
.
field_shapes
[
global_idx
].
update
(
shape_value
[
i
])
# ==================== Consumption Status Interface ====================
def
get_consumption_status
(
self
,
task_name
:
str
)
->
torch
.
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
Returns:
Consumption status tensor for the specified task
"""
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
)
return
self
.
consumption_status
[
task_name
]
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
)
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
}
"
)
def
get_production_status_for_fields
(
self
,
field_names
:
list
[
str
])
->
bool
:
"""
Check if all samples for specified fields are fully produced and ready.
Args:
field_names: List of field names to check production status for
Returns:
bool: True if all samples have been produced for all specified fields, False otherwise
"""
if
self
.
production_status
is
None
or
field_names
is
None
or
len
(
field_names
)
==
0
:
return
False
# Check if all requested fields are registered
for
field_name
in
field_names
:
if
field_name
not
in
self
.
field_name_mapping
:
return
False
# 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
# Get production status for requested fields
relevant_status
=
self
.
production_status
[:,
col_mask
]
# Check if all samples have all requested fields produced (all values are 1)
all_fields_produced
=
torch
.
all
(
relevant_status
==
1
).
item
()
return
all_fields_produced
# ==================== 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
"""
if
self
.
production_status
is
None
:
return
[]
# 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
)
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
# ==================== Field Metadata Methods ====================
def
get_field_dtype
(
self
,
global_index
:
int
,
field_name
:
str
)
->
Optional
[
Any
]:
"""Get dtype for a specific sample and field."""
return
self
.
field_dtypes
.
get
(
global_index
, {}).
get
(
field_name
)
def
get_field_shape
(
self
,
global_index
:
int
,
field_name
:
str
)
->
Optional
[
Any
]:
"""Get shape for a specific sample and field."""
return
self
.
field_shapes
.
get
(
global_index
, {}).
get
(
field_name
)
# ==================== 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
,
torch
.
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
)
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
}
"
)
@
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=GRPOGroupNSampler (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
):
self
.
sampler
=
sampler
()
else
:
raise
TypeError
(
f"sampler
{
getattr
(
sampler
,
'__name__'
,
repr
(
sampler
))
}
must be an instance or subclass of BaseSampler"
)
self
.
controller_id
=
f"TQ_CONTROLLER_
{
uuid4
().
hex
[:
8
]
}
"
self
.
polling_mode
=
polling_mode
# Initialize ZMQ sockets for communication
self
.
_init_zmq_socket
()
# Partition management
self
.
partitions
:
dict
[
str
,
DataPartitionStatus
]
=
{}
# partition_id -> DataPartitionStatus
# Partition-GlobalIndex management
self
.
index_manager
=
PartitionIndexManager
()
# partition_id -> global_indexes
# Connected storage managers tracking
self
.
_connected_storage_managers
:
set
[
str
]
=
set
()
# Start background processing threads
self
.
_start_process_handshake
()
self
.
_start_process_update_data_status
()
self
.
_start_process_request
()
logger
.
info
(
f"TransferQueue Controller
{
self
.
controller_id
}
initialized"
)
# ==================== Partition Management API ====================
def
create_partition
(
self
,
partition_id
:
str
)
->
bool
:
"""
Create a new data partition.
Note: Partitions now dynamically expand as needed, so initial capacity is not required.
Args:
partition_id: Unique identifier for the partition (e.g., "train@global_batch_0")
Returns:
True if partition was created successfully, False if it already exists
"""
if
partition_id
in
self
.
partitions
:
logger
.
warning
(
f"Partition
{
partition_id
}
already exists"
)
return
False
self
.
partitions
[
partition_id
]
=
DataPartitionStatus
(
partition_id
=
partition_id
)
logger
.
info
(
f"Created partition
{
partition_id
}
"
)
return
True
def
_get_partition
(
self
,
partition_id
:
str
)
->
Optional
[
DataPartitionStatus
]:
"""
Get partition status information.
Args:
partition_id: ID of the partition to retrieve
Returns:
DataPartitionStatus object if partition exists, None otherwise
"""
return
self
.
partitions
.
get
(
partition_id
)
def
get_partition_snapshot
(
self
,
partition_id
:
str
)
->
Optional
[
DataPartitionStatus
]:
"""
Get a copy of partition status information, without threading.Lock().
Args:
partition_id: ID of the partition to retrieve
Returns:
DataPartitionStatus object if partition exists, None otherwise
"""
partition
=
self
.
_get_partition
(
partition_id
)
if
partition
is
None
:
return
None
return
partition
.
to_snapshot
()
def
list_partitions
(
self
)
->
list
[
str
]:
"""
List all available partition IDs.
Returns:
List of partition IDs
"""
return
list
(
self
.
partitions
.
keys
())
# ==================== Partition Index Management API ====================
def
get_partition_index_range
(
self
,
partition
:
DataPartitionStatus
)
->
set
:
"""
Get all indexes for a specific partition.
Args:
partition: Partition identifier
Returns:
Set of indexes allocated to the partition
"""
return
self
.
index_manager
.
get_indexes_for_partition
(
partition
)
# ==================== Data Production API ====================
# TODO: Modify dtypes & shapes to be required
def
update_production_status
(
self
,
partition_id
:
str
,
global_indexes
:
list
[
int
],
field_names
:
list
[
str
],
dtypes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
shapes
:
Optional
[
dict
[
int
,
dict
[
str
,
Any
]]],
)
->
bool
:
"""
Update production status for specific samples and fields in a partition.
Delegates to the partition's own update_production_status method.
Args:
partition_id: ID of the partition
global_indexes: List of sample indices to update
field_names: List of field names to mark as produced
dtypes: Optional per-sample field dtype information
shapes: Optional per-sample field shape information
Returns:
True if update was successful, False otherwise
"""
partition
=
self
.
_get_partition
(
partition_id
)
if
not
partition
:
logger
.
error
(
f"Partition
{
partition_id
}
not found"
)
return
False
success
=
partition
.
update_production_status
(
global_indexes
,
field_names
,
dtypes
,
shapes
)
if
success
:
logger
.
debug
(
f"[
{
self
.
controller_id
}
]: Updated production status for partition
{
partition_id
}
: "
f"samples=
{
global_indexes
}
, fields=
{
field_names
}
"
)
return
success
# ==================== Data Consumption API ====================
def
get_consumption_status
(
self
,
partition_id
:
str
,
task_name
:
str
)
->
Optional
[
torch
.
Tensor
]:
"""
Get or create consumption status for a specific task and partition.
Delegates to the partition's own method.
Args:
partition_id: ID of the partition
task_name: Name of the consumer task
Returns:
Consumption status tensor if partition exists, None otherwise
"""
partition
=
self
.
_get_partition
(
partition_id
)
if
not
partition
:
return
None
return
partition
.
get_consumption_status
(
task_name
)
def
get_production_status
(
self
,
partition_id
:
str
,
data_fields
:
list
[
str
])
->
bool
:
"""
Check if all samples for specified fields are fully produced in a partition.
Args:
partition_id: ID of the partition
data_fields: List of field names to check production status for
Returns:
bool: True if all samples have been produced for all specified fields, False otherwise
"""
partition
=
self
.
_get_partition
(
partition_id
)
if
not
partition
:
return
False
return
partition
.
get_production_status_for_fields
(
data_fields
)
def
get_metadata
(
self
,
data_fields
:
list
[
str
],
partition_id
:
str
,
mode
:
str
=
"fetch"
,
task_name
:
str
|
None
=
None
,
batch_size
:
int
|
None
=
None
,
sampling_config
:
Optional
[
dict
[
str
,
Any
]]
=
None
,
*
args
,
**
kwargs
,
)
->
BatchMeta
:
"""
Retrieve metadata with support for three modes.
Args:
data_fields: List of field names to include in metadata
partition_id: Partition id for which to retrieve metadata
mode: Operation mode - 'insert', 'fetch', or 'force_fetch'
- mode="insert": Create metadata for new samples (for data insertion)
- mode="fetch": Get metadata from ready samples using the configured sampler
- mode="force_fetch": Get metadata for unconsumed samples without sampling
(excludes already consumed samples)
task_name: Name of the consumer task (required for fetch modes)
batch_size: Number of samples to retrieve
*args: Additional positional arguments
**kwargs: Additional keyword arguments
Returns:
BatchMeta object containing the requested metadata
Raises:
TimeoutError: If waiting for sufficient data times out in fetch mode
"""
if
partition_id
not
in
self
.
partitions
:
self
.
create_partition
(
partition_id
)
if
mode
==
"insert"
:
if
data_fields
:
# First put_data call, get_metadata in insert mode
batch_global_indexes
=
self
.
index_manager
.
allocate_indexes
(
partition_id
,
count
=
batch_size
)
else
:
# clear metadata call passes empty data_fields
batch_global_indexes
=
self
.
index_manager
.
get_indexes_for_partition
(
partition_id
)
return
self
.
generate_batch_meta
(
partition_id
,
batch_global_indexes
,
data_fields
,
mode
)
assert
task_name
is
not
None
if
mode
==
"fetch"
:
# Find ready samples within current data partition and package into BatchMeta when reading
start_time
=
time
.
time
()
while
True
:
# ready_for_consume_indexes: samples where all required fields are produced
# (production status is ready) and not yet consumed
ready_for_consume_indexes
=
self
.
scan_data_status
(
partition_id
,
data_fields
,
task_name
)
if
len
(
ready_for_consume_indexes
)
<
batch_size
:
if
self
.
polling_mode
:
logger
.
debug
(
f"[
{
self
.
controller_id
}
]: Not enough data for task
{
task_name
}
in partition
{
partition_id
}
."
f" Required:
{
batch_size
}
, Available:
{
len
(
ready_for_consume_indexes
)
}
."
f" Returning None due to polling mode."
)
return
BatchMeta
.
empty
()
if
time
.
time
()
-
start_time
>
TQ_CONTROLLER_GET_METADATA_TIMEOUT
:
raise
TimeoutError
(
f"Timeout while waiting for sufficient data for task
{
task_name
}
. "
f"Required:
{
batch_size
}
, Available:
{
len
(
ready_for_consume_indexes
)
}
"
)
logger
.
warning
(
f"[
{
self
.
controller_id
}
]: Insufficient data for task
{
task_name
}
. Required:
{
batch_size
}
"
f"samples with fields
{
data_fields
}
in partition
{
partition_id
}
, but only have "
f"
{
len
(
ready_for_consume_indexes
)
}
samples meeting the criteria. "
f"Retrying in
{
TQ_CONTROLLER_GET_METADATA_CHECK_INTERVAL
}
s..."
)
time
.
sleep
(
TQ_CONTROLLER_GET_METADATA_CHECK_INTERVAL
)
else
:
break
batch_global_indexes
,
consumed_indexes
=
self
.
sampler
(
ready_for_consume_indexes
,
batch_size
,
**
(
sampling_config
or
{}),
)
# Check if we got valid results from the sampler
if
len
(
batch_global_indexes
)
!=
batch_size
:
raise
RuntimeError
(
f"Sampler returned insufficient samples. Please check the sampler logic. "
f"Expected:
{
batch_size
}
, before sampling:
{
len
(
ready_for_consume_indexes
)
}
, "
f"after sampling:
{
len
(
batch_global_indexes
)
}
"
)
elif
mode
==
"force_fetch"
:
global_indexes_range
=
self
.
index_manager
.
get_indexes_for_partition
(
partition_id
)
consumer_status
=
self
.
get_consumption_status
(
partition_id
,
task_name
)
not_consumed_idx
=
[
i
for
i
in
global_indexes_range
if
consumer_status
[
i
]
==
0
]
batch_global_indexes
=
not_consumed_idx
consumed_indexes
=
[]
# Package into metadata
metadata
=
self
.
generate_batch_meta
(
partition_id
,
batch_global_indexes
,
data_fields
,
mode
)
# Mark samples as consumed if in fetch mode
if
mode
==
"fetch"
and
consumed_indexes
:
partition
=
self
.
partitions
[
partition_id
]
partition
.
mark_consumed
(
task_name
,
consumed_indexes
)
return
metadata
def
scan_data_status
(
self
,
partition_id
:
str
,
data_fields
:
list
[
str
],
task_name
:
str
,
)
->
list
[
int
]:
"""
Find samples that are ready for consumption in a specific partition.
Delegates scanning functionality to the partition's own method.
Args:
partition_id: ID of the partition
data_fields: List of required field names
task_name: Name of the consumer task
Returns:
List of global indices that are ready for consumption
"""
partition
=
self
.
_get_partition
(
partition_id
)
if
not
partition
:
return
[]
# Use partition's own scanning method
ready_sample_indices
=
partition
.
scan_data_status
(
data_fields
,
task_name
)
return
ready_sample_indices
# ==================== Metadata Generation API ====================
def
generate_batch_meta
(
self
,
partition_id
:
str
,
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL