-
Notifications
You must be signed in to change notification settings - Fork 74k
/
pjrt_c_api_client.cc
2312 lines (2061 loc) · 90.9 KB
/
pjrt_c_api_client.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2022 The OpenXLA Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "xla/pjrt/pjrt_c_api_client.h"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/span.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project
#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/Dialect/MLProgram/IR/MLProgram.h" // from @llvm-project
#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project
#include "mlir/IR/DialectRegistry.h" // from @llvm-project
#include "mlir/IR/OwningOpRef.h" // from @llvm-project
#include "mlir/Parser/Parser.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "stablehlo/dialect/Register.h" // from @stablehlo
#include "xla/client/xla_computation.h"
#include "xla/hlo/ir/hlo_module.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/mlir_hlo/mhlo/IR/register.h"
#include "xla/mlir_hlo/mhlo/transforms/passes.h"
#include "xla/pjrt/c/pjrt_c_api.h"
#include "xla/pjrt/c/pjrt_c_api_helpers.h"
#include "xla/pjrt/c/pjrt_c_api_profiler_extension.h"
#include "xla/pjrt/compile_options.pb.h"
#include "xla/pjrt/distributed/key_value_store_interface.h"
#include "xla/pjrt/mlir_to_hlo.h"
#include "xla/pjrt/pjrt_api.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_device_description.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/pjrt_layout.h"
#include "xla/service/computation_placer.h"
#include "xla/service/hlo.pb.h"
#include "xla/service/hlo_module_config.h"
#include "xla/shape.h"
#include "xla/shape_util.h"
#include "xla/status.h"
#include "xla/statusor.h"
#include "xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h"
#include "xla/util.h"
#include "xla/xla.pb.h"
#include "xla/xla_data.pb.h"
#include "tsl/framework/allocator.h"
#include "tsl/platform/casts.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
namespace xla {
// Helper macros
// Return error future if not success and frees the PJRT_Error returned by
// `expr`.
#define RETURN_FUTURE_IF_ERROR(expr, c_api) \
do { \
PJRT_Error* error = (expr); \
std::unique_ptr<PJRT_Error, pjrt::PJRT_ErrorDeleter> _error( \
error, pjrt::MakeErrorDeleter(c_api)); \
absl::Status _status = pjrt::PjrtErrorToStatus(_error.get(), c_api); \
if (!_status.ok()) { \
return PjRtFuture<>(_status); \
} \
} while (false)
// ---------------------------------- Client -----------------------------------
static StatusOr<const PjRtCApiTopologyDescription> InitClientTopoDesc(
const PJRT_Api* c_api, PJRT_Client* c_client) {
StatusOr<PJRT_TopologyDescription*> c_topo =
pjrt::GetTopologyDescription(c_client, c_api);
TF_RETURN_IF_ERROR(c_topo.status());
return PjRtCApiTopologyDescription(c_api, *c_topo, /*owned=*/false);
}
PjRtCApiClient::PjRtCApiClient(
const PJRT_Api* c_api, PJRT_Client* c_client,
std::unique_ptr<pjrt::PJRT_KeyValueCallbackData> kv_callback_data)
: c_api_(c_api),
c_client_(std::unique_ptr<PJRT_Client, ::pjrt::PJRT_ClientDeleter>(
c_client, ::pjrt::MakeClientDeleter(c_api))),
kv_callback_data_(std::move(kv_callback_data)),
topo_desc_(InitClientTopoDesc(c_api, c_client)),
// Example platform version string:
// PJRT C API
// TFRT TPU v2
// Built on Mar 4 2021 15:25:57 (1614900357) cl/360760169
platform_version_(absl::StrCat(
"PJRT C API\n", ::pjrt::GetPlatformVersion(c_client, c_api))),
platform_name_(::pjrt::GetPlatformName(c_client, c_api)),
platform_id_(tsl::Fingerprint64(platform_name_)) {
InitDevicesAndMemorySpaces();
InitAttributes();
LOG(INFO) << "PjRtCApiClient created.";
}
void PjRtCApiClient::InitDevicesAndMemorySpaces() {
// Initialize devices.
PJRT_Client_Devices_Args devices_args;
devices_args.struct_size = PJRT_Client_Devices_Args_STRUCT_SIZE;
devices_args.extension_start = nullptr;
devices_args.client = c_client_.get();
pjrt::LogFatalIfPjrtError(c_api_->PJRT_Client_Devices(&devices_args), c_api_);
const size_t num_devices = devices_args.num_devices;
c_to_cpp_device_map_.reserve(num_devices);
owned_devices_.reserve(num_devices);
devices_.reserve(num_devices);
for (int i = 0; i < num_devices; ++i) {
PJRT_Device* device = devices_args.devices[i];
std::unique_ptr<PjRtCApiDevice>& cpp_device = owned_devices_.emplace_back(
std::make_unique<PjRtCApiDevice>(device, this));
devices_.push_back(cpp_device.get());
c_to_cpp_device_map_[device] = cpp_device.get();
}
// Initialize addressable devices.
PJRT_Client_AddressableDevices_Args address_args;
address_args.struct_size = PJRT_Client_AddressableDevices_Args_STRUCT_SIZE;
address_args.extension_start = nullptr;
address_args.client = c_client_.get();
pjrt::LogFatalIfPjrtError(
c_api_->PJRT_Client_AddressableDevices(&address_args), c_api_);
const size_t num_addressable_devices = address_args.num_addressable_devices;
addressable_devices_.reserve(num_addressable_devices);
for (int i = 0; i < num_addressable_devices; ++i) {
PJRT_Device* c_device = address_args.addressable_devices[i];
addressable_devices_.push_back(GetCppDevice(c_device));
}
// Initialize addressable memory spaces.
// TODO(yueshengys): Initialize global memory spaces when supported.
PJRT_Client_AddressableMemories_Args memory_args;
memory_args.struct_size = PJRT_Client_AddressableMemories_Args_STRUCT_SIZE;
memory_args.extension_start = nullptr;
memory_args.client = c_client_.get();
std::unique_ptr<PJRT_Error, pjrt::PJRT_ErrorDeleter> client_error(
c_api_->PJRT_Client_AddressableMemories(&memory_args),
pjrt::MakeErrorDeleter(c_api_));
if (client_error == nullptr) {
const size_t num_memories = memory_args.num_addressable_memories;
c_to_cpp_memory_map_.reserve(num_memories);
owned_memory_spaces_.reserve(num_memories);
addressable_memory_spaces_.reserve(num_memories);
for (int i = 0; i < num_memories; ++i) {
PJRT_Memory* memory = memory_args.addressable_memories[i];
std::unique_ptr<PjRtCApiMemorySpace>& cpp_memory =
owned_memory_spaces_.emplace_back(
std::make_unique<PjRtCApiMemorySpace>(memory, this));
addressable_memory_spaces_.push_back(cpp_memory.get());
c_to_cpp_memory_map_[memory] = cpp_memory.get();
}
} else if (pjrt::GetErrorCode(client_error.get(), c_api_) !=
PJRT_Error_Code_UNIMPLEMENTED) {
pjrt::LogFatalIfPjrtError(client_error.get(), c_api_);
}
// Attach memory spaces to devices.
// TODO(yueshengys): switch to global devices when supported.
for (const auto& device : addressable_devices_) {
PjRtCApiDevice* cpp_device = tensorflow::down_cast<PjRtCApiDevice*>(device);
PJRT_Device* c_device = cpp_device->c_device();
PJRT_Device_AddressableMemories_Args args;
args.struct_size = PJRT_Device_AddressableMemories_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device = c_device;
std::unique_ptr<PJRT_Error, pjrt::PJRT_ErrorDeleter> device_error(
c_api_->PJRT_Device_AddressableMemories(&args),
pjrt::MakeErrorDeleter(c_api_));
if (device_error != nullptr) {
if (pjrt::GetErrorCode(device_error.get(), c_api_) !=
PJRT_Error_Code_UNIMPLEMENTED) {
pjrt::LogFatalIfPjrtError(device_error.get(), c_api_);
}
break;
}
const size_t num_memories = args.num_memories;
cpp_device->memory_spaces_.reserve(num_memories);
for (int i = 0; i < num_memories; ++i) {
cpp_device->memory_spaces_.push_back(GetCppMemory(args.memories[i]));
}
}
// Attach devices to memory spaces.
// TODO(yueshengys): switch to global memories when supported.
for (const auto& memory : addressable_memory_spaces_) {
PjRtCApiMemorySpace* cpp_memory =
tensorflow::down_cast<PjRtCApiMemorySpace*>(memory);
PJRT_Memory* c_memory = cpp_memory->c_memory();
PJRT_Memory_AddressableByDevices_Args args;
args.struct_size = PJRT_Memory_AddressableByDevices_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_Memory_AddressableByDevices(&args),
c_api_);
const size_t num_attached_devices = args.num_devices;
cpp_memory->devices_.reserve(num_attached_devices);
for (int i = 0; i < num_attached_devices; ++i) {
cpp_memory->devices_.push_back(GetCppDevice(args.devices[i]));
}
}
}
void PjRtCApiClient::InitAttributes() {
PJRT_Plugin_Attributes_Args args;
args.struct_size = PJRT_Plugin_Attributes_Args_STRUCT_SIZE;
args.extension_start = nullptr;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_Plugin_Attributes(&args), c_api_);
attributes_ =
pjrt::ConvertFromPjRtNamedValueList(args.attributes, args.num_attributes);
}
int PjRtCApiClient::device_count() const { return devices_.size(); }
int PjRtCApiClient::addressable_device_count() const {
return addressable_devices_.size();
}
absl::Span<PjRtDevice* const> PjRtCApiClient::devices() const {
return devices_;
}
absl::Span<PjRtDevice* const> PjRtCApiClient::addressable_devices() const {
return addressable_devices_;
}
int PjRtCApiClient::process_index() const {
PJRT_Client_ProcessIndex_Args process_index_args;
process_index_args.struct_size = PJRT_Client_ProcessIndex_Args_STRUCT_SIZE;
process_index_args.extension_start = nullptr;
process_index_args.client = c_client_.get();
pjrt::LogFatalIfPjrtError(
c_api_->PJRT_Client_ProcessIndex(&process_index_args), c_api_);
return process_index_args.process_index;
}
absl::string_view PjRtCApiClient::platform_version() const {
return platform_version_;
}
std::optional<PjRtPluginAttributes> PjRtCApiClient::plugin_attributes() const {
return PjRtPluginAttributes{c_api_->pjrt_api_version.major_version,
c_api_->pjrt_api_version.minor_version,
attributes_};
}
static DeviceAssignment CalculateDefaultAssignment(
int num_replicas, int num_partitions,
absl::Span<const int> device_assignment) {
DeviceAssignment cpp_device_assignment(num_replicas, num_partitions);
const int* iterator = device_assignment.begin();
for (int replica = 0; replica < num_replicas; ++replica) {
for (int partition = 0; partition < num_partitions; ++partition) {
cpp_device_assignment(replica, partition) = *(iterator++);
}
}
return cpp_device_assignment;
}
StatusOr<DeviceAssignment> PjRtCApiClient::GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const {
PJRT_Client_DefaultDeviceAssignment_Args args;
args.struct_size = PJRT_Client_DefaultDeviceAssignment_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.client = c_client_.get();
args.num_replicas = num_replicas;
args.num_partitions = num_partitions;
std::vector<int> assignment_buffer(num_replicas * num_partitions);
args.default_assignment_size = assignment_buffer.size();
args.default_assignment = assignment_buffer.data();
RETURN_STATUS_IF_PJRT_ERROR(
c_api_->PJRT_Client_DefaultDeviceAssignment(&args), c_api_);
absl::Span<const int> param{args.default_assignment,
args.default_assignment_size};
return CalculateDefaultAssignment(args.num_replicas, args.num_partitions,
param);
}
StatusOr<PjRtDevice*> PjRtCApiClient::LookupDevice(int device_id) const {
return LookupDevice(PjRtGlobalDeviceId(device_id));
}
StatusOr<PjRtDevice*> PjRtCApiClient::LookupDevice(
PjRtGlobalDeviceId global_device_id) const {
PJRT_Client_LookupDevice_Args args;
args.struct_size = PJRT_Client_LookupDevice_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.client = c_client_.get();
args.id = global_device_id.value();
RETURN_STATUS_IF_PJRT_ERROR(c_api_->PJRT_Client_LookupDevice(&args), c_api_);
return GetCppDevice(args.device);
}
StatusOr<PjRtDevice*> PjRtCApiClient::LookupAddressableDevice(
int local_hardware_id) const {
return LookupAddressableDevice(PjRtLocalDeviceId(local_hardware_id));
}
StatusOr<PjRtDevice*> PjRtCApiClient::LookupAddressableDevice(
PjRtLocalDeviceId local_device_id) const {
PJRT_Client_LookupAddressableDevice_Args args;
args.struct_size = PJRT_Client_LookupAddressableDevice_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.client = c_client_.get();
args.local_hardware_id = local_device_id.value();
RETURN_STATUS_IF_PJRT_ERROR(
c_api_->PJRT_Client_LookupAddressableDevice(&args), c_api_);
return GetCppDevice(args.addressable_device);
}
absl::Span<PjRtMemorySpace* const> PjRtCApiClient::memory_spaces() const {
return addressable_memory_spaces_;
}
// Initializes `PJRT_Client_Compile_Args`, which will be used to call
// API PJRT_Client_Compile().
static StatusOr<std::unique_ptr<PjRtLoadedExecutable>> InitializeArgsAndCompile(
PjRtCApiClient* api_client, const PJRT_Api* c_api, PJRT_Client* client,
const CompileOptions& options, const std::string& code,
const std::string& format) {
PJRT_Client_Compile_Args args;
args.struct_size = PJRT_Client_Compile_Args_STRUCT_SIZE;
PJRT_Profiler_Extension profiler_extension =
pjrt::CreatePjrtProfilerExtension("PJRT_Client_Compile linkage");
args.extension_start =
reinterpret_cast<PJRT_Extension_Base*>(&profiler_extension);
args.client = client;
TF_ASSIGN_OR_RETURN(const CompileOptionsProto options_proto,
options.ToProto());
std::string options_str = options_proto.SerializeAsString();
args.compile_options = options_str.c_str();
args.compile_options_size = options_str.size();
PJRT_Program program;
program.struct_size = PJRT_Program_STRUCT_SIZE;
program.extension_start = nullptr;
program.code = const_cast<char*>(code.c_str());
program.code_size = code.size();
program.format = format.c_str();
program.format_size = format.size();
args.program = &program;
RETURN_STATUS_IF_PJRT_ERROR(c_api->PJRT_Client_Compile(&args), c_api);
std::unique_ptr<PjRtLoadedExecutable> ret =
std::make_unique<PjRtCApiLoadedExecutable>(api_client, args.executable);
return ret;
}
StatusOr<std::unique_ptr<PjRtLoadedExecutable>> PjRtCApiClient::Compile(
const XlaComputation& computation, CompileOptions options) {
std::string module_str = computation.proto().SerializeAsString();
std::string format(pjrt::kHloFormat);
return InitializeArgsAndCompile(this, c_api_, c_client_.get(), options,
module_str, format);
}
StatusOr<std::unique_ptr<PjRtLoadedExecutable>> PjRtCApiClient::Compile(
mlir::ModuleOp module, CompileOptions options) {
// TODO: Once plugins are ready, use SerializeUsingVersionedStablehlo.
if (!pjrt_c_api()) llvm::report_fatal_error("pjrt_c_api is null");
TF_ASSIGN_OR_RETURN(
std::string serialized,
xla::SerializeUsingNativeBytecode(
module, plugin_attributes()->pjrt_c_api_minor_version));
std::string format(pjrt::kMlirFormat);
return InitializeArgsAndCompile(this, c_api_, c_client_.get(), options,
serialized, format);
}
StatusOr<std::unique_ptr<PjRtLoadedExecutable>>
PjRtCApiClient::DeserializeExecutable(absl::string_view serialized,
std::optional<CompileOptions> options) {
PJRT_Executable_DeserializeAndLoad_Args des_args;
des_args.struct_size = PJRT_Executable_DeserializeAndLoad_Args_STRUCT_SIZE;
des_args.extension_start = nullptr;
des_args.client = c_client_.get();
des_args.serialized_executable = serialized.data();
des_args.serialized_executable_size = serialized.length();
const PJRT_Api* api = pjrt_c_api();
RETURN_STATUS_IF_PJRT_ERROR(
api->PJRT_Executable_DeserializeAndLoad(&des_args), api);
PJRT_LoadedExecutable* c_exec = des_args.loaded_executable;
CHECK(c_exec != nullptr);
return std::unique_ptr<PjRtLoadedExecutable>(
std::make_unique<PjRtCApiLoadedExecutable>(this, c_exec));
}
StatusOr<const PjRtTopologyDescription*>
PjRtCApiClient::GetTopologyDescription() const {
if (!topo_desc_.ok()) {
return topo_desc_.status();
}
return &(*topo_desc_);
}
StatusOr<std::uintptr_t> PjRtCApiClient::UnsafeBufferPointer(
PjRtBuffer* buffer) {
// Validate that the buffer's client matches the function call's client, since
// that could be a common error.
// Not doing input nullptr validation since such cases should be rare, and
// crashes should bubble up the call stack to higher layers. See b/248334153
// for the considerations that went into this.
if (buffer->client() != this) {
return InvalidArgument(
"buffer passed to PjRtCApiClient::UnsafeBufferPointer() is from a "
"different client than that of the function call. Buffer's client "
"platform: '%s', function call's client platform: '%s'.",
buffer->client()->platform_name(), this->platform_name());
}
PJRT_Buffer_UnsafePointer_Args args;
args.struct_size = PJRT_Buffer_UnsafePointer_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.buffer =
tensorflow::down_cast<const PjRtCApiBuffer*>(buffer)->c_buffer();
RETURN_STATUS_IF_PJRT_ERROR(c_api_->PJRT_Buffer_UnsafePointer(&args), c_api_);
return args.buffer_pointer;
}
StatusOr<std::unique_ptr<PjRtBuffer>>
PjRtCApiClient::BufferFromHostBufferInternalImpl(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
std::variant<PjRtDevice*, PjRtMemorySpace*> device_or_memory,
const Layout* device_layout) {
if (host_buffer_semantics != HostBufferSemantics::kImmutableOnlyDuringCall &&
host_buffer_semantics != HostBufferSemantics::kImmutableZeroCopy &&
host_buffer_semantics !=
HostBufferSemantics::kImmutableUntilTransferCompletes) {
return Unimplemented(
"PJRT C API does not support HostBufferSemantics other than "
"HostBufferSemantics::kImmutableOnlyDuringCall, "
"HostBufferSemantics::kImmutableZeroCopy and "
"HostBufferSemantics::kImmutableUntilTransferCompletes.");
}
PJRT_Client_BufferFromHostBuffer_Args args;
args.struct_size = PJRT_Client_BufferFromHostBuffer_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.client = c_client_.get();
args.data = data;
args.type = ::pjrt::ConvertToPjRtBufferType(type);
args.dims = dims.data();
args.num_dims = dims.size();
if (byte_strides.has_value()) {
args.byte_strides = byte_strides.value().data();
args.num_byte_strides = byte_strides.value().size();
} else {
args.byte_strides = nullptr;
args.num_byte_strides = 0;
}
pjrt::BufferMemoryLayoutData c_layout_data;
if (device_layout != nullptr) {
TF_ASSIGN_OR_RETURN(c_layout_data,
pjrt::ConvertToBufferMemoryLayoutData(*device_layout));
args.device_layout = &c_layout_data.c_layout;
} else {
args.device_layout = nullptr;
}
args.host_buffer_semantics =
::pjrt::ConvertToPjRtHostBufferSemantics(host_buffer_semantics);
if (std::holds_alternative<PjRtDevice*>(device_or_memory)) {
args.device = tensorflow::down_cast<PjRtCApiDevice*>(
std::get<PjRtDevice*>(device_or_memory))
->c_device();
args.memory = nullptr;
} else {
CHECK(std::holds_alternative<PjRtMemorySpace*>(device_or_memory));
args.device = nullptr;
args.memory = tensorflow::down_cast<PjRtCApiMemorySpace*>(
std::get<PjRtMemorySpace*>(device_or_memory))
->c_memory();
}
RETURN_STATUS_IF_PJRT_ERROR(c_api_->PJRT_Client_BufferFromHostBuffer(&args),
c_api_);
auto buffer = std::unique_ptr<PjRtBuffer>(
std::make_unique<PjRtCApiBuffer>(this, args.buffer));
std::unique_ptr<PJRT_Event, ::pjrt::PJRT_EventDeleter> event(
args.done_with_host_buffer, ::pjrt::MakeEventDeleter(c_api_));
if (on_done_with_host_buffer) {
PJRT_Event_OnReady_Args event_args;
event_args.struct_size = PJRT_Event_OnReady_Args_STRUCT_SIZE;
event_args.extension_start = nullptr;
event_args.event = event.get();
event_args.user_arg = new absl::AnyInvocable<void(PJRT_Error*)>(
[on_done_with_host_buffer = std::move(on_done_with_host_buffer),
c_api = c_api_](PJRT_Error* error) mutable {
if (error) {
::pjrt::MakeErrorDeleter(c_api)(error);
}
std::move(on_done_with_host_buffer)();
});
event_args.callback = [](PJRT_Error* error, void* args) {
auto* on_done_with_host_buffer =
reinterpret_cast<absl::AnyInvocable<void(PJRT_Error*)>*>(args);
(*on_done_with_host_buffer)(error);
delete on_done_with_host_buffer;
};
RETURN_STATUS_IF_PJRT_ERROR(c_api_->PJRT_Event_OnReady(&event_args),
c_api_);
}
return buffer;
}
StatusOr<std::unique_ptr<PjRtBuffer>> PjRtCApiClient::BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtMemorySpace* memory_space, const Layout* device_layout) {
return BufferFromHostBufferInternalImpl(
data, type, dims, byte_strides, host_buffer_semantics,
std::move(on_done_with_host_buffer), memory_space, device_layout);
}
StatusOr<std::unique_ptr<PjRtBuffer>> PjRtCApiClient::BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer, PjRtDevice* device,
const Layout* device_layout) {
return BufferFromHostBufferInternalImpl(
data, type, dims, byte_strides, host_buffer_semantics,
std::move(on_done_with_host_buffer), device, device_layout);
}
StatusOr<std::unique_ptr<PjRtBuffer>> PjRtCApiClient::BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,
std::optional<absl::Span<int64_t const>> byte_strides,
HostBufferSemantics host_buffer_semantics,
absl::AnyInvocable<void() &&> on_done_with_host_buffer,
PjRtDevice* device) {
return BufferFromHostBufferInternalImpl(
data, type, dims, byte_strides, host_buffer_semantics,
std::move(on_done_with_host_buffer), device, /*device_layout=*/nullptr);
}
StatusOr<std::unique_ptr<PjRtBuffer>> PjRtCApiClient::CreateViewOfDeviceBuffer(
void* device_ptr, const Shape& shape, PjRtDevice* device,
std::function<void()> on_delete_callback,
std::optional<std::intptr_t> stream) {
PJRT_Client_CreateViewOfDeviceBuffer_Args args;
args.struct_size = PJRT_Client_CreateViewOfDeviceBuffer_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.client = c_client_.get();
args.device_buffer_ptr = device_ptr;
args.dims = shape.dimensions().data();
args.num_dims = shape.dimensions().size();
args.element_type = pjrt::ConvertToPjRtBufferType(shape.element_type());
pjrt::BufferMemoryLayoutData c_layout_data;
if (shape.has_layout()) {
TF_ASSIGN_OR_RETURN(c_layout_data,
pjrt::ConvertToBufferMemoryLayoutData(shape.layout()));
args.layout = &(c_layout_data.c_layout);
} else {
args.layout = nullptr;
}
if (on_delete_callback != nullptr) {
args.on_delete_callback_arg =
new std::function(std::move(on_delete_callback));
args.on_delete_callback = [](void* device_buffer_ptr, void* user_arg) {
auto* c_func = reinterpret_cast<std::function<void()>*>(user_arg);
(*c_func)();
delete c_func;
};
} else {
args.on_delete_callback = nullptr;
args.on_delete_callback_arg = nullptr;
}
args.device = tensorflow::down_cast<PjRtCApiDevice*>(device)->c_device();
if (stream.has_value()) {
args.stream = *stream;
} else {
args.stream = reinterpret_cast<intptr_t>(nullptr);
}
const PJRT_Api* c_api = pjrt_c_api();
RETURN_STATUS_IF_PJRT_ERROR(
c_api->PJRT_Client_CreateViewOfDeviceBuffer(&args), c_api);
return std::unique_ptr<PjRtBuffer>(
std::make_unique<PjRtCApiBuffer>(this, args.buffer));
}
const PJRT_Api* PjRtCApiClient::pjrt_c_api() const { return c_api_; }
// --------------------------------- Devices -----------------------------------
PjRtCApiDeviceDescription::PjRtCApiDeviceDescription(
const PJRT_Api* c_api, PJRT_DeviceDescription* device_description)
: c_api_(c_api), device_description_(device_description) {
InitAttributes();
}
int PjRtCApiDeviceDescription::id() const {
PJRT_DeviceDescription_Id_Args args;
args.struct_size = PJRT_DeviceDescription_Id_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_Id(&args), c_api_);
return args.id;
}
int PjRtCApiDeviceDescription::process_index() const {
PJRT_DeviceDescription_ProcessIndex_Args args;
args.struct_size = PJRT_DeviceDescription_ProcessIndex_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_ProcessIndex(&args),
c_api_);
return args.process_index;
}
void PjRtCApiDeviceDescription::InitAttributes() {
attributes_ = {};
PJRT_DeviceDescription_Attributes_Args args;
args.struct_size = PJRT_DeviceDescription_Attributes_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_Attributes(&args),
c_api_);
for (int i = 0; i < args.num_attributes; ++i) {
const auto& attribute = args.attributes[i];
std::string attribute_name(attribute.name, attribute.name_size);
switch (attribute.type) {
case PJRT_NamedValue_Type::PJRT_NamedValue_kString: {
std::string string_value(attribute.string_value, attribute.value_size);
attributes_[attribute_name] = PjRtDeviceAttribute(string_value);
break;
}
case PJRT_NamedValue_Type::PJRT_NamedValue_kInt64: {
attributes_[attribute_name] =
PjRtDeviceAttribute(attribute.int64_value);
break;
}
case PJRT_NamedValue_Type::PJRT_NamedValue_kInt64List: {
const int64_t* array_ptr(attribute.int64_array_value);
std::vector<int64_t> int64_array(array_ptr,
array_ptr + attribute.value_size);
attributes_[attribute_name] = PjRtDeviceAttribute(int64_array);
break;
}
// Do not allow other types (such as
// PJRT_NamedValue::PJRT_NamedValue_kFloat) since device attributes
// currently should not return other types. Also C API client currently
// does not support forward compatibility (such as if the underlying
// PJRT library is a newer version that returns types not supported by
// this client). Failing here to prevent undefined behavior.
default: {
LOG(FATAL) << "PJRT_DeviceDescription_Attributes() returned attribute '"
<< attribute_name << "' with unsupported type "
<< attribute.type
<< " to PjRtCApiDeviceDescription::InitAttributes()";
break;
}
}
}
}
const absl::flat_hash_map<std::string, PjRtDeviceAttribute>&
PjRtCApiDeviceDescription::Attributes() const {
return attributes_;
}
absl::string_view PjRtCApiDeviceDescription::device_kind() const {
PJRT_DeviceDescription_Kind_Args args;
args.struct_size = PJRT_DeviceDescription_Kind_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_Kind(&args), c_api_);
absl::string_view device_kind(args.device_kind, args.device_kind_size);
return device_kind;
}
absl::string_view PjRtCApiDeviceDescription::DebugString() const {
PJRT_DeviceDescription_DebugString_Args args;
args.struct_size = PJRT_DeviceDescription_DebugString_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_DebugString(&args),
c_api_);
absl::string_view debug_string(args.debug_string, args.debug_string_size);
return debug_string;
}
absl::string_view PjRtCApiDeviceDescription::ToString() const {
PJRT_DeviceDescription_ToString_Args args;
args.struct_size = PJRT_DeviceDescription_ToString_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device_description = device_description_;
pjrt::LogFatalIfPjrtError(c_api_->PJRT_DeviceDescription_ToString(&args),
c_api_);
absl::string_view to_string(args.to_string, args.to_string_size);
return to_string;
}
PjRtCApiDevice::PjRtCApiDevice(PJRT_Device* device, PjRtCApiClient* client)
: client_(client),
device_(device),
description_(client->pjrt_c_api(),
pjrt::GetDeviceDescription(client->pjrt_c_api(), device)) {}
PjRtClient* PjRtCApiDevice::client() const { return client_; }
bool PjRtCApiDevice::IsAddressable() const {
PJRT_Device_IsAddressable_Args args;
args.struct_size = PJRT_Device_IsAddressable_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device = device_;
const PJRT_Api* api = client_->pjrt_c_api();
pjrt::LogFatalIfPjrtError(api->PJRT_Device_IsAddressable(&args), api);
return args.is_addressable;
}
int PjRtCApiDevice::local_hardware_id() const {
return local_hardware_id_typed().value();
}
PjRtLocalHardwareId PjRtCApiDevice::local_hardware_id_typed() const {
PJRT_Device_LocalHardwareId_Args args;
args.struct_size = PJRT_Device_LocalHardwareId_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device = device_;
const PJRT_Api* api = client_->pjrt_c_api();
pjrt::LogFatalIfPjrtError(api->PJRT_Device_LocalHardwareId(&args), api);
return PjRtLocalHardwareId(args.local_hardware_id);
}
StatusOr<PjRtMemorySpace*> PjRtCApiDevice::default_memory_space() const {
PJRT_Device_DefaultMemory_Args args;
args.struct_size = PJRT_Device_DefaultMemory_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device = device_;
const PJRT_Api* api = client_->pjrt_c_api();
RETURN_STATUS_IF_PJRT_ERROR(api->PJRT_Device_DefaultMemory(&args), api);
return client_->GetCppMemory(args.memory);
}
StatusOr<tsl::AllocatorStats> PjRtCApiDevice::GetAllocatorStats() const {
PJRT_Device_MemoryStats_Args args;
args.struct_size = PJRT_Device_MemoryStats_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.device = device_;
const PJRT_Api* api = client_->pjrt_c_api();
RETURN_STATUS_IF_PJRT_ERROR(api->PJRT_Device_MemoryStats(&args), api);
tsl::AllocatorStats result;
result.bytes_in_use = args.bytes_in_use;
// The PJRT C API supports optionally returning most fields, but only some
// fields in tsl::AllocatorStats are optional. Return -1 for unset,
// non-optional fields. We could change tsl::AllocatorStats to have all
// optional fields, but that requires changing a lot of callers.
if (args.peak_bytes_in_use_is_set) {
result.peak_bytes_in_use = args.peak_bytes_in_use;
} else {
result.peak_bytes_in_use = -1;
}
if (args.num_allocs_is_set) {
result.num_allocs = args.num_allocs;
} else {
result.num_allocs = -1;
}
if (args.largest_alloc_size_is_set) {
result.largest_alloc_size = args.largest_alloc_size;
} else {
result.largest_alloc_size = -1;
}
if (args.bytes_limit_is_set) {
result.bytes_limit = args.bytes_limit;
}
if (args.bytes_reserved_is_set) {
result.bytes_reserved = args.bytes_reserved;
} else {
result.bytes_reserved = -1;
}
if (args.peak_bytes_reserved_is_set) {
result.peak_bytes_reserved = args.peak_bytes_reserved;
} else {
result.peak_bytes_reserved = -1;
}
if (args.bytes_reservable_limit_is_set) {
result.bytes_reservable_limit = args.bytes_reservable_limit;
}
if (args.largest_free_block_bytes_is_set) {
result.largest_free_block_bytes = args.largest_free_block_bytes;
} else {
result.largest_free_block_bytes = -1;
}
if (args.pool_bytes_is_set) {
result.pool_bytes = args.pool_bytes;
}
if (args.peak_pool_bytes_is_set) {
result.peak_pool_bytes = args.peak_pool_bytes;
}
return result;
}
// ------------------------------- Memory --------------------------------------
const PJRT_Api* PjRtCApiMemorySpace::pjrt_c_api() const {
return client_->pjrt_c_api();
}
PjRtClient* PjRtCApiMemorySpace::client() const { return client_; }
int PjRtCApiMemorySpace::id() const {
PJRT_Memory_Id_Args args;
args.struct_size = PJRT_Memory_Id_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory_;
pjrt::LogFatalIfPjrtError(pjrt_c_api()->PJRT_Memory_Id(&args), pjrt_c_api());
return args.id;
}
absl::string_view PjRtCApiMemorySpace::kind() const {
PJRT_Memory_Kind_Args args;
args.struct_size = PJRT_Memory_Kind_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory_;
pjrt::LogFatalIfPjrtError(pjrt_c_api()->PJRT_Memory_Kind(&args),
pjrt_c_api());
return absl::string_view(args.kind, args.kind_size);
}
int PjRtCApiMemorySpace::kind_id() const {
PJRT_Memory_Kind_Id_Args args;
args.struct_size = PJRT_Memory_Kind_Id_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory_;
if (pjrt_c_api()->pjrt_api_version.major_version > 0 ||
pjrt_c_api()->pjrt_api_version.minor_version >= 48) {
// The `kind_id` API is added in version 0.48.
pjrt::LogFatalIfPjrtError(pjrt_c_api()->PJRT_Memory_Kind_Id(&args),
pjrt_c_api());
return args.kind_id;
}
return tsl::Fingerprint32(kind());
}
absl::string_view PjRtCApiMemorySpace::DebugString() const {
PJRT_Memory_DebugString_Args args;
args.struct_size = PJRT_Memory_DebugString_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory_;
pjrt::LogFatalIfPjrtError(pjrt_c_api()->PJRT_Memory_DebugString(&args),
pjrt_c_api());
return absl::string_view(args.debug_string, args.debug_string_size);
}
absl::string_view PjRtCApiMemorySpace::ToString() const {
PJRT_Memory_ToString_Args args;
args.struct_size = PJRT_Memory_ToString_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.memory = c_memory_;
pjrt::LogFatalIfPjrtError(pjrt_c_api()->PJRT_Memory_ToString(&args),
pjrt_c_api());
return absl::string_view(args.to_string, args.to_string_size);
}
// ------------------------------- Executables ---------------------------------
PjRtCApiExecutable::PjRtCApiExecutable(const PJRT_Api* c_api,
PJRT_Executable* executable)
: c_api_(c_api),
executable_(executable, ::pjrt::MakeExecutableDeleter(c_api)) {}
absl::string_view PjRtCApiExecutable::name() const {
auto* c_api = pjrt_c_api();
auto* executable = c_executable();
PJRT_Executable_Name_Args args;
args.executable = executable;
args.struct_size = PJRT_Executable_Name_Args_STRUCT_SIZE;
args.extension_start = nullptr;
pjrt::LogFatalIfPjrtError(c_api->PJRT_Executable_Name(&args), c_api);
return absl::string_view(args.executable_name, args.executable_name_size);
}
int PjRtCApiExecutable::num_replicas() const {
auto* c_api = pjrt_c_api();
auto* executable = c_executable();
PJRT_Executable_NumReplicas_Args args;
args.executable = executable;
args.struct_size = PJRT_Executable_NumReplicas_Args_STRUCT_SIZE;
args.extension_start = nullptr;
pjrt::LogFatalIfPjrtError(c_api->PJRT_Executable_NumReplicas(&args), c_api);
return args.num_replicas;
}
int PjRtCApiExecutable::num_partitions() const {
auto* c_api = pjrt_c_api();
auto* executable = c_executable();
PJRT_Executable_NumPartitions_Args args;
args.executable = executable;
args.struct_size = PJRT_Executable_NumPartitions_Args_STRUCT_SIZE;
args.extension_start = nullptr;
pjrt::LogFatalIfPjrtError(c_api->PJRT_Executable_NumPartitions(&args), c_api);
return args.num_partitions;
}
int64_t PjRtCApiExecutable::SizeOfGeneratedCodeInBytes() const {
auto* c_api = pjrt_c_api();
auto* executable = c_executable();
PJRT_Executable_SizeOfGeneratedCodeInBytes_Args args;
args.struct_size =
PJRT_Executable_SizeOfGeneratedCodeInBytes_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.executable = executable;
pjrt::LogFatalIfPjrtError(
c_api->PJRT_Executable_SizeOfGeneratedCodeInBytes(&args), c_api);
return args.size_in_bytes;
}
StatusOr<absl::flat_hash_map<std::string, PjRtValueType>>
PjRtCApiExecutable::GetCostAnalysis() const {
// Initialize function call args
PJRT_Executable_GetCostAnalysis_Args args;
args.struct_size = PJRT_Executable_GetCostAnalysis_Args_STRUCT_SIZE;
args.extension_start = nullptr;
args.executable = c_executable();
// Make PJRT C API call
const PJRT_Api* c_api = pjrt_c_api();