-
Notifications
You must be signed in to change notification settings - Fork 505
/
Copy pathinit_python_bindings.cpp
3050 lines (2885 loc) · 127 KB
/
init_python_bindings.cpp
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
#include <ATen/dlpack.h>
#include <Python.h>
#include <c10/core/Device.h>
#include <google/protobuf/text_format.h>
#include <torch/csrc/autograd/utils/wrap_outputs.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/jit/python/pybind.h>
#include <torch/csrc/lazy/backend/backend_data.h>
#include <torch/csrc/lazy/core/config.h>
#include <torch/csrc/lazy/core/ir_util.h>
#include <torch/csrc/lazy/core/lazy_graph_executor.h>
#include <cstring>
#include <fstream>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/synchronization/blocking_counter.h"
#include "absl/types/variant.h"
#include "pybind11/attr.h"
#include "pybind11/cast.h"
#include "pybind11/detail/common.h"
#include "pybind11/functional.h"
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
#include "pybind11/pytypes.h"
#include "pybind11/stl.h"
#include "pybind11/stl_bind.h"
#include "torch_xla/csrc/XLANativeFunctions.h"
#include "torch_xla/csrc/aten_autograd_ops.h"
#include "torch_xla/csrc/aten_fallback.h"
#include "torch_xla/csrc/aten_xla_bridge.h"
#include "torch_xla/csrc/device.h"
#include "torch_xla/csrc/dl_convertor.h"
#include "torch_xla/csrc/dtype.h"
#include "torch_xla/csrc/dynamic_shape_detector.h"
#include "torch_xla/csrc/helpers.h"
#include "torch_xla/csrc/ir.h"
#include "torch_xla/csrc/ir_dump_util.h"
#include "torch_xla/csrc/layout_manager.h"
#include "torch_xla/csrc/ops/device_data.h"
#include "torch_xla/csrc/ops/xla_ops.h"
#include "torch_xla/csrc/runtime/computation_client.h"
#include "torch_xla/csrc/runtime/env_vars.h"
#include "torch_xla/csrc/runtime/metrics.h"
#include "torch_xla/csrc/runtime/metrics_analysis.h"
#include "torch_xla/csrc/runtime/metrics_reader.h"
#include "torch_xla/csrc/runtime/pjrt_computation_client.h"
#include "torch_xla/csrc/runtime/pjrt_registry.h"
#include "torch_xla/csrc/runtime/profiler.h"
#include "torch_xla/csrc/runtime/runtime.h"
#include "torch_xla/csrc/runtime/sys_util.h"
#include "torch_xla/csrc/runtime/util.h"
#include "torch_xla/csrc/runtime/xla_coordinator.h"
#include "torch_xla/csrc/runtime/xla_util.h"
#include "torch_xla/csrc/shape_helper.h"
#include "torch_xla/csrc/tensor_impl.h"
#include "torch_xla/csrc/tensor_methods.h"
#include "torch_xla/csrc/tensor_util.h"
#include "torch_xla/csrc/torch_util.h"
#include "torch_xla/csrc/version.h"
#include "torch_xla/csrc/xla_backend_impl.h"
#include "torch_xla/csrc/xla_graph_executor.h"
#include "torch_xla/csrc/xla_op_builder.h"
#include "torch_xla/csrc/xla_sharding_util.h"
#include "tsl/platform/env.h"
#include "tsl/profiler/lib/traceme.h"
#include "xla/hlo/parser/hlo_parser.h"
#include "xla/pjrt/distributed/distributed.h"
#include "xla/python/profiler/internal/traceme_wrapper.h"
namespace torch_xla {
namespace {
static int64_t seed_info_id = -127389;
struct NoGilSection {
NoGilSection() : state(PyEval_SaveThread()) {}
~NoGilSection() { PyEval_RestoreThread(state); }
PyThreadState* state = nullptr;
};
class PyPjRtPlugin : public runtime::PjRtPlugin {
public:
using runtime::PjRtPlugin::PjRtPlugin;
std::string library_path() const override {
PYBIND11_OVERRIDE_PURE(std::string, runtime::PjRtPlugin, library_path, );
}
// Templates with commas confuse pybind's macros, so use an alias here
// See https://github.com/pybind/pybind11/issues/2185#issuecomment-634005168
using PjRtCreateOptions = std::unordered_map<std::string, xla::PjRtValueType>;
const PjRtCreateOptions client_create_options() const override {
PYBIND11_OVERRIDE_PURE(PjRtCreateOptions, runtime::PjRtPlugin,
client_create_options, );
}
bool requires_xla_coordinator() const override {
PYBIND11_OVERRIDE_PURE(bool, runtime::PjRtPlugin,
requires_xla_coordinator, );
}
};
std::optional<torch::lazy::BackendDevice> GetOptionalDevice(
const std::string& device_str) {
if (device_str.empty()) {
return std::nullopt;
}
return bridge::AtenDeviceToXlaDevice(c10::Device(device_str));
}
torch::lazy::BackendDevice GetDeviceOrCurrent(const std::string& device_str) {
if (device_str.empty()) {
return bridge::GetCurrentDevice();
}
return bridge::AtenDeviceToXlaDevice(c10::Device(device_str));
}
void WaitDeviceOps(absl::Span<const std::string> devices = {}) {
XLAGraphExecutor::Get()->WaitDeviceOps(devices);
runtime::GetComputationClient()->WaitDeviceOps(devices);
}
void PrepareToExit() {
runtime::ComputationClient* client =
runtime::GetComputationClientIfInitialized();
if (client != nullptr) {
auto xla_device = GetDeviceOrCurrent("");
SetAllReduceToken(xla_device, nullptr);
WaitDeviceOps();
}
}
std::string GetTensorsDump(
const std::vector<at::Tensor>& tensors,
const std::function<
std::string(absl::Span<const torch::lazy::Node* const>)>& coverter) {
std::vector<const torch::lazy::Node*> nodes;
std::vector<torch::lazy::Value> values;
for (auto& tensor : tensors) {
XLATensorPtr xtensor = bridge::GetXlaTensor(tensor);
values.push_back(xtensor->GetIrValue());
nodes.push_back(values.back().node.get());
}
return coverter(nodes);
}
std::string SetCurrentThreadDevice(const std::string& device_str) {
c10::Device prev_device = bridge::SetCurrentDevice(c10::Device(device_str));
std::stringstream ss;
ss << prev_device;
return ss.str();
}
std::string GetCurrentThreadDevice() {
return bridge::GetCurrentAtenDevice().str();
}
std::vector<std::string> GetXlaDevices(
const std::vector<std::string>& devices) {
std::vector<std::string> xla_devices;
xla_devices.reserve(devices.size());
for (auto& device_str : devices) {
torch::lazy::BackendDevice device =
bridge::AtenDeviceToXlaDevice(c10::Device(device_str));
xla_devices.emplace_back(device.toString());
}
return xla_devices;
}
std::vector<XLATensorPtr> GetXlaTensors(const std::vector<at::Tensor>& tensors,
bool want_all) {
std::vector<XLATensorPtr> xtensors;
xtensors.reserve(tensors.size());
if (want_all) {
for (auto& tensor : tensors) {
xtensors.push_back(bridge::GetXlaTensor(tensor));
}
} else {
for (auto& tensor : tensors) {
auto xtensor = bridge::TryGetXlaTensor(tensor);
if (xtensor) {
xtensors.push_back(xtensor);
}
}
}
return xtensors;
}
bool IsNonDeviceDataIR(const at::Tensor& tensor) {
XLATensorPtr xtensor = bridge::GetXlaTensor(tensor);
return xtensor->CurrentIrValue() &&
!DeviceData::Cast(xtensor->CurrentIrValue().node.get());
}
std::vector<std::vector<int64_t>> CreateReduceGroups(const py::list& groups) {
std::vector<std::vector<int64_t>> replica_groups;
for (auto& group : groups) {
replica_groups.emplace_back();
for (auto& replica_id : group.cast<py::list>()) {
replica_groups.back().push_back(replica_id.cast<int64_t>());
}
}
return replica_groups;
}
std::vector<at::Tensor> XlaCustomCall(
const std::vector<at::Tensor>& inputs, const std::string& payload,
const std::vector<std::vector<int64_t>>& output_shapes,
const std::vector<py::object>& output_dtypes, bool is_tpu) {
std::vector<at::ScalarType> dtypes;
dtypes.reserve(output_dtypes.size());
for (auto& dtype : output_dtypes) {
dtypes.push_back(reinterpret_cast<THPDtype*>(dtype.ptr())->scalar_type);
}
if (is_tpu) {
return bridge::AtenFromXlaTensors(tensor_methods::tpu_custom_call(
bridge::GetXlaTensors(inputs), payload, output_shapes, dtypes));
}
return bridge::AtenFromXlaTensors(tensor_methods::gpu_custom_call(
bridge::GetXlaTensors(inputs), payload, output_shapes, dtypes));
}
std::vector<std::vector<int>> ExtractXlaDotGeneralDimVectors(
const py::tuple& dimension_numbers) {
// Expect Python arg `dimension_numbers` to be
// (([lhs_contract_dim0,...], [rhs_contract_dim0,...]), ([lhs_batch_dim0,...],
// [rhs_batch_dim0,...]))
std::vector<std::vector<int>> dim_vectors;
XLA_CHECK_EQ(dimension_numbers.size(), 2)
<< "dimension_numbers must be a tuple of 2 elements";
for (int i = 0; i < 2; ++i) {
XLA_CHECK(py::isinstance<py::tuple>(dimension_numbers[i]))
<< "_xla_dot_general: Dimension_numbers[" << i << "] must be a tuple";
py::tuple cast_tuple = py::cast<py::tuple>(dimension_numbers[i]);
XLA_CHECK(cast_tuple.size() == 0 || cast_tuple.size() == 2)
<< "_xla_dot_general: Contracting/batch dims must be speficied for "
"both lhs and rhs or neither";
if (cast_tuple.size() == 0) {
// Empty tuple means no contracting/batch dims
dim_vectors.push_back({});
dim_vectors.push_back({});
} else {
for (const auto& dim_list : cast_tuple) {
XLA_CHECK(py::isinstance<py::list>(dim_list))
<< "_xla_dot_general: lhs/rhs contracting/batch dims must be a "
"list";
const py::list& dim_list_casted = py::cast<py::list>(dim_list);
std::vector<int> dim_vector;
for (const auto& item : dim_list_casted) {
XLA_CHECK(py::isinstance<py::int_>(item))
<< "_xla_dot_general: lhs/rhs contracting/batch dims must be a "
"list of integers";
dim_vector.push_back(py::cast<int>(item));
}
dim_vectors.push_back(dim_vector);
}
}
}
return dim_vectors;
}
at::Tensor XlaDotGeneral(const at::Tensor& lhs, const at::Tensor& rhs,
const std::vector<std::vector<int>>& dim_vectors,
std::optional<py::object> preferred_element_type) {
std::optional<at::ScalarType> at_preferred_element_type;
if (preferred_element_type.has_value()) {
at_preferred_element_type =
reinterpret_cast<THPDtype*>(preferred_element_type.value().ptr())
->scalar_type;
}
return bridge::AtenFromXlaTensor(tensor_methods::xla_dot_general(
bridge::GetXlaTensor(lhs), bridge::GetXlaTensor(rhs), dim_vectors,
at_preferred_element_type));
}
std::vector<std::pair<int64_t, int64_t>> CreateSourceTargetPairs(
const py::list& pairs) {
std::vector<std::pair<int64_t, int64_t>> source_target_pairs;
for (auto& pair : pairs) {
const auto& pylist_pair = pair.cast<py::list>();
XLA_CHECK_EQ(len(pylist_pair), 2);
source_target_pairs.push_back(
{pylist_pair[0].cast<int64_t>(), pylist_pair[1].cast<int64_t>()});
}
return source_target_pairs;
}
void AllReduceInPlace(const std::string& reduce_type,
const std::vector<at::Tensor>& tensors, double scale,
const std::vector<std::vector<int64_t>>& replica_groups,
bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
std::vector<XLATensorPtr> xtensors =
GetXlaTensors(tensors, /*want_all=*/true);
tensor_methods::all_reduce(xtensors, GetReduceType(reduce_type), scale,
replica_groups, pin_layout);
std::vector<XLATensorPtr> new_xtensors =
GetXlaTensors(tensors, /*want_all=*/true);
bridge::ReplaceXlaTensor(tensors, new_xtensors);
}
at::Tensor AllReduce(const std::string& reduce_type, const at::Tensor& input,
double scale,
const std::vector<std::vector<int64_t>>& replica_groups,
bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
auto result = tensor_methods::all_reduce(bridge::GetXlaTensor(input),
GetReduceType(reduce_type), scale,
replica_groups, pin_layout);
return bridge::AtenFromXlaTensor(std::move(result));
}
at::Tensor DynamicExpand(const at::Tensor& input,
const std::vector<int64_t>& size,
const at::Tensor& src_tensor, int src_dim,
int target_dim) {
XLATensorPtr result = tensor_methods::dynamic_expand(
bridge::GetXlaTensor(input), size, bridge::GetXlaTensor(src_tensor),
src_dim, target_dim);
return bridge::AtenFromXlaTensor(std::move(result));
}
at::Tensor DynamicView(const at::Tensor& input,
const std::vector<int64_t>& size,
const at::Tensor& src_tensor, int src_dim,
int target_dim, float mul_scaler) {
XLATensorPtr result = tensor_methods::dynamic_view(
bridge::GetXlaTensor(input), size, bridge::GetXlaTensor(src_tensor),
src_dim, target_dim, mul_scaler);
return bridge::AtenFromXlaTensor(std::move(result));
}
at::Tensor CastInt4(const at::Tensor& weight,
const std::vector<int>& int4_weight_values) {
auto result = tensor_methods::cast_int4(bridge::GetXlaTensor(weight),
int4_weight_values);
return bridge::AtenFromXlaTensor(std::move(result));
}
at::Tensor QuantizeTensor(const at::Tensor& input,
const std::vector<float>& scale_list,
const std::vector<int>& zero_point_list,
int quant_min, int quant_max,
const std::string& dtype, int axis) {
auto result = tensor_methods::quantize_tensor(
bridge::GetXlaTensor(input), scale_list, zero_point_list, quant_min,
quant_max, dtype, axis);
return bridge::AtenFromXlaTensor(std::move(result));
}
at::Tensor DequantizeTensor(const at::Tensor& input,
const std::vector<float>& scale_list,
const std::vector<int>& zero_point_list,
int quant_min, int quant_max,
const std::string& dtype, int axis) {
auto result = tensor_methods::dequantize_tensor(
bridge::GetXlaTensor(input), scale_list, zero_point_list, quant_min,
quant_max, dtype, axis);
return bridge::AtenFromXlaTensor(std::move(result));
}
std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>> ReduceScatter(
const std::string& reduce_type, const at::Tensor& input,
const std::shared_ptr<torch::lazy::Value>& token, double scale,
int64_t scatter_dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
XLATensorPtr result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::reduce_scatter(
bridge::GetXlaTensor(input), *token, GetReduceType(reduce_type), scale,
scatter_dim, shard_count, replica_groups, pin_layout);
return std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>>(
bridge::AtenFromXlaTensor(std::move(result)),
std::make_shared<torch::lazy::Value>(new_token));
}
std::shared_ptr<torch::lazy::Value> ReduceScatterOut(
const std::string& reduce_type, at::Tensor& output, const at::Tensor& input,
const std::shared_ptr<torch::lazy::Value>& token, double scale,
int64_t scatter_dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
XLATensorPtr out = bridge::GetXlaTensor(output);
torch::lazy::Value new_token;
new_token = tensor_methods::reduce_scatter_out(
out, bridge::GetXlaTensor(input), *token, GetReduceType(reduce_type),
scale, scatter_dim, shard_count, replica_groups, pin_layout);
return std::make_shared<torch::lazy::Value>(new_token);
}
std::pair<std::vector<at::Tensor>, std::shared_ptr<torch::lazy::Value>>
ReduceScatterCoalesced(const std::string& reduce_type,
const std::vector<at::Tensor>& inputs,
const std::shared_ptr<torch::lazy::Value>& token,
double scale, int64_t scatter_dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups,
bool pin_layout) {
std::vector<XLATensorPtr> xtensors = GetXlaTensors(inputs, /*want_all=*/true);
std::vector<XLATensorPtr> result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::reduce_scatter_coalesced(
xtensors, *token, GetReduceType(reduce_type), scale, scatter_dim,
shard_count, replica_groups, pin_layout);
std::vector<at::Tensor> aten_result;
for (auto& xt : result) {
aten_result.emplace_back(bridge::AtenFromXlaTensor(std::move(xt)));
}
return {aten_result, std::make_shared<torch::lazy::Value>(new_token)};
}
std::shared_ptr<torch::lazy::Value> ReduceScatterCoalescedOut(
const std::string& reduce_type, std::vector<at::Tensor>& outputs,
const std::vector<at::Tensor>& inputs,
const std::shared_ptr<torch::lazy::Value>& token, double scale,
int64_t scatter_dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
std::vector<XLATensorPtr> xtensors_out =
GetXlaTensors(outputs, /*want_all=*/true);
std::vector<XLATensorPtr> xtensors = GetXlaTensors(inputs, /*want_all=*/true);
torch::lazy::Value new_token;
new_token = tensor_methods::reduce_scatter_coalesced_out(
xtensors_out, xtensors, *token, GetReduceType(reduce_type), scale,
scatter_dim, shard_count, replica_groups, pin_layout);
return std::make_shared<torch::lazy::Value>(new_token);
}
at::Tensor AllGather(const at::Tensor& input, int64_t dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups,
bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
auto result =
tensor_methods::all_gather(bridge::GetXlaTensor(input), dim, shard_count,
replica_groups, pin_layout);
return bridge::AtenFromXlaTensor(std::move(result));
}
std::shared_ptr<torch::lazy::Value> AllGatherOut(
at::Tensor& output, const at::Tensor& input,
const std::shared_ptr<torch::lazy::Value>& token, int64_t dim,
int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
XLATensorPtr out = bridge::GetXlaTensor(output);
torch::lazy::Value new_token;
new_token = tensor_methods::all_gather_out(out, bridge::GetXlaTensor(input),
*token, dim, shard_count,
replica_groups, pin_layout);
return std::make_shared<torch::lazy::Value>(new_token);
}
std::pair<std::vector<at::Tensor>, std::shared_ptr<torch::lazy::Value>>
AllGatherCoalesced(const std::vector<at::Tensor>& tensors,
const std::shared_ptr<torch::lazy::Value>& token,
int64_t dim, int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups,
bool pin_layout) {
std::vector<XLATensorPtr> xtensors =
GetXlaTensors(tensors, /*want_all=*/true);
std::vector<XLATensorPtr> result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::all_gather_coalesced(
xtensors, *token, dim, shard_count, replica_groups, pin_layout);
std::vector<at::Tensor> aten_result;
for (auto& xt : result) {
aten_result.emplace_back(bridge::AtenFromXlaTensor(std::move(xt)));
}
return {aten_result, std::make_shared<torch::lazy::Value>(new_token)};
}
std::shared_ptr<torch::lazy::Value> AllGatherCoalescedOut(
std::vector<at::Tensor>& outputs, const std::vector<at::Tensor>& inputs,
const std::shared_ptr<torch::lazy::Value>& token, int64_t dim,
int64_t shard_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
std::vector<XLATensorPtr> xtensors_out =
GetXlaTensors(outputs, /*want_all=*/true);
std::vector<XLATensorPtr> xtensors = GetXlaTensors(inputs, /*want_all=*/true);
torch::lazy::Value new_token;
new_token = tensor_methods::all_gather_coalesced_out(
xtensors_out, xtensors, *token, dim, shard_count, replica_groups,
pin_layout);
return std::make_shared<torch::lazy::Value>(new_token);
}
std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>> AllToAll(
const at::Tensor& input, const std::shared_ptr<torch::lazy::Value>& token,
int64_t split_dimension, int64_t concat_dimension, int64_t split_count,
const std::vector<std::vector<int64_t>>& replica_groups, bool pin_layout) {
TORCH_LAZY_FN_COUNTER_TIMED_TRACING("xla::");
XLATensorPtr result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::all_to_all(
bridge::GetXlaTensor(input), *token, split_dimension, concat_dimension,
split_count, replica_groups, pin_layout);
return std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>>(
bridge::AtenFromXlaTensor(std::move(result)),
std::make_shared<torch::lazy::Value>(new_token));
}
std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>> CollectivePermute(
const at::Tensor& input, const std::shared_ptr<torch::lazy::Value>& token,
const std::vector<std::pair<int64_t, int64_t>>& source_target_pairs) {
XLATensorPtr result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::collective_permute(
bridge::GetXlaTensor(input), *token, source_target_pairs);
return std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>>(
bridge::AtenFromXlaTensor(std::move(result)),
std::make_shared<torch::lazy::Value>(new_token));
}
void OptimizationBarrier_(std::vector<at::Tensor>& tensors) {
std::vector<XLATensorPtr> xtensors =
GetXlaTensors(tensors, /*want_all=*/false);
tensor_methods::optimization_barrier_(xtensors);
}
std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>> Send(
const at::Tensor& input, const std::shared_ptr<torch::lazy::Value>& token,
int64_t channel_id) {
XLATensorPtr result;
torch::lazy::Value new_token;
std::tie(result, new_token) =
tensor_methods::send(bridge::GetXlaTensor(input), *token, channel_id);
return {bridge::AtenFromXlaTensor(std::move(result)),
std::make_shared<torch::lazy::Value>(new_token)};
}
std::pair<at::Tensor, std::shared_ptr<torch::lazy::Value>> Recv(
at::Tensor& output, const std::shared_ptr<torch::lazy::Value>& token,
int64_t channel_id) {
XLATensorPtr out = bridge::GetXlaTensor(output);
XLATensorPtr result;
torch::lazy::Value new_token;
std::tie(result, new_token) = tensor_methods::recv(out, *token, channel_id);
return {bridge::AtenFromXlaTensor(std::move(result)),
std::make_shared<torch::lazy::Value>(new_token)};
}
void SyncTensors(const std::vector<at::Tensor>& tensors,
const std::vector<std::string>& devices, bool wait,
bool sync_xla_data, bool warm_up_cache_only = false) {
std::vector<XLATensorPtr> xtensors =
GetXlaTensors(tensors, /*want_all=*/false);
XLAGraphExecutor::Get()->SyncTensorsGraph(&xtensors, devices, wait,
sync_xla_data, warm_up_cache_only);
}
void SyncLiveTensors(const std::string& device_str,
const std::vector<std::string>& devices, bool wait) {
auto opt_device = GetOptionalDevice(device_str);
XLAGraphExecutor::Get()->SyncLiveTensorsGraph(
opt_device ? &opt_device.value() : nullptr, devices, wait);
}
void StepMarker(const std::string& device_str,
const std::vector<std::string>& devices, bool wait,
bool reset_scope) {
tsl::profiler::TraceMe activity("StepMarker",
tsl::profiler::TraceMeLevel::kInfo);
torch::lazy::BackendDevice device = GetDeviceOrCurrent(device_str);
XLAGraphExecutor::Get()->SyncLiveTensorsGraph(&device, devices, wait);
XLAGraphExecutor::Get()->MarkStep(device, reset_scope);
bool debug_mode = runtime::sys_util::GetEnvBool("PT_XLA_DEBUG", false);
if (TF_PREDICT_FALSE(debug_mode)) {
std::string report = runtime::metrics::CreatePerformanceReport(
runtime::GetComputationClient()->GetMetrics());
if (!report.empty()) {
std::string fout =
runtime::sys_util::GetEnvString("PT_XLA_DEBUG_FILE", "");
if (TF_PREDICT_FALSE(!fout.empty())) {
std::ofstream out_file(fout, std::ios_base::app);
out_file << report;
} else {
std::cout << report;
}
}
}
}
void SetRngSeed(uint64_t seed, const std::string& device_str) {
torch::lazy::BackendDevice device = GetDeviceOrCurrent(device_str);
XLAGraphExecutor::Get()->SetRngSeed(device, seed);
}
uint64_t GetRngSeed(const std::string& device_str) {
return XLAGraphExecutor::Get()->GetRunningSeed(
GetDeviceOrCurrent(device_str));
}
std::string GetTensorsHloGraph(const std::vector<at::Tensor>& tensors,
EmitMode mode) {
std::vector<XLATensorPtr> xtensors =
GetXlaTensors(tensors, /*want_all=*/false);
return XLAGraphExecutor::Get()->DumpHloComputation(xtensors, mode);
}
std::string GetXLAShardingSpec(const XLATensorPtr xtensor) {
auto sharding_spec = xtensor->sharding_spec();
if (sharding_spec != nullptr) {
auto hlo_sharding = xla::HloSharding::FromProto(sharding_spec->sharding);
return hlo_sharding->ToString();
}
return std::string();
}
std::string GetXLATensorDebugInfo(const at::Tensor& tensor) {
auto xtensor = bridge::TryGetXlaTensor(tensor);
if (!xtensor) {
return "Not a XLATensor\n";
}
std::stringstream ss;
ss << "XLATensor {\n";
ss << "TensorID: " << xtensor->GetUniqueId() << "\n";
ss << "AliasID: " << xtensor->data()->alias_id << "\n";
ss << "Device: " << xtensor->GetDevice() << "\n";
ss << "XLA Shape: " << xtensor->shape().get().ToString() << "\n";
std::string sharding_spec_str = GetXLAShardingSpec(xtensor);
ss << "ShardingSpec: "
<< ((sharding_spec_str.size() > 0) ? sharding_spec_str : "None");
ss << "\n";
torch::lazy::Value ir_value = xtensor->CurrentIrValue();
ss << "IR: ";
if (ir_value) {
ss << ir_value.node->ToString() << "\n";
} else {
ss << "None\n";
}
torch::lazy::BackendDataPtr handle = xtensor->CurrentDataHandle();
if (handle) {
auto data =
std::dynamic_pointer_cast<runtime::ComputationClient::Data>(handle);
ss << data->ToString();
} else {
ss << "XLAData: None\n";
}
auto at_tensor = xtensor->CurrentTensorData();
ss << "Tensor on host: ";
if (at_tensor) {
ss << "with size " << at_tensor->sizes() << "\n";
} else {
ss << "None\n";
}
ss << "}\n";
return ss.str();
}
std::string GetLiveTensorsReport(size_t nodes_threshold,
const std::string& device_str) {
auto opt_device = GetOptionalDevice(device_str);
auto tensors = XLAGraphExecutor::Get()->GetLiveTensors(
opt_device ? &opt_device.value() : nullptr);
std::stringstream ss;
for (auto& tensor : tensors) {
torch::lazy::Value ir_value = tensor->CurrentIrValue();
if (ir_value) {
std::vector<const torch::lazy::Node*> roots({ir_value.node.get()});
auto post_order = torch::lazy::Util::ComputePostOrder(roots);
if (post_order.size() > nodes_threshold) {
ss << "Tensor: id=" << tensor->GetUniqueId()
<< ", shape=" << tensor->shape().get()
<< ", device=" << tensor->GetDevice()
<< ", ir_nodes=" << post_order.size() << "\n";
for (size_t i = post_order.size(); i > 0; --i) {
if (!post_order[i - 1]->metadata().frame_info.empty()) {
ss << post_order[i - 1]->metadata().frame_info;
break;
}
}
ss << DumpUtil::PostOrderToText(post_order, roots);
ss << "\n\n";
}
}
}
return ss.str();
}
void ClearPendingIrs(const std::string& device_str) {
auto opt_device = GetOptionalDevice(device_str);
XLA_CHECK(opt_device);
auto tensors = XLAGraphExecutor::Get()->GetLiveTensors(&opt_device.value());
XLAGraphExecutor::Get()->ClearPendingIrs(tensors, opt_device.value());
}
std::ptrdiff_t GetTensorViewAliasId(const at::Tensor& tensor) {
XLATensorPtr xtensor = bridge::GetXlaTensor(tensor);
return xtensor->GetViewAliasId();
}
std::ptrdiff_t GetTensorId(const at::Tensor& tensor) {
XLATensorPtr xtensor = bridge::GetXlaTensor(tensor);
return xtensor->GetUniqueId();
}
std::vector<at::Tensor> GetXlaTensorsFromAten(
const std::vector<at::Tensor>& aten_tensors,
const std::vector<std::string>& devices,
const std::optional<std::vector<XLATensor::ShardingSpecPtr>>
sharding_specs) {
std::vector<std::shared_ptr<torch::lazy::BackendData>> data_handles;
if (sharding_specs.has_value()) {
data_handles = CreateTensorsData(aten_tensors, sharding_specs.value(),
GetXlaDevices(devices));
} else {
data_handles = CreateTensorsData(aten_tensors, GetXlaDevices(devices));
}
std::vector<at::Tensor> xla_tensors;
xla_tensors.reserve(data_handles.size());
for (int i = 0; i < data_handles.size(); i++) {
auto& data_handle = data_handles[i];
XLATensorPtr xla_tensor = XLATensor::Create(std::move(data_handle));
if (sharding_specs.has_value() && sharding_specs.value()[i] != nullptr) {
xla_tensor->SetShardingSpec(*sharding_specs.value()[i]);
}
xla_tensors.push_back(bridge::AtenFromXlaTensor(std::move(xla_tensor)));
}
return xla_tensors;
}
at::Tensor GetXlaTensorDimensionSize(const at::Tensor& tensor, int64_t dim) {
XLATensorPtr xtensor = bridge::GetXlaTensor(tensor);
return bridge::AtenFromXlaTensor(
tensor_methods::get_dimensions_size(xtensor, {dim}));
}
template <class T>
py::object GetMetricData(const T* data) {
double accumulator = 0.0;
size_t total_samples = 0;
auto samples = data->Samples(&accumulator, &total_samples);
auto py_samples = py::tuple(samples.size());
for (size_t i = 0; i < samples.size(); ++i) {
auto sample = py::tuple(2);
sample[0] = 1.0e-9 * samples[i].timestamp_ns;
sample[1] = samples[i].value;
py_samples[i] = sample;
}
auto result = py::tuple(3);
result[0] = total_samples;
result[1] = accumulator;
result[2] = py_samples;
return result;
}
py::object GetMetricData(const std::string& name) {
if (auto* data = torch::lazy::GetMetric(name)) {
return GetMetricData<torch::lazy::MetricData>(data);
}
if (auto* data = runtime::metrics::GetMetric(name)) {
return GetMetricData<runtime::metrics::MetricData>(data);
}
return py::none();
}
py::object GetRevisions() {
auto py_dict = py::dict();
py_dict["xla"] = std::string(XLA_GITREV);
py_dict["torch"] = std::string(TORCH_GITREV);
return py_dict;
}
std::vector<at::Tensor> XlaUserComputation(
const std::string& opname, const std::vector<at::Tensor>& inputs,
runtime::ComputationClient::ComputationPtr computation) {
std::vector<XLATensorPtr> xinputs = GetXlaTensors(inputs, /*want_all=*/true);
std::vector<XLATensorPtr> xresults =
tensor_methods::user_computation(opname, xinputs, std::move(computation));
std::vector<at::Tensor> results;
for (auto& xresult : xresults) {
at::Tensor tensor = bridge::AtenFromXlaTensor(std::move(xresult));
results.push_back(
torch::autograd::make_variable(tensor, /*requires_grad=*/false));
}
return results;
}
runtime::ComputationClient::ComputationPtr CreateComputation(
const std::string& name, xla::XlaOp root) {
xla::XlaComputation computation = ConsumeValue(root.builder()->Build(root));
return std::make_shared<runtime::ComputationClient::Computation>(
name, std::move(computation));
}
runtime::ComputationClient::ComputationPtr CreateComputationFromProto(
const std::string& name, const std::string& module_proto) {
xla::HloModuleProto proto;
proto.ParseFromString(module_proto);
xla::XlaComputation computation(std::move(proto));
return std::make_shared<runtime::ComputationClient::Computation>(
name, std::move(computation));
}
xla::Shape GetTensorShape(const at::Tensor& tensor,
const std::string& device_str) {
auto xtensor = bridge::TryGetXlaTensor(tensor);
if (xtensor) {
return xtensor->shape();
}
torch::lazy::BackendDevice device = GetDeviceOrCurrent(device_str);
return CreateComputationShapeFromTensor(tensor, &device);
}
py::dict GetMemoryInfo(const std::string& device_str) {
runtime::ComputationClient::MemoryInfo mem_info;
{
NoGilSection nogil;
torch::lazy::BackendDevice device = GetDeviceOrCurrent(device_str);
mem_info =
runtime::GetComputationClient()->GetMemoryInfo(device.toString());
}
auto py_dict = py::dict();
py_dict["bytes_used"] = mem_info.bytes_used;
py_dict["bytes_limit"] = mem_info.bytes_limit;
py_dict["peak_bytes_used"] = mem_info.peak_bytes_used;
return py_dict;
}
// Must be called holding GIL as it reads Python objects. Also, Python objects
// are reference counted; reading py::dict will increase its reference count.
absl::flat_hash_map<std::string, std::variant<int, std::string>>
ConvertDictToMap(const py::dict& dictionary) {
absl::flat_hash_map<std::string, std::variant<int, std::string>> map;
for (const auto& item : dictionary) {
std::variant<int, std::string> value;
try {
value = item.second.cast<int>();
} catch (...) {
try {
value = item.second.cast<std::string>();
} catch (...) {
continue;
}
}
map.emplace(item.first.cast<std::string>(), value);
}
return map;
}
// Maps PT/XLA env vars to upstream torch::lazy env vars.
// Upstream lazy env vars defined in torch/csrc/lazy/core/config.h.
void MapXlaEnvVarsToLazy() {
static bool wants_frames =
runtime::sys_util::GetEnvBool("XLA_IR_DEBUG", false) |
runtime::sys_util::GetEnvBool("XLA_HLO_DEBUG", false);
FLAGS_torch_lazy_ir_debug = wants_frames;
static bool no_scalars =
runtime::sys_util::GetEnvBool("XLA_NO_SPECIAL_SCALARS", false);
FLAGS_torch_lazy_handle_special_scalars = !no_scalars;
FLAGS_torch_lazy_metrics_samples =
runtime::sys_util::GetEnvInt("XLA_METRICS_SAMPLES", 1024);
FLAGS_torch_lazy_metrics_percentiles = runtime::sys_util::GetEnvString(
"XLA_METRICS_PERCENTILES", "0.01:0.05:0.1:0.2:0.5:0.8:0.9:0.95:0.99");
}
at::Tensor MarkTensor(const at::Tensor& input, const std::string& info) {
XLATensorPtr result =
tensor_methods::mark_tensor(bridge::GetXlaTensor(input), info);
return bridge::AtenFromXlaTensor(std::move(result));
}
std::string GetPyTypeString(py::handle obj) {
std::string type = obj.attr("__class__").attr("__name__").cast<std::string>();
return type;
}
std::vector<bool> check_materialization_helper(
const std::vector<XLATensorPtr>& xtensors) {
std::vector<bool> need_materialization;
need_materialization.reserve(xtensors.size());
for (auto& xtensor : xtensors) {
if (!xtensor) {
// input tensor is not a xla tensor
need_materialization.push_back(false);
} else if (xtensor->CurrentDataHandle() != nullptr) {
// input tensor has xla_data which means it is already on device
need_materialization.push_back(false);
} else if (xtensor->CurrentIrValue().node != nullptr) {
torch::lazy::NodePtr node = xtensor->CurrentIrValue().node;
if (torch_xla::DeviceData::Cast(xtensor->CurrentIrValue().node.get()) !=
nullptr) {
need_materialization.push_back(false);
} else {
// input tensor is an IR other than DeviceData which means a
// compuation is required to get the value of this tensor.
need_materialization.push_back(true);
}
} else if (xtensor->CurrentTensorData().has_value()) {
need_materialization.push_back(false);
} else {
XLA_CHECK(false)
<< "_check_tensor_need_materialization "
"currently does not handle XLATensor without XLAData and IR";
}
}
return need_materialization;
}
void BuildProfilerSubmodule(py::module* m) {
py::module profiler = m->def_submodule("profiler", "Profiler integration");
py::class_<runtime::profiler::ProfilerServer,
std::unique_ptr<runtime::profiler::ProfilerServer>>
profiler_server_class(profiler, "ProfilerServer");
profiler.def(
"start_server",
[](int port) -> std::unique_ptr<runtime::profiler::ProfilerServer> {
auto server = absl::make_unique<runtime::profiler::ProfilerServer>();
server->Start(port);
return server;
},
py::arg("port"));
profiler.def(
"trace",
[](const char* service_addr, const char* logdir, int duration_ms,
int num_tracing_attempts, int timeout_s, int interval_s,
py::dict options) {
absl::flat_hash_map<std::string, std::variant<int, std::string>> opts =
ConvertDictToMap(options);
std::chrono::seconds sleep_s(interval_s);
absl::Status status;
{
NoGilSection nogil;
for (int i = 0; i <= timeout_s / interval_s; i++) {
status = runtime::profiler::Trace(service_addr, logdir, duration_ms,
num_tracing_attempts, opts);
if (status.ok()) {
return;
}
std::this_thread::sleep_for(sleep_s);
}
}
if (!status.ok()) {
PyErr_SetString(PyExc_RuntimeError, std::string(status.message()));
throw py::error_already_set();
}
},
py::arg("service_addr"), py::arg("logdir"), py::arg("duration_ms") = 1000,
py::arg("num_tracing_attempts") = 3, py::arg("timeout_s") = 120,
py::arg("interval_s") = 5, py::arg("options"));
py::class_<xla::profiler::TraceMeWrapper> traceme_class(profiler, "TraceMe",
py::module_local());
traceme_class.def(py::init<py::str, py::kwargs>())
.def("__enter__", [](py::object self) -> py::object { return self; })
.def("__exit__",
[](py::object self, const py::object& ex_type,
const py::object& ex_value,
const py::object& traceback) -> py::object {
py::cast<xla::profiler::TraceMeWrapper*>(self)->Stop();
return py::none();
})
.def("set_metadata", &xla::profiler::TraceMeWrapper::SetMetadata)
.def_static("is_enabled", &tsl::profiler::TraceMe::Active);
py::class_<torch::lazy::ScopePusher,
std::unique_ptr<torch::lazy::ScopePusher>>
scope_pusher_class(profiler, "ScopePusher");
profiler.def(
"scope_pusher",
[](const std::string& name) -> std::unique_ptr<torch::lazy::ScopePusher> {
return absl::make_unique<torch::lazy::ScopePusher>(name);
});
// Profiler Session Definition.
py::class_<runtime::profiler::TslProfilerSessionWrapper,
std::unique_ptr<runtime::profiler::TslProfilerSessionWrapper>>
profiler_session_class(profiler, "TslProfilerSessionWrapper");
profiler_session_class.def(
py::init(&runtime::profiler::TslProfilerSessionWrapper::Create));
profiler_session_class.def("stop", [](py::object self) -> py::bytes {
std::string xspace_str =
py::cast<runtime::profiler::TslProfilerSessionWrapper*>(self)->Stop();
return py::bytes(xspace_str);
});
profiler_session_class.def("export", [](py::object self, py::bytes xspace,
const std::string& dump_dir) {
const std::string xspace_str = xspace.cast<std::string>();
py::cast<runtime::profiler::TslProfilerSessionWrapper*>(self)->Export(
xspace_str, dump_dir);
});
}