-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_parallel_simulator.py
More file actions
2021 lines (1605 loc) · 79.1 KB
/
llm_parallel_simulator.py
File metadata and controls
2021 lines (1605 loc) · 79.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
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
"""
LLM并行计算模拟器
支持的并行策略:
- 数据并行 (Data Parallel): DDP, FSDP
- 张量并行 (Tensor Parallel): Megatron-LM风格
- 流水线并行 (Pipeline Parallel): GPipe, PipeDream
- 序列并行 (Sequence Parallel): 长序列处理
- 专家并行 (Expert Parallel): MoE并行
- 3D并行 (3D Parallel): 混合并行策略
"""
import time
import random
import math
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, field
from enum import Enum
from abc import ABC, abstractmethod
try:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
print("警告: matplotlib/numpy未安装,将跳过可视化功能")
try:
from tqdm import tqdm
HAS_TQDM = True
except ImportError:
HAS_TQDM = False
print("警告: tqdm未安装,将使用简单进度显示")
# ======================
# LLM模型架构定义
# ======================
@dataclass
class TransformerConfig:
"""Transformer模型配置"""
# 模型结构参数
vocab_size: int = 50000
hidden_size: int = 4096
num_layers: int = 32
num_attention_heads: int = 32
intermediate_size: int = 11008 # FFN中间层大小
max_sequence_length: int = 2048
# 训练参数
batch_size: int = 8
micro_batch_size: int = 2
gradient_accumulation_steps: int = 4
# 内存和计算参数
dtype_bytes: int = 2 # FP16
activation_checkpointing: bool = True
def __post_init__(self):
"""计算派生参数"""
self.head_dim = self.hidden_size // self.num_attention_heads
self.total_params = self.estimate_parameters()
self.model_memory_gb = self.estimate_model_memory()
def estimate_parameters(self) -> int:
"""估算模型参数量"""
# Embedding层
embedding_params = self.vocab_size * self.hidden_size
# Transformer层参数
# Attention: Q,K,V投影 + 输出投影
attention_params = 4 * self.hidden_size * self.hidden_size
# FFN: 上投影 + 下投影
ffn_params = 2 * self.hidden_size * self.intermediate_size
# LayerNorm: 2个LayerNorm层
layernorm_params = 2 * self.hidden_size
layer_params = attention_params + ffn_params + layernorm_params
total_layer_params = self.num_layers * layer_params
# 输出层
output_params = self.hidden_size * self.vocab_size
return embedding_params + total_layer_params + output_params
def estimate_model_memory(self) -> float:
"""估算模型内存使用(GB)"""
return self.total_params * self.dtype_bytes / (1024**3)
@dataclass
class LLMWorkload:
"""LLM工作负载定义"""
model_config: TransformerConfig
sequence_length: int
batch_size: int
def __post_init__(self):
"""计算工作负载特征"""
self.tokens_per_batch = self.batch_size * self.sequence_length
self.activation_memory_gb = self.estimate_activation_memory()
self.compute_flops = self.estimate_compute_flops()
def estimate_activation_memory(self) -> float:
"""估算激活内存使用(GB)"""
# 每个token的激活内存
hidden_states = self.model_config.hidden_size
attention_scores = self.model_config.num_attention_heads * self.sequence_length
activation_per_token = (hidden_states + attention_scores) * self.model_config.dtype_bytes
total_activation = activation_per_token * self.tokens_per_batch * self.model_config.num_layers
# 如果使用激活检查点,减少内存使用
if self.model_config.activation_checkpointing:
total_activation *= 0.5
return total_activation / (1024**3)
def estimate_compute_flops(self) -> int:
"""估算计算FLOPs"""
# 前向传播FLOPs估算
# Attention: O(n²d + nd²)
attention_flops = (
self.sequence_length ** 2 * self.model_config.hidden_size +
self.sequence_length * self.model_config.hidden_size ** 2
) * self.model_config.num_layers
# FFN: O(nd_ff)
ffn_flops = (
self.sequence_length * self.model_config.hidden_size * self.model_config.intermediate_size * 2
) * self.model_config.num_layers
return (attention_flops + ffn_flops) * self.batch_size
# ======================
# 设备和通信模拟
# ======================
@dataclass
class DeviceSpec:
"""设备规格"""
device_id: int
memory_gb: float = 80.0 # A100 80GB
compute_tflops: float = 312.0 # A100 BF16
memory_bandwidth_gbps: float = 2000.0 # HBM带宽
class CommunicationTopology:
"""通信拓扑模拟"""
def __init__(self, num_devices: int, topology_type: str = "dgx"):
self.num_devices = num_devices
self.topology_type = topology_type
self.devices = [DeviceSpec(i) for i in range(num_devices)]
self.bandwidth_matrix = self._create_bandwidth_matrix()
def _create_bandwidth_matrix(self) -> List[List[float]]:
"""创建设备间带宽矩阵(GB/s)"""
matrix = [[0.0] * self.num_devices for _ in range(self.num_devices)]
if self.topology_type == "dgx":
# DGX A100拓扑: NVLink连接
nvlink_bandwidth = 600.0 # GB/s
infiniband_bandwidth = 200.0 # GB/s
for i in range(self.num_devices):
for j in range(self.num_devices):
if i == j:
matrix[i][j] = float('inf') # 本地内存
elif abs(i - j) <= 2: # 相邻设备用NVLink
matrix[i][j] = nvlink_bandwidth
else: # 远程设备用InfiniBand
matrix[i][j] = infiniband_bandwidth
else:
# 默认全连接拓扑
default_bandwidth = 100.0
for i in range(self.num_devices):
for j in range(self.num_devices):
if i == j:
matrix[i][j] = float('inf')
else:
matrix[i][j] = default_bandwidth
return matrix
def get_communication_time(self, src: int, dst: int, data_size_gb: float) -> float:
"""计算通信时间(秒)"""
if src == dst:
return 0.0
bandwidth = self.bandwidth_matrix[src][dst]
return data_size_gb / bandwidth
@dataclass
class PerformanceMetrics:
"""性能指标"""
strategy_name: str
total_time: float
compute_time: float
communication_time: float
memory_usage_per_device: float
peak_memory_usage: float
throughput_tokens_per_sec: float
model_flops_utilization: float
communication_efficiency: float
scalability_efficiency: float
details: Dict[str, Any] = field(default_factory=dict)
@property
def speedup(self) -> float:
"""相对于基准的加速比"""
baseline_time = self.details.get('baseline_time', self.total_time)
return baseline_time / self.total_time if self.total_time > 0 else 1.0
# ======================
# 内存管理器
# ======================
class MemoryManager:
"""内存管理器"""
def __init__(self, devices: List[DeviceSpec]):
self.devices = devices
self.memory_usage = {dev.device_id: 0.0 for dev in devices}
self.peak_usage = {dev.device_id: 0.0 for dev in devices}
def allocate(self, device_id: int, size_gb: float) -> bool:
"""分配内存"""
if device_id >= len(self.devices):
return False
device = self.devices[device_id]
if self.memory_usage[device_id] + size_gb <= device.memory_gb:
self.memory_usage[device_id] += size_gb
self.peak_usage[device_id] = max(
self.peak_usage[device_id],
self.memory_usage[device_id]
)
return True
return False
def deallocate(self, device_id: int, size_gb: float):
"""释放内存"""
if device_id < len(self.devices):
self.memory_usage[device_id] = max(0, self.memory_usage[device_id] - size_gb)
def get_memory_utilization(self, device_id: int) -> float:
"""获取内存利用率"""
if device_id >= len(self.devices):
return 0.0
return self.memory_usage[device_id] / self.devices[device_id].memory_gb
def reset(self):
"""重置内存使用"""
for device_id in self.memory_usage:
self.memory_usage[device_id] = 0.0
self.peak_usage[device_id] = 0.0
# ======================
# 并行策略抽象基类
# ======================
class ParallelStrategy(ABC):
"""并行策略抽象基类"""
def __init__(self,
workload: LLMWorkload,
topology: CommunicationTopology,
memory_manager: MemoryManager):
self.workload = workload
self.topology = topology
self.memory_manager = memory_manager
self.strategy_name = self.__class__.__name__
@abstractmethod
def setup(self) -> bool:
"""设置并行策略,返回是否成功"""
pass
@abstractmethod
def forward_pass(self) -> Tuple[float, float]:
"""执行前向传播,返回(计算时间, 通信时间)"""
pass
@abstractmethod
def backward_pass(self) -> Tuple[float, float]:
"""执行反向传播,返回(计算时间, 通信时间)"""
pass
@abstractmethod
def get_memory_usage(self) -> Dict[int, float]:
"""获取各设备内存使用情况"""
pass
def simulate_compute(self, flops: int, device_id: int) -> float:
"""模拟计算时间"""
device = self.topology.devices[device_id]
# 考虑设备利用率和随机性
utilization = 0.8 + 0.2 * random.random()
compute_time = flops / (device.compute_tflops * 1e12) / utilization
# 添加少量实际等待时间用于演示
time.sleep(compute_time * 0.001)
return compute_time
def simulate_communication(self, src: int, dst: int, data_size_gb: float) -> float:
"""模拟通信时间"""
comm_time = self.topology.get_communication_time(src, dst, data_size_gb)
# 添加通信开销和随机性
overhead = 1.1 + 0.1 * random.random()
actual_time = comm_time * overhead
# 添加少量实际等待时间用于演示
time.sleep(actual_time * 0.001)
return actual_time
def run_simulation(self) -> PerformanceMetrics:
"""运行完整的训练模拟"""
print(f"\n🔄 运行 {self.strategy_name} 模拟...")
# 设置策略
if not self.setup():
raise RuntimeError(f"Failed to setup {self.strategy_name}")
start_time = time.time()
# 前向传播
forward_compute, forward_comm = self.forward_pass()
# 反向传播
backward_compute, backward_comm = self.backward_pass()
total_time = time.time() - start_time
total_compute = forward_compute + backward_compute
total_comm = forward_comm + backward_comm
# 计算性能指标
memory_usage = self.get_memory_usage()
peak_memory = max(memory_usage.values()) if memory_usage else 0.0
avg_memory = sum(memory_usage.values()) / len(memory_usage) if memory_usage else 0.0
throughput = self.workload.tokens_per_batch / total_time
flops_utilization = self.workload.compute_flops / (total_compute * sum(
dev.compute_tflops * 1e12 for dev in self.topology.devices
)) if total_compute > 0 else 0.0
comm_efficiency = total_compute / (total_compute + total_comm) if (total_compute + total_comm) > 0 else 1.0
# 可扩展性效率(相对于理想线性扩展)
ideal_time = total_time * len(self.topology.devices)
scalability_efficiency = ideal_time / (total_time * len(self.topology.devices)) if total_time > 0 else 1.0
metrics = PerformanceMetrics(
strategy_name=self.strategy_name,
total_time=total_time,
compute_time=total_compute,
communication_time=total_comm,
memory_usage_per_device=avg_memory,
peak_memory_usage=peak_memory,
throughput_tokens_per_sec=throughput,
model_flops_utilization=flops_utilization,
communication_efficiency=comm_efficiency,
scalability_efficiency=scalability_efficiency,
details={
'memory_per_device': memory_usage,
'forward_compute': forward_compute,
'forward_comm': forward_comm,
'backward_compute': backward_compute,
'backward_comm': backward_comm,
'num_devices': len(self.topology.devices)
}
)
print(f"✅ {self.strategy_name} 完成: {total_time:.3f}秒, "
f"吞吐量: {throughput:.1f} tokens/s, "
f"通信效率: {comm_efficiency:.2%}")
return metrics
# ======================
# 基准策略(单设备)
# ======================
class BaselineStrategy(ParallelStrategy):
"""基准策略:单设备训练"""
def setup(self) -> bool:
"""设置单设备训练"""
# 检查单设备是否能容纳模型和激活
model_memory = self.workload.model_config.model_memory_gb
activation_memory = self.workload.activation_memory_gb
total_memory = model_memory + activation_memory
if not self.memory_manager.allocate(0, total_memory):
print(f"❌ 单设备内存不足: 需要 {total_memory:.1f}GB")
return False
print(f"📊 单设备配置: 模型 {model_memory:.1f}GB + 激活 {activation_memory:.1f}GB")
return True
def forward_pass(self) -> Tuple[float, float]:
"""前向传播"""
# 计算前向传播FLOPs
forward_flops = self.workload.compute_flops // 2 # 前向约占一半
compute_time = self.simulate_compute(forward_flops, 0)
return compute_time, 0.0 # 单设备无通信
def backward_pass(self) -> Tuple[float, float]:
"""反向传播"""
# 计算反向传播FLOPs(约为前向的2倍)
backward_flops = self.workload.compute_flops
compute_time = self.simulate_compute(backward_flops, 0)
return compute_time, 0.0 # 单设备无通信
def get_memory_usage(self) -> Dict[int, float]:
"""获取内存使用"""
return {0: self.memory_manager.memory_usage[0]}
# ======================
# 数据并行策略
# ======================
class DataParallelStrategy(ParallelStrategy):
"""数据并行策略:DDP风格"""
def __init__(self, workload: LLMWorkload, topology: CommunicationTopology,
memory_manager: MemoryManager, dp_type: str = "ddp"):
super().__init__(workload, topology, memory_manager)
self.dp_type = dp_type # "ddp" or "fsdp"
self.num_devices = len(topology.devices)
self.micro_batch_per_device = workload.batch_size // self.num_devices
def setup(self) -> bool:
"""设置数据并行"""
model_memory = self.workload.model_config.model_memory_gb
if self.dp_type == "fsdp":
# FSDP: 模型参数分片
model_memory_per_device = model_memory / self.num_devices
print(f"📊 FSDP配置: 模型分片 {model_memory_per_device:.1f}GB/设备")
else:
# DDP: 每个设备复制完整模型
model_memory_per_device = model_memory
print(f"📊 DDP配置: 完整模型 {model_memory_per_device:.1f}GB/设备")
# 激活内存按设备分配
activation_memory_per_device = self.workload.activation_memory_gb / self.num_devices
total_memory_per_device = model_memory_per_device + activation_memory_per_device
# 检查每个设备内存
for device_id in range(self.num_devices):
if not self.memory_manager.allocate(device_id, total_memory_per_device):
print(f"❌ 设备 {device_id} 内存不足: 需要 {total_memory_per_device:.1f}GB")
return False
print(f"✅ 数据并行设置完成: {self.num_devices}设备, "
f"微批次大小: {self.micro_batch_per_device}")
return True
def forward_pass(self) -> Tuple[float, float]:
"""前向传播"""
# 每个设备处理自己的微批次
forward_flops_per_device = (self.workload.compute_flops // 2) // self.num_devices
# 并行计算(取最慢设备的时间)
compute_times = []
for device_id in range(self.num_devices):
compute_time = self.simulate_compute(forward_flops_per_device, device_id)
compute_times.append(compute_time)
max_compute_time = max(compute_times)
# 前向传播无需通信
return max_compute_time, 0.0
def backward_pass(self) -> Tuple[float, float]:
"""反向传播"""
# 反向传播计算
backward_flops_per_device = self.workload.compute_flops // self.num_devices
compute_times = []
for device_id in range(self.num_devices):
compute_time = self.simulate_compute(backward_flops_per_device, device_id)
compute_times.append(compute_time)
max_compute_time = max(compute_times)
# 梯度同步通信
if self.dp_type == "fsdp":
# FSDP: 分片梯度收集和重分布
comm_time = self._simulate_fsdp_communication()
else:
# DDP: All-Reduce梯度同步
comm_time = self._simulate_allreduce_communication()
return max_compute_time, comm_time
def _simulate_allreduce_communication(self) -> float:
"""模拟All-Reduce通信"""
# 梯度大小等于模型参数大小
gradient_size_gb = self.workload.model_config.model_memory_gb
# All-Reduce算法:Ring All-Reduce
# 通信量 = 2 * (N-1) / N * 数据大小,其中N是设备数
comm_volume = 2 * (self.num_devices - 1) / self.num_devices * gradient_size_gb
# 使用最慢链路的带宽
min_bandwidth = min(
self.topology.bandwidth_matrix[i][j]
for i in range(self.num_devices)
for j in range(self.num_devices)
if i != j
)
comm_time = comm_volume / min_bandwidth
# 模拟实际通信
time.sleep(comm_time * 0.001)
return comm_time
def _simulate_fsdp_communication(self) -> float:
"""模拟FSDP通信"""
# FSDP通信包括:
# 1. All-Gather参数分片
# 2. Reduce-Scatter梯度
param_shard_size = self.workload.model_config.model_memory_gb / self.num_devices
# All-Gather: 每个设备收集其他设备的参数分片
allgather_volume = (self.num_devices - 1) * param_shard_size
# Reduce-Scatter: 梯度归约并分散
reduce_scatter_volume = (self.num_devices - 1) / self.num_devices * param_shard_size
total_volume = allgather_volume + reduce_scatter_volume
# 使用平均带宽
avg_bandwidth = sum(
self.topology.bandwidth_matrix[i][j]
for i in range(self.num_devices)
for j in range(self.num_devices)
if i != j
) / (self.num_devices * (self.num_devices - 1))
comm_time = total_volume / avg_bandwidth
# 模拟实际通信
time.sleep(comm_time * 0.001)
return comm_time
def get_memory_usage(self) -> Dict[int, float]:
"""获取内存使用"""
return {i: self.memory_manager.memory_usage[i] for i in range(self.num_devices)}
# ======================
# 张量并行策略
# ======================
class TensorParallelStrategy(ParallelStrategy):
"""张量并行策略:Megatron-LM风格"""
def __init__(self, workload: LLMWorkload, topology: CommunicationTopology,
memory_manager: MemoryManager, tp_degree: int = None):
super().__init__(workload, topology, memory_manager)
self.tp_degree = tp_degree or len(topology.devices)
self.num_devices = len(topology.devices)
if self.num_devices % self.tp_degree != 0:
raise ValueError(f"设备数 {self.num_devices} 必须能被张量并行度 {self.tp_degree} 整除")
def setup(self) -> bool:
"""设置张量并行"""
# 张量并行:模型参数按张量维度分片
model_memory_per_device = self.workload.model_config.model_memory_gb / self.tp_degree
# 激活内存:每个设备处理完整批次,但中间激活分片
activation_memory_per_device = self.workload.activation_memory_gb / self.tp_degree
total_memory_per_device = model_memory_per_device + activation_memory_per_device
# 检查每个设备内存
for device_id in range(self.num_devices):
if not self.memory_manager.allocate(device_id, total_memory_per_device):
print(f"❌ 设备 {device_id} 内存不足: 需要 {total_memory_per_device:.1f}GB")
return False
print(f"📊 张量并行配置: {self.tp_degree}路并行, "
f"模型分片 {model_memory_per_device:.1f}GB/设备")
return True
def forward_pass(self) -> Tuple[float, float]:
"""前向传播"""
# 张量并行的前向传播包括多个通信点
total_compute_time = 0.0
total_comm_time = 0.0
# 模拟每一层的计算和通信
layers_per_group = self.workload.model_config.num_layers
for layer_idx in range(layers_per_group):
# Attention层
attn_compute, attn_comm = self._simulate_attention_layer()
# FFN层
ffn_compute, ffn_comm = self._simulate_ffn_layer()
total_compute_time += attn_compute + ffn_compute
total_comm_time += attn_comm + ffn_comm
return total_compute_time, total_comm_time
def backward_pass(self) -> Tuple[float, float]:
"""反向传播"""
# 反向传播的计算量约为前向的2倍
forward_compute, forward_comm = self.forward_pass()
# 反向传播有额外的梯度All-Reduce
gradient_comm = self._simulate_gradient_allreduce()
return forward_compute * 2, forward_comm + gradient_comm
def _simulate_attention_layer(self) -> Tuple[float, float]:
"""模拟Attention层的张量并行"""
# Attention计算:Q, K, V投影并行,输出投影需要All-Reduce
# 计算时间:每个设备处理1/tp_degree的头
seq_len = self.workload.sequence_length
hidden_size = self.workload.model_config.hidden_size
batch_size = self.workload.batch_size
# QKV投影计算(并行)
qkv_flops = 3 * seq_len * hidden_size * hidden_size * batch_size // self.tp_degree
qkv_compute_time = self.simulate_compute(qkv_flops, 0)
# Attention计算(并行)
attn_flops = seq_len * seq_len * hidden_size * batch_size // self.tp_degree
attn_compute_time = self.simulate_compute(attn_flops, 0)
# 输出投影(需要All-Reduce)
output_flops = seq_len * hidden_size * hidden_size * batch_size // self.tp_degree
output_compute_time = self.simulate_compute(output_flops, 0)
total_compute = qkv_compute_time + attn_compute_time + output_compute_time
# 通信:输出投影后的All-Reduce
output_size_gb = seq_len * hidden_size * batch_size * self.workload.model_config.dtype_bytes / (1024**3)
comm_time = self._simulate_allreduce(output_size_gb)
return total_compute, comm_time
def _simulate_ffn_layer(self) -> Tuple[float, float]:
"""模拟FFN层的张量并行"""
# FFN: 上投影并行,下投影需要All-Reduce
seq_len = self.workload.sequence_length
hidden_size = self.workload.model_config.hidden_size
intermediate_size = self.workload.model_config.intermediate_size
batch_size = self.workload.batch_size
# 上投影(并行)
up_flops = seq_len * hidden_size * intermediate_size * batch_size // self.tp_degree
up_compute_time = self.simulate_compute(up_flops, 0)
# 激活函数(并行)
activation_flops = seq_len * intermediate_size * batch_size // self.tp_degree
activation_compute_time = self.simulate_compute(activation_flops, 0)
# 下投影(需要All-Reduce)
down_flops = seq_len * intermediate_size * hidden_size * batch_size // self.tp_degree
down_compute_time = self.simulate_compute(down_flops, 0)
total_compute = up_compute_time + activation_compute_time + down_compute_time
# 通信:下投影后的All-Reduce
output_size_gb = seq_len * hidden_size * batch_size * self.workload.model_config.dtype_bytes / (1024**3)
comm_time = self._simulate_allreduce(output_size_gb)
return total_compute, comm_time
def _simulate_allreduce(self, data_size_gb: float) -> float:
"""模拟张量并行组内的All-Reduce"""
# Ring All-Reduce算法
comm_volume = 2 * (self.tp_degree - 1) / self.tp_degree * data_size_gb
# 使用张量并行组内的最小带宽
min_bandwidth = min(
self.topology.bandwidth_matrix[i][j]
for i in range(self.tp_degree)
for j in range(self.tp_degree)
if i != j
)
comm_time = comm_volume / min_bandwidth
time.sleep(comm_time * 0.001)
return comm_time
def _simulate_gradient_allreduce(self) -> float:
"""模拟梯度All-Reduce"""
# 梯度大小等于模型参数分片大小
gradient_size_gb = self.workload.model_config.model_memory_gb / self.tp_degree
return self._simulate_allreduce(gradient_size_gb)
def get_memory_usage(self) -> Dict[int, float]:
"""获取内存使用"""
return {i: self.memory_manager.memory_usage[i] for i in range(self.num_devices)}
# ======================
# 流水线并行策略
# ======================
class PipelineParallelStrategy(ParallelStrategy):
"""流水线并行策略:GPipe/PipeDream风格"""
def __init__(self, workload: LLMWorkload, topology: CommunicationTopology,
memory_manager: MemoryManager, pp_degree: int = None,
schedule: str = "gpipe"):
super().__init__(workload, topology, memory_manager)
self.pp_degree = pp_degree or len(topology.devices)
self.num_devices = len(topology.devices)
self.schedule = schedule # "gpipe" or "pipedream"
if self.num_devices % self.pp_degree != 0:
raise ValueError(f"设备数 {self.num_devices} 必须能被流水线并行度 {self.pp_degree} 整除")
# 计算微批次数量
self.num_microbatches = max(4, self.pp_degree * 2) # 通常是流水线深度的2-4倍
self.microbatch_size = workload.batch_size // self.num_microbatches
# 每个阶段的层数
self.layers_per_stage = workload.model_config.num_layers // self.pp_degree
def setup(self) -> bool:
"""设置流水线并行"""
# 每个阶段只需要部分模型参数
model_memory_per_stage = self.workload.model_config.model_memory_gb / self.pp_degree
# 激活内存:需要存储多个微批次的激活
activation_memory_per_stage = (
self.workload.activation_memory_gb / self.pp_degree *
self.num_microbatches / self.workload.batch_size * self.microbatch_size
)
total_memory_per_stage = model_memory_per_stage + activation_memory_per_stage
# 检查每个设备内存
for device_id in range(self.num_devices):
if not self.memory_manager.allocate(device_id, total_memory_per_stage):
print(f"❌ 设备 {device_id} 内存不足: 需要 {total_memory_per_stage:.1f}GB")
return False
print(f"📊 流水线并行配置: {self.pp_degree}阶段, {self.num_microbatches}微批次, "
f"调度: {self.schedule}")
return True
def forward_pass(self) -> Tuple[float, float]:
"""前向传播"""
if self.schedule == "gpipe":
return self._simulate_gpipe_forward()
else:
return self._simulate_pipedream_forward()
def backward_pass(self) -> Tuple[float, float]:
"""反向传播"""
if self.schedule == "gpipe":
return self._simulate_gpipe_backward()
else:
return self._simulate_pipedream_backward()
def _simulate_gpipe_forward(self) -> Tuple[float, float]:
"""模拟GPipe前向传播"""
# GPipe: 严格的前向-反向分离
stage_compute_time = self._get_stage_compute_time() / 2 # 前向约占一半
# 流水线执行时间线
pipeline_timeline = []
# 前向传播:填充流水线
for microbatch_id in range(self.num_microbatches):
for stage_id in range(self.pp_degree):
start_time = microbatch_id * stage_compute_time + stage_id * stage_compute_time
pipeline_timeline.append({
'stage': stage_id,
'microbatch': microbatch_id,
'phase': 'forward',
'start_time': start_time,
'duration': stage_compute_time
})
# 计算总的前向时间
total_forward_time = (self.num_microbatches + self.pp_degree - 1) * stage_compute_time
# 通信时间:阶段间激活传递
activation_size_per_microbatch = (
self.workload.sequence_length * self.workload.model_config.hidden_size *
self.microbatch_size * self.workload.model_config.dtype_bytes / (1024**3)
)
total_comm_time = 0.0
for stage_id in range(self.pp_degree - 1):
comm_time = self.simulate_communication(
stage_id, stage_id + 1,
activation_size_per_microbatch * self.num_microbatches
)
total_comm_time += comm_time
return total_forward_time, total_comm_time
def _simulate_gpipe_backward(self) -> Tuple[float, float]:
"""模拟GPipe反向传播"""
# 反向传播计算时间
stage_compute_time = self._get_stage_compute_time() # 反向约为前向的2倍
# 反向传播:排空流水线
total_backward_time = (self.num_microbatches + self.pp_degree - 1) * stage_compute_time
# 通信时间:梯度传递
gradient_size_per_microbatch = (
self.workload.sequence_length * self.workload.model_config.hidden_size *
self.microbatch_size * self.workload.model_config.dtype_bytes / (1024**3)
)
total_comm_time = 0.0
for stage_id in range(1, self.pp_degree):
comm_time = self.simulate_communication(
stage_id, stage_id - 1,
gradient_size_per_microbatch * self.num_microbatches
)
total_comm_time += comm_time
return total_backward_time, total_comm_time
def _simulate_pipedream_forward(self) -> Tuple[float, float]:
"""模拟PipeDream前向传播(1F1B调度)"""
# PipeDream: 前向和反向交替执行
stage_compute_time = self._get_stage_compute_time() / 2
# 1F1B调度:每个阶段在前向后立即执行反向
# 这里简化为前向时间,反向在backward_pass中计算
warmup_time = self.pp_degree * stage_compute_time
steady_time = (self.num_microbatches - self.pp_degree) * stage_compute_time
total_time = warmup_time + steady_time
# 通信时间类似GPipe但重叠更好
activation_size = (
self.workload.sequence_length * self.workload.model_config.hidden_size *
self.microbatch_size * self.workload.model_config.dtype_bytes / (1024**3)
)
# 通信与计算重叠,实际通信时间更少
comm_time = activation_size * self.num_microbatches / self.topology.bandwidth_matrix[0][1] * 0.5
return total_time, comm_time
def _simulate_pipedream_backward(self) -> Tuple[float, float]:
"""模拟PipeDream反向传播"""
# 1F1B调度中反向与前向交替,总时间已在前向中计算
stage_compute_time = self._get_stage_compute_time()
# 反向传播时间
backward_time = stage_compute_time * self.num_microbatches
# 梯度通信
gradient_size = (
self.workload.model_config.model_memory_gb / self.pp_degree / self.num_microbatches
)
comm_time = gradient_size * self.num_microbatches / self.topology.bandwidth_matrix[0][1] * 0.3
return backward_time, comm_time
def _get_stage_compute_time(self) -> float:
"""计算每个阶段的计算时间"""
# 每个阶段处理部分层和一个微批次
stage_flops = (
self.workload.compute_flops / self.workload.batch_size * self.microbatch_size / self.pp_degree
)
return self.simulate_compute(stage_flops, 0)
def get_memory_usage(self) -> Dict[int, float]:
"""获取内存使用"""
return {i: self.memory_manager.memory_usage[i] for i in range(self.num_devices)}
# ======================
# 序列并行策略
# ======================
class SequenceParallelStrategy(ParallelStrategy):
"""序列并行策略:长序列处理"""
def __init__(self, workload: LLMWorkload, topology: CommunicationTopology,
memory_manager: MemoryManager, sp_degree: int = None):
super().__init__(workload, topology, memory_manager)
self.sp_degree = sp_degree or len(topology.devices)
self.num_devices = len(topology.devices)
# 序列长度必须能被并行度整除
if workload.sequence_length % self.sp_degree != 0:
raise ValueError(f"序列长度 {workload.sequence_length} 必须能被序列并行度 {self.sp_degree} 整除")
self.seq_len_per_device = workload.sequence_length // self.sp_degree
def setup(self) -> bool:
"""设置序列并行"""
# 每个设备存储完整模型但只处理部分序列
model_memory_per_device = self.workload.model_config.model_memory_gb
# 激活内存按序列长度分片
activation_memory_per_device = self.workload.activation_memory_gb / self.sp_degree
total_memory_per_device = model_memory_per_device + activation_memory_per_device
# 检查每个设备内存
for device_id in range(self.num_devices):
if not self.memory_manager.allocate(device_id, total_memory_per_device):
print(f"❌ 设备 {device_id} 内存不足: 需要 {total_memory_per_device:.1f}GB")
return False
print(f"📊 序列并行配置: {self.sp_degree}路并行, "
f"每设备序列长度: {self.seq_len_per_device}")
return True
def forward_pass(self) -> Tuple[float, float]:
"""前向传播"""
total_compute_time = 0.0
total_comm_time = 0.0
# 模拟每一层的序列并行计算
for layer_idx in range(self.workload.model_config.num_layers):
layer_compute, layer_comm = self._simulate_sequence_parallel_layer()
total_compute_time += layer_compute
total_comm_time += layer_comm
return total_compute_time, total_comm_time
def backward_pass(self) -> Tuple[float, float]:
"""反向传播"""
# 反向传播的计算量约为前向的2倍
forward_compute, forward_comm = self.forward_pass()
# 梯度All-Reduce
gradient_comm = self._simulate_gradient_allreduce()
return forward_compute * 2, forward_comm + gradient_comm
def _simulate_sequence_parallel_layer(self) -> Tuple[float, float]:
"""模拟序列并行层"""
# 每个设备处理部分序列长度
hidden_size = self.workload.model_config.hidden_size
batch_size = self.workload.batch_size
# Attention计算:需要All-Gather序列维度
# 1. All-Gather输入
input_size_gb = (
self.seq_len_per_device * hidden_size * batch_size *
self.workload.model_config.dtype_bytes / (1024**3)
)
allgather_time = self._simulate_allgather(input_size_gb)
# 2. 本地Attention计算(处理完整序列)
attn_flops = (
self.workload.sequence_length * self.workload.sequence_length *
hidden_size * batch_size // self.sp_degree
)
attn_compute_time = self.simulate_compute(attn_flops, 0)
# 3. Reduce-Scatter输出
output_size_gb = input_size_gb
reduce_scatter_time = self._simulate_reduce_scatter(output_size_gb)
# FFN计算(本地,无通信)
ffn_flops = (
self.seq_len_per_device * hidden_size *
self.workload.model_config.intermediate_size * batch_size * 2
)
ffn_compute_time = self.simulate_compute(ffn_flops, 0)
total_compute = attn_compute_time + ffn_compute_time
total_comm = allgather_time + reduce_scatter_time
return total_compute, total_comm
def _simulate_allgather(self, data_size_gb: float) -> float:
"""模拟All-Gather通信"""
# All-Gather: 每个设备收集其他设备的数据
comm_volume = (self.sp_degree - 1) * data_size_gb
avg_bandwidth = sum(
self.topology.bandwidth_matrix[i][j]
for i in range(self.sp_degree)
for j in range(self.sp_degree)
if i != j
) / (self.sp_degree * (self.sp_degree - 1))
comm_time = comm_volume / avg_bandwidth