-
Notifications
You must be signed in to change notification settings - Fork 3
/
hap.rs
3859 lines (3235 loc) · 156 KB
/
hap.rs
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
#![allow(unused)]
#![allow(non_upper_case_globals)]
#![feature(let_chains)]
use std::io::Write;
use std::iter::Product;
use std::ops::{Index, IndexMut, Add, Mul, Div};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use std::fmt::{Display, Debug, Formatter};
use std::cmp::Ordering;
use float_ord::FloatOrd;
use cpython::{PyResult, PyTuple, ToPyObject, ObjectProtocol, Python, PyObject, PyDict, PyClone, PyNone, PyList};
use smallvec::{SmallVec, smallvec};
pub type SVec<T, const N: usize = 1> = SmallVec<[T; N]>;
type Dimension = u8;
type Shape = SVec<usize, 4>;
type SymbolicShape = SVec<Expression, 4>;
static ctrlc_received: AtomicBool = AtomicBool::new(false);
static init_script: &str = r#"
import collectives
import operator
import models
def get_shape_of_param_or_buffer(graph_module, node):
try:
p = graph_module.get_parameter(node.target)
except AttributeError:
p = graph_module.get_buffer(node.target)
return tuple(p.shape)
def split_param_or_buffer(graph_module, target, sharding_lengths, dim, rank):
import torch
try:
p = graph_module.get_parameter(target)
except AttributeError:
p = graph_module.get_buffer(target)
if p.data.shape[dim] == 1: # hack for broadcasting
return
p.data = torch.split(p.data, sharding_lengths, dim)[rank]
def symbolic_trace(module):
import torch.fx
class Tracer(torch.fx.Tracer):
def is_leaf_module(*_): return False
graph = Tracer().trace(module)
graph.eliminate_dead_code()
model = torch.fx.graph_module.GraphModule(module, graph)
from torch.fx.experimental.normalize import NormalizeArgs, NormalizeOperators
model = NormalizeArgs(model).transform()
model = NormalizeOperators(model).transform()
for i, node in enumerate(model.graph.nodes):
node.meta['id'] = i
return model
"#;
cpython::py_module_initializer!(hap, |py, m| {
ctrlc::set_handler(|| {
ctrlc_received.store(true, std::sync::atomic::Ordering::Relaxed)
}).unwrap();
py.run(init_script, None, None).map(|_| PyNone);
// eprintln!("Hap initialized!");
m.add(py, "trace", cpython::py_fn!(py, py_trace(py_module: PyObject) -> PyResult<PyObject> {
py.eval("symbolic_trace", None, None)?.call(py, PyTuple::new(py, &[py_module]), None)
}))?;
m.add(py, "main", cpython::py_fn!(py, py_main(py_graph_module: PyObject, py_config: PyObject) -> PyResult<PyObject> {
macro_rules! get_config {
($key: expr) => { py_config.get_item(py, $key)?.extract(py)? }
}
let py_input_shape_dict = py_config.get_item(py, "input_shape").unwrap();
let mut rgraph = load_fx_graph(py, py_graph_module.clone_ref(py), py_input_shape_dict)?;
// eprintln!("graph: {rgraph:#?}");
let mut triples = analyze_rgraph(&rgraph, AnalyzerConfig {
force_zero: get_config!("extra_ps"),
force_group_collective: get_config!("group_collective")
});
let mut default_properties = vec![];
heuristics::unique_computation(&mut triples, &mut default_properties);
heuristics::unique_communication(&mut triples, &mut default_properties);
heuristics::fuse_free_triple(&mut triples, &mut default_properties);
heuristics::fuse_communication(&mut triples, &mut default_properties);
// for triple in triples.iter() {
// eprintln!("{triple}");
// }
let cluster_info = ClusterInfo {
device_flops: get_config!("device_flops"),
all_reduce_bandwidth: get_config!("all_reduce_bandwidth"),
all_gather_bandwidth: get_config!("all_gather_bandwidth"),
reduce_scatter_bandwidth: get_config!("reduce_scatter_bandwidth"),
all_to_all_bandwidth: get_config!("all_to_all_bandwidth")
};
let provided_sharding_ratios: Option<Vec<f64>> = py_config.get_item(py, "sharding_ratios").ok().and_then(|x| x.extract(py).ok());
let triple_set = IndexedHoareTripleSet::new(triples);
let (mut symbolic_sharding_ratios, mut symbol_values) = rgraph.gen_sharding_ratios(&cluster_info, &{
let total_computation_power = cluster_info.device_flops.iter().sum::<f64>();
cluster_info.device_flops.iter().map(|f| f / total_computation_power).collect::<Vec<_>>()
});
let mut best_of_the_best: Option<Program> = None;
loop {
let a_star_context = AStarContext {
triple_set: &triple_set,
symbolic_sharding_ratios: &symbolic_sharding_ratios,
symbol_values: &symbol_values
};
let best_program = a_star(&a_star_context, &default_properties, &Profiler {
rgraph: &rgraph,
cluster_info: &cluster_info
});
if provided_sharding_ratios.is_some() {
best_of_the_best = Some(best_program);
break
}
if get_config!("extra_ps") {
ps_segmentation(&mut rgraph, &best_program, &triple_set);
(symbolic_sharding_ratios, symbol_values) = rgraph.gen_sharding_ratios(&cluster_info, &{
let total_computation_power = cluster_info.device_flops.iter().sum::<f64>();
cluster_info.device_flops.iter().map(|f| f / total_computation_power).collect::<Vec<_>>()
})
}
sharding_ratio_optimization(&best_program, &triple_set, &symbolic_sharding_ratios, &Profiler {
rgraph: &rgraph,
cluster_info: &cluster_info
}, &mut symbol_values);
if best_of_the_best.is_none() || best_program.cost < best_of_the_best.as_ref().unwrap().cost {
best_program.show(&triple_set);
eprintln!("=== sharding ratios ===");
for i in 0..symbolic_sharding_ratios.len() {
eprint!("[");
for j in 0..symbolic_sharding_ratios[i].len() {
if j > 0 {
eprint!(" ");
}
eprint!("{}", symbolic_sharding_ratios[i][j].instantialize(&symbol_values));
}
eprintln!("]");
}
eprintln!("");
best_of_the_best = Some(best_program);
} else {
break
}
}
let mut codegen_context = CodegenContext::new(
py, py_graph_module, &rgraph, get_config!("rank"),
symbolic_sharding_ratios.iter().map(|s| {
s.iter().map(|d| d.instantialize(&symbol_values)).collect()
}).collect()
)?;
// println!("Estimated cost: {}", best_of_the_best.as_ref().unwrap().cost);
best_of_the_best.unwrap().codegen(&triple_set, &mut codegen_context)?;
Ok(codegen_context.graph)
}))?;
m.add(py, "stat", cpython::py_fn!(py, py_stat(py_graph_module: PyObject, py_config: PyObject) -> PyResult<f64> {
let py_input_shape_dict = py_config.get_item(py, "input_shape").unwrap();
let py_input_shape_dict = py_config.get_item(py, "input_shape").unwrap();
let rgraph = load_fx_graph(py, py_graph_module.clone_ref(py), py_input_shape_dict)?;
let mut total_flops = 0.;
for node in rgraph.nodes.iter() {
if let RInstruction::Op(op) = &node.instruction {
let shapes = node.inputs.iter()
.map(|i| &rgraph[*i].shape)
.map(|s| s.iter().map(|x| Expression::constant(*x as _)).collect::<SVec<_, 4>>())
.collect::<SVec<_>>();
let flops = (op.flops)(&shapes);
total_flops += flops.unwrap_constant();
}
}
Ok(total_flops * 3.) // 2 for backward, 1 for forward
}))?;
m.add(py, "sharding_round", cpython::py_fn!(py, py_sharding_round(py_full_length: usize, py_ratios: PyObject) -> PyResult<PyNone> {
let sharding_ratio: Vec<f64> = py_ratios.extract(py)?;
let result = sharding_round(py_full_length, &sharding_ratio);
for i in 0..result.len() {
py_ratios.set_item(py, i, result[i])?;
}
Ok(PyNone)
}))?;
Ok(())
});
macro_rules! new_usize_type {
($visibility: vis, $type_name: ident) => {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
$visibility struct $type_name(pub usize);
impl<T: Into<$type_name>> std::ops::Add<T> for $type_name {
type Output = $type_name;
fn add(self, rhs: T) -> $type_name {
$type_name(self.0 + rhs.into().0)
}
}
impl<T: Into<$type_name>> std::ops::AddAssign<T> for $type_name {
fn add_assign(&mut self, rhs: T) {
self.0 += rhs.into().0;
}
}
impl From<usize> for $type_name {
fn from(x: usize) -> $type_name {
$type_name(x)
}
}
impl std::fmt::Display for $type_name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
}
}
pub(crate) use new_usize_type;
macro_rules! py_dict {
($py:expr, $($key:ident => $value:expr),*) => {{
let dict = PyDict::new($py);
$(
dict.set_item($py, stringify!($key), &$value).unwrap();
)*
dict
}}
}
// Some names:
// R stands for Reference (the nodes and tensors in the orignal single card graph)
// D stands for Distributed (the nodes and tensors in the SIMD graph)
// Op is a curried operator with non-tensor parameters filled in
// Parameters are the parameters of the model. "Attr" is only used in "GetAttr" to keep the same as PyTorch.
// Placeholders are the inputs to the model
// The "input" of an instruction is the tensor that is read by the instruction
new_usize_type!(pub, RNodeId);
new_usize_type!(pub, RTensorId);
new_usize_type!(pub, DNodeId);
new_usize_type!(pub, DTensorId);
new_usize_type!(pub, SegmentId);
pub struct HoareTriple {
pre_conditions: SVec<Property, 4>,
post_conditions: SVec<Property>,
negative_post_conditions: Vec<Property>,
instruction: String, // for debugging purpose
codegen: Rc<dyn Fn(&mut CodegenContext) -> PyResult<()>>,
profile: Rc<dyn Fn(&mut ProfileContext) -> (Profile, Profile)>
}
impl Display for HoareTriple {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{{")?;
for (i, p) in self.pre_conditions.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{p}")?;
}
write!(f, "}} {} {{", self.instruction)?;
for (i, p) in self.post_conditions.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{p}")?;
}
// for (i, p) in self.negative_post_conditions.iter().enumerate() {
// if i > 0 || !self.post_conditions.is_empty() {
// write!(f, ", ")?;
// }
// write!(f, "¬({p})")?;
// }
write!(f, "}}")?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Property {
HasTensor(RTensorId, TensorRelation),
Finished,
AllowCommunication(RTensorId),
AllowComputation(RTensorId), // also includes placeholder and getattr
}
impl Display for Property {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Property::HasTensor(tensor_id, relation) => {
write!(f, "{}|{:?}", tensor_id, relation)
}
Property::Finished => write!(f, "finished"),
Property::AllowCommunication(tensor_id) => {
write!(f, "{}|allow_communication", tensor_id)
}
Property::AllowComputation(tensor_id) => {
write!(f, "{}|allow_computation", tensor_id)
}
}
}
}
impl Property {
fn identity(tensor_id: RTensorId) -> Property {
Property::HasTensor(tensor_id, TensorRelation::Identity)
}
fn gather(tensor_id: RTensorId, dim: Dimension) -> Property {
Property::HasTensor(tensor_id, TensorRelation::Gather(dim))
}
fn reduce(tensor_id: RTensorId) -> Property {
Property::HasTensor(tensor_id, TensorRelation::Reduce)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TensorRelation {
Gather(Dimension),
Reduce,
Identity,
}
impl HoareTriple {
fn get_cost_symbolic(&self, profiler: &Profiler, sharding_ratios: &[Vec<Expression>]) -> (Vec<Expression>, Vec<Expression>) {
let (computation_times, communication_times): (Vec<_>, Vec<_>) = (0..profiler.cluster_info.n_devices()).map(|i| {
// TODO: a lot of unnecessary work. Need benchmark.
let mut profile_context = ProfileContext {
profiler,
sharding_ratios,
device_index: i,
};
let (forward, backward) = (self.profile)(&mut profile_context);
let computation_time = (forward.flops + backward.flops) / profiler.cluster_info.device_flops[i];
let communication_time =
(forward.all_gather + backward.all_gather) / profiler.cluster_info.all_gather_bandwidth +
(forward.all_reduce + backward.all_reduce) / profiler.cluster_info.all_reduce_bandwidth +
(forward.reduce_scatter + backward.reduce_scatter) / profiler.cluster_info.reduce_scatter_bandwidth +
(forward.all_to_all + backward.all_to_all) / profiler.cluster_info.all_to_all_bandwidth;
(computation_time, communication_time)
}).unzip();
(computation_times, communication_times)
}
fn get_cost(&self, profiler: &Profiler, sharding_ratios: &[Vec<Expression>], symbol_values: &[f64]) -> f64 {
// idea: may cache the cost of each triple while using the same sharding ratios
let (computation_times, communication_times) = self.get_cost_symbolic(profiler, sharding_ratios);
let computation_time = computation_times.into_iter().map(|x| x.instantialize(symbol_values)).map(FloatOrd).max().unwrap().0;
let communication_time = communication_times.into_iter().map(|x| x.instantialize(symbol_values)).map(FloatOrd).max().unwrap().0;
computation_time + communication_time
}
fn fuse_into(&self, consumer: &HoareTriple) -> HoareTriple {
// note: must avoid circles. Currently I only fuse free tensors and communications, which are safe
for negative_post_condition in self.negative_post_conditions.iter() {
assert!(!consumer.pre_conditions.contains(&negative_post_condition));
}
let pre_conditions = self.pre_conditions.iter().chain(
consumer.pre_conditions.iter()
.filter(|c| !self.pre_conditions.contains(c) && !self.post_conditions.contains(c))
).cloned().collect();
let post_conditions = self.post_conditions.iter().chain(consumer.post_conditions.iter()).cloned().collect();
let negative_post_conditions = self.negative_post_conditions.iter().chain(consumer.negative_post_conditions.iter()).cloned().collect();
let instruction = format!("{}, {}", self.instruction, consumer.instruction);
let codegen = {
let self_codegen = self.codegen.clone();
let consumer_codegen = consumer.codegen.clone();
Rc::new(move |ctx: &mut CodegenContext| {
self_codegen(ctx)?;
consumer_codegen(ctx)
})
};
let profile = {
let self_profile = self.profile.clone();
let consumer_profile = consumer.profile.clone();
Rc::new(move |ctx: &mut ProfileContext| {
let (forward1, backward1) = self_profile(ctx);
let (forward2, backward2) = consumer_profile(ctx);
(forward1 + forward2, backward1 + backward2)
})
};
HoareTriple {
pre_conditions,
post_conditions,
negative_post_conditions,
instruction,
codegen,
profile
}
}
}
#[derive(Debug, Clone)]
struct Profiler<'r, 'c> {
rgraph: &'r RGraph,
cluster_info: &'c ClusterInfo,
}
#[derive(Debug, Clone, Default)]
struct Profile {
flops: Expression,
all_reduce: Expression,
all_gather: Expression,
all_to_all: Expression,
reduce_scatter: Expression,
}
impl Add for Profile {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Profile {
flops: self.flops + rhs.flops,
all_reduce: self.all_reduce + rhs.all_reduce,
all_gather: self.all_gather + rhs.all_gather,
all_to_all: self.all_to_all + rhs.all_to_all,
reduce_scatter: self.reduce_scatter + rhs.reduce_scatter,
}
}
}
struct ProfileContext<'p, 's, 'r, 'c> {
profiler: &'p Profiler<'r, 'c>,
sharding_ratios: &'s [Vec<Expression>],
device_index: usize
}
impl<'p, 's, 'r, 'c> ProfileContext<'p, 's, 'r, 'c> {
fn get_shape_by_property(&self, property: Property) -> SymbolicShape {
if let Property::HasTensor(tensor_id, rel) = property {
let tensor = &self.profiler.rgraph[tensor_id];
match rel {
TensorRelation::Identity | TensorRelation::Reduce => tensor.shape.iter().map(|s| Expression::constant(*s as _)).collect(),
TensorRelation::Gather(dim) => {
let dim = dim as usize;
let mut shape: SymbolicShape = tensor.shape.iter().map(|s| Expression::constant(*s as _)).collect();
shape[dim] = sharding_symbolic(tensor.shape[dim], &self.sharding_ratios[tensor.segment_id.0])[self.device_index].clone(); // unnecessary clone
shape
}
}
} else {
unreachable!()
}
}
}
#[derive(Default, Debug, Clone)]
struct Program {
triple_ids: Vec<HoareTripleId>,
properties: BTreeSet<Property>,
cost: f64,
ecost: f64,
}
impl Program {
fn empty(properties: impl IntoIterator<Item=Property>) -> Program {
Program { properties: properties.into_iter().collect(), ..Default::default() }
}
fn with_a_new_triple(&self, ctx: &AStarContext, triple_id: HoareTripleId, profiler: &Profiler) -> Program {
let mut triples = self.triple_ids.clone();
triples.push(triple_id);
let triple = &ctx.triple_set[triple_id];
let mut properties = self.properties.iter()
.filter(|p| !triple.negative_post_conditions.contains(p))
.chain(triple.post_conditions.iter())
.cloned()
.collect();
remove_irrelavent_properties(&mut properties, &ctx.triple_set);
let cost = self.cost + triple.get_cost(profiler, &ctx.symbolic_sharding_ratios, &ctx.symbol_values);
let ecost = 0.0;
Program { triple_ids: triples, properties, cost, ecost }
}
fn find_available_triples<'s, 't: 's>(&'s self, triple_set: &'t IndexedHoareTripleSet) -> Vec<HoareTripleId> {
let candidates: BTreeSet<_> = self.properties.iter().flat_map(|p| triple_set.get_triples_with_pre_condition(*p)).copied().collect();
candidates.into_iter().filter(|triple_id| {
let triple = &triple_set[*triple_id];
triple.pre_conditions.iter().all(|p| self.properties.contains(p)) && triple.post_conditions.iter().any(|p| !self.properties.contains(p))
}).collect()
}
fn is_complete(&self) -> bool {
self.properties.iter().any(|p| *p == Property::Finished)
}
fn show(&self, triple_set: &IndexedHoareTripleSet) {
eprintln!("length: {}, cost: {}, ecost: {}", self.triple_ids.len(), self.cost, self.ecost);
eprintln!("=== active properties ===");
for property in &self.properties {
eprintln!("{property}");
}
eprintln!("=== triples ===");
for triple_id in &self.triple_ids {
eprintln!("{}", triple_set[*triple_id]);
}
}
fn codegen<'py, 'r>(&self, triple_set: &IndexedHoareTripleSet, ctx: &mut CodegenContext<'py, 'r>) -> PyResult<()> {
for triple_id in &self.triple_ids {
let triple = &triple_set[*triple_id];
(triple.codegen)(ctx)?;
for property in &triple.post_conditions {
if let Property::HasTensor(_, _) = property {
assert!(ctx.property_implementation.contains_key(property), "{} {}", triple, property);
}
}
}
Ok(())
}
}
// not all irrelavent properties are removed: we only remove those can be checked without recursion to speeds up this function
fn remove_irrelavent_properties(properties: &mut BTreeSet<Property>, triple_set: &IndexedHoareTripleSet) {
let irrelavent: Vec<_> = properties.iter().filter(|property| {
if property == &&Property::Finished {
return false;
}
// sufficient but not necessary
triple_set.get_triples_with_pre_condition(**property).iter().all(|triple_id| {
triple_set[*triple_id].pre_conditions.iter().any(|p| {
!properties.contains(p) && triple_set.get_triples_with_post_condition(*p).is_empty()
})
})
}).cloned().collect();
for property in irrelavent {
properties.remove(&property);
}
}
#[derive(Debug, Clone)]
struct ProgramHeapEntry {
program: Program,
total_cost: FloatOrd<f64>,
}
impl Ord for ProgramHeapEntry {
fn cmp(&self, other: &Self) -> Ordering {
self.total_cost.partial_cmp(&other.total_cost).unwrap()
}
}
impl PartialOrd for ProgramHeapEntry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other).reverse()) // reverse to convert the max heap to min heap
}
}
impl Eq for ProgramHeapEntry {}
impl PartialEq for ProgramHeapEntry {
fn eq(&self, other: &Self) -> bool {
self.total_cost == other.total_cost
}
}
impl ProgramHeapEntry {
fn new(program: Program) -> Self {
let total_cost = FloatOrd(program.cost + program.ecost);
ProgramHeapEntry { program, total_cost }
}
}
/// a helper struct to print the iteration count and the elapsed time
struct Ticker {
iter_count: usize,
iter_per_print: usize,
start_time: std::time::Instant,
}
impl Ticker {
fn new(iter_per_print: usize) -> Self {
Ticker { iter_count: 0, iter_per_print, start_time: std::time::Instant::now() }
}
fn tick(&mut self) {
self.iter_count += 1;
if self.iter_count % self.iter_per_print == 0 {
eprintln!("{self}")
}
}
}
impl Display for Ticker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"iter count: {}, speed: {} iter/s",
self.iter_count,
self.iter_count as f64 / self.start_time.elapsed().as_secs_f64()
)
}
}
impl Drop for Ticker {
fn drop(&mut self) {
eprintln!("{self}")
}
}
struct AStarContext<'t, 's, 'v> {
triple_set: &'t IndexedHoareTripleSet,
symbolic_sharding_ratios: &'s [Vec<Expression>],
symbol_values: &'v [f64]
}
new_usize_type!(pub, HoareTripleId);
struct IndexedHoareTripleSet {
triples: Vec<HoareTriple>,
pre_condition_index: BTreeMap<Property, Vec<HoareTripleId>>,
post_condition_index: BTreeMap<Property, Vec<HoareTripleId>>,
}
impl IndexedHoareTripleSet {
fn new(triples: Vec<HoareTriple>) -> Self {
let mut pre_condition_index: BTreeMap<Property, Vec<HoareTripleId>> = Default::default();
let mut post_condition_index: BTreeMap<Property, Vec<HoareTripleId>> = Default::default();
for (i, triple) in triples.iter().enumerate() {
for p in &triple.pre_conditions {
pre_condition_index.entry(*p).or_default().push(HoareTripleId(i));
}
for p in &triple.post_conditions {
post_condition_index.entry(*p).or_default().push(HoareTripleId(i));
}
}
IndexedHoareTripleSet { triples, pre_condition_index, post_condition_index }
}
fn get_triples_with_pre_condition(&self, property: Property) -> &[HoareTripleId] {
static empty: Vec<HoareTripleId> = vec![];
self.pre_condition_index.get(&property).unwrap_or(&empty)
}
fn get_triples_with_post_condition(&self, property: Property) -> &[HoareTripleId] {
static empty: Vec<HoareTripleId> = vec![];
self.post_condition_index.get(&property).unwrap_or(&empty)
}
}
impl Index<HoareTripleId> for IndexedHoareTripleSet {
type Output = HoareTriple;
fn index(&self, index: HoareTripleId) -> &Self::Output {
&self.triples[index.0]
}
}
fn a_star(ctx: &AStarContext, initial_properties: &[Property], profiler: &Profiler) -> Program {
let mut heap = BinaryHeap::new();
let mut best_program: Option<Program> = None;
let mut property_cache: BTreeMap<BTreeSet<Property>, f64> = BTreeMap::new();
heap.push(ProgramHeapEntry::new(Program::empty(initial_properties.iter().cloned())));
property_cache.insert(initial_properties.iter().cloned().collect(), 0.);
let mut ticker = Ticker::new(5000);
while let Some(ProgramHeapEntry { program, .. }) = heap.pop() {
if ctrlc_received.load(std::sync::atomic::Ordering::Relaxed) {
panic!("interupted")
}
if best_program.as_ref().map(|p| p.cost < program.cost).unwrap_or(false) {
continue;
}
if let Some(&cached_cost) = property_cache.get(&program.properties) && cached_cost < program.cost { // it has been superseded by a better program
continue;
}
// if ticker.iter_count % 5000 == 0 {
// program.show(&ctx.triple_set);
// }
if program.is_complete() {
if best_program.as_ref().map(|p| p.cost > program.cost).unwrap_or(true) {
best_program = Some(program);
}
} else {
for triple_id in program.find_available_triples(&ctx.triple_set) {
let new_program = program.with_a_new_triple(ctx, triple_id, profiler);
if let Some(&cached_cost) = property_cache.get(&new_program.properties) && cached_cost <= new_program.cost {
continue
}
property_cache.insert(new_program.properties.clone(), new_program.cost);
heap.push(ProgramHeapEntry::new(new_program));
}
}
ticker.tick();
}
best_program.unwrap()
}
#[derive(Debug, Default)]
pub struct RGraph {
nodes: Vec<RNode>,
tensors: Vec<RTensor>,
n_segments: usize,
}
#[derive(Debug)]
pub struct RNode {
inputs: SVec<RTensorId, 4>,
outputs: SVec<RTensorId>,
instruction: RInstruction,
}
// An instruction in the reference graph without the input and output information
#[derive(Debug, Clone)]
pub enum RInstruction {
Op(Rc<Op>),
GetAttr(String),
Placeholder(String),
Output
}
#[derive(Debug)]
pub struct RTensor {
producer: RNodeId,
consumers: SVec<RNodeId>,
segment_id: SegmentId,
shape: Shape,
communicatable: bool, // hints automatically generated for certain operatios (outputs of adaptive nodes are not communicatble), can be override by user annotation
}
impl RTensor {
fn n_dims(&self) -> Dimension {
self.shape.len() as _
}
fn size(&self) -> f64 {
self.shape.iter().map(|x| *x as f64).product()
}
}
impl Index<RNodeId> for RGraph {
type Output = RNode;
fn index(&self, index: RNodeId) -> &Self::Output {
&self.nodes[index.0]
}
}
impl IndexMut<RNodeId> for RGraph {
fn index_mut(&mut self, index: RNodeId) -> &mut Self::Output {
&mut self.nodes[index.0]
}
}
impl Index<RTensorId> for RGraph {
type Output = RTensor;
fn index(&self, index: RTensorId) -> &Self::Output {
&self.tensors[index.0]
}
}
impl IndexMut<RTensorId> for RGraph {
fn index_mut(&mut self, index: RTensorId) -> &mut Self::Output {
&mut self.tensors[index.0]
}
}
impl RGraph {
// generate symbolic sharding ratios and the corresponding symbol value mapping array for an rgraph with a given initial ratios to use for all segments
fn gen_sharding_ratios(&self, cluster_info: &ClusterInfo, initial_sharding_ratios: &[f64]) -> (Vec<Vec<Expression>>, Vec<f64>) {
let mut next_symbol_id = SymbolId(0);
let symbolic_sharding_ratios = (0..self.n_segments).map(|s| {
(0..cluster_info.n_devices()).map(|d| {
let exp = Expression::symbol(next_symbol_id);
next_symbol_id += 1;
exp
}).collect::<Vec<_>>()
}).collect::<Vec<_>>();
let mut symbol_values = vec![];
for segment_sharding_ratio in symbolic_sharding_ratios.iter() {
for (sharding_ratio, initial_ratio) in segment_sharding_ratio.iter().zip(initial_sharding_ratios.iter()) {
let symbol_index = sharding_ratio.unwrap_symbol().0;
if symbol_index >= symbol_values.len() {
symbol_values.resize(symbol_index + 1, 0.0);
}
symbol_values[symbol_index] = *initial_ratio;
}
}
(symbolic_sharding_ratios, symbol_values)
}
}
struct CodegenContext<'py, 'r> {
py: Python<'py>,
graph: PyObject,
module: PyObject, // the graph_module to modify (the parameters will be sharded inplace)
rgraph: &'r RGraph, // only to provide shape information
rank: usize,
sharding_ratios: Vec<Vec<f64>>,
property_implementation: BTreeMap<Property, PyObject>,
sharded_paramters: BTreeMap<String, Dimension>, // records inplace sharded parameters and the sharding dimensions, so we won't shard a tensor multiple times
}
impl<'py, 'r> CodegenContext<'py, 'r> {
fn new(py: Python<'py>, module: PyObject, rgraph: &'r RGraph, rank: usize, sharding_ratios: Vec<Vec<f64>>) -> PyResult<Self> {
let graph = py.eval("torch.fx.Graph()", None, None)?;
Ok(Self {
py, graph, module, rgraph, rank, sharding_ratios,
property_implementation: BTreeMap::new(),
sharded_paramters: BTreeMap::new(),
})
}
fn get_property_implementation(&mut self, property: Property) -> PyObject {
self.property_implementation[&property].clone_ref(self.py)
}
fn set_property_implementation(&mut self, property: Property, tensor: PyObject) {
assert!(self.property_implementation.insert(property, tensor).is_none())
}
fn fx_placeholder(&mut self, placeholder_name: &str) -> PyResult<PyObject> {
self.graph.call_method(self.py, "placeholder", (placeholder_name, ), None)
}
fn fx_get_attr(&mut self, parameter_name: &str) -> PyResult<PyObject> {
self.graph.call_method(self.py, "get_attr", (parameter_name, ), None)
}
fn fx_call_function(&mut self, function_name: &str, args: impl ToPyObject<ObjectType = PyTuple>, kwargs: Option<&PyDict>) -> PyResult<PyObject> {
let py_function = self.py.eval(function_name, None, None)?;
self.graph.call_method(self.py, "call_function", (py_function, args, kwargs), None)
}
fn fx_call_method(&mut self, method_name: &str, args: impl ToPyObject<ObjectType = PyTuple>, kwargs: Option<&PyDict>) -> PyResult<PyObject> {
self.graph.call_method(self.py, "call_method", (method_name, args, kwargs), None)
}
fn fx_output(&mut self, output: PyObject) -> PyResult<PyObject> {
self.graph.call_method(self.py, "output", (output, ), None)
}
fn get_shape_by_property(&self, property: Property) -> Shape {
if let Property::HasTensor(tensor_id, rel) = property {
let tensor = &self.rgraph[tensor_id];
match rel {
TensorRelation::Identity | TensorRelation::Reduce => tensor.shape.clone(),
TensorRelation::Gather(dim) => {
let dim = dim as usize;
let mut shape = tensor.shape.clone();
shape[dim] = sharding_round(shape[dim], &self.sharding_ratios[tensor.segment_id.0])[self.rank];
shape
}
}
} else {
unreachable!()
}
}
fn shard_inplace(&mut self, name: &str, sharding_lengths: &[usize], dim: Dimension) -> PyResult<()> {
if let Some(x) = self.sharded_paramters.get(name) {
assert_eq!(*x, dim);
return Ok(())
} else {
self.sharded_paramters.insert(name.to_string(), dim);
}
self.py.run("split_param_or_buffer(graph_module, target, sharding_lengths, dim, rank)", None, Some(&py_dict!(self.py,
graph_module => self.module,
target => name,
sharding_lengths => sharding_lengths,
dim => dim,
rank => self.rank
)))
}
}
pub struct Op {
py_name: String,
codegen: Box<dyn Fn(Python, &PyObject, &[PyObject], &[Shape]) -> PyResult<SVec<PyObject, 1>>>,
flops: Box<dyn Fn(&[SymbolicShape]) -> Expression>,
info: BTreeMap<String, String>, // additional info for generating triples
}
impl Debug for Op {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Op")
.field("py_name", &self.py_name)
.finish()
}
}
struct ParserContext<'py, 'g, 's, 'r> {
py: Python<'py>,
graph: &'g mut RGraph,
current_segment: &'s mut SegmentId,
results: &'r mut Vec<Option<EvalResult>>
}
#[derive(Debug, Clone)]
enum EvalResult {
Tensor(RTensorId),
Tuple(SVec<RTensorId>),
}
impl EvalResult {
fn as_tensor(&self) -> RTensorId {
match self {
EvalResult::Tensor(id) => *id,
EvalResult::Tuple(_) => panic!("not a tensor")
}
}
fn as_tuple(&self) -> &[RTensorId] {
match self {
EvalResult::Tensor(_) => panic!("not a tuple"),
EvalResult::Tuple(ids) => ids
}
}
}
fn initialize_parsing_handlers(py: Python) -> PyResult<BTreeMap<*mut (), &'static dyn Fn(ParserContext, PyObject) -> PyResult<()>>> {
let mut parsing_handlers: BTreeMap<*mut (), &'static dyn Fn(ParserContext, PyObject) -> PyResult<()>> = BTreeMap::new();
let tensor_class = py.eval("torch.Tensor", None, None)?;
parsing_handlers.insert(py.eval("torch.nn.functional.linear", None, None)?.as_ptr() as _, &handle_linear);
fn handle_linear(ctx: ParserContext, py_node: PyObject) -> PyResult<()> {
let py_id: usize = py_node.getattr(ctx.py, "meta")?.get_item(ctx.py, "id")?.extract(ctx.py)?;
let py_input_input_node = py_node.getattr(ctx.py, "kwargs")?.get_item(ctx.py, "input")?;
let py_input_weight_node = py_node.getattr(ctx.py, "kwargs")?.get_item(ctx.py, "weight")?;