-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathpjrt_stream_executor_client.cc
3339 lines (3033 loc) · 137 KB
/
pjrt_stream_executor_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 2017 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.
==============================================================================*/
// Implementation notes:
//
// Asynchronous execution:
// -----------------------
//
// Computations and host-to-device transfers do not need to block the host
// waiting for the operation to complete but instead return control to the host
// immediately. This allows client logic to overlap with device-side
// computation.
//
// For a good user experience, we must be careful only to enqueue operations
// that are unlikely to fail; as a rule error checking must be done eagerly
// before returning control to the client.
//
// The degree to which the client can enqueue operations ahead of the client
// is limited by a semaphore. There are at two modes: asynchronous, where we
// allow the client to enqueue up to 32 executions ahead of the device, and
// synchronous, where we limit the client to having one enqueued operation at
// a time. The value of 32 is arbitrary.
//
// Even in asynchronous mode, it is important that we do not permit
// unbounded queue-ahead. Firstly it is problematic when the user does something
// like the following in Python:
// %timeit run_computation()
// To the timeit logic, op() appears to be extremely cheap since it is deferring
// all of its real work and not blocking, and so the %timeit will run op() many
// (e.g., 10000) times to get better timing resolution, even though in reality
// it may be expensive. Secondly, on CPU the allocator is synchronized with the
// head of the compute stream, and we allocate buffers for all of the enqueued
// programs without any reuse (unlike GPU). This means that the memory usage
// is proportional to the queue size.
//
// Multi-stream execution:
// -----------------------
//
// We use a multistream execution design, where different Streams are used for
// host-to-device transfers, device-to-host transfers, and compute. This allows
// us to overlap transfers on and off the device with computation.
//
// Synchronization between streams occurs via BufferSequencingEvents that
// describe when the contents of a logical buffer are known to be valid on
// a particular stream, and when a buffer's uses have all completed.
//
// Synchronous vs asynchronous deallocation:
// -----------------------------------------
//
// See the comment on LocalDeviceState::AllocationModel for a discussion of the
// different allocation semantics on CPU, GPU, and TPU.
#include "xla/pjrt/pjrt_stream_executor_client.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/base/casts.h"
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/functional/any_invocable.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "xla/client/executable_build_options.h"
#include "xla/client/local_client.h"
#include "xla/client/xla_computation.h"
#include "xla/cpu_function_runtime.h"
#include "xla/executable_run_options.h"
#include "xla/layout.h"
#include "xla/literal.h"
#include "xla/pjrt/distributed/protocol.pb.h"
#include "xla/pjrt/event_pool.h"
#include "xla/pjrt/host_callback.h"
#include "xla/pjrt/local_device_state.h"
#include "xla/pjrt/metrics.h"
#include "xla/pjrt/mlir_to_hlo.h"
#include "xla/pjrt/pjrt_client.h"
#include "xla/pjrt/pjrt_common.h"
#include "xla/pjrt/pjrt_compiler.h"
#include "xla/pjrt/pjrt_executable.h"
#include "xla/pjrt/pjrt_future.h"
#include "xla/pjrt/semaphore.h"
#include "xla/pjrt/tracked_device_buffer.h"
#include "xla/pjrt/transpose.h"
#include "xla/pjrt/utils.h"
#include "xla/primitive_util.h"
#include "xla/service/compiler.h"
#include "xla/service/computation_layout.h"
#include "xla/service/executable.h"
#include "xla/service/generic_transfer_manager.h"
#include "xla/service/hlo_cost_analysis.h"
#include "xla/service/maybe_owning_device_memory.h"
#include "xla/service/shaped_buffer.h"
#include "xla/service/transfer_manager.h"
#include "xla/shape.h"
#include "xla/shape_tree.h"
#include "xla/shape_util.h"
#include "xla/status.h"
#include "xla/statusor.h"
#include "xla/stream_executor/device_memory.h"
#include "xla/stream_executor/device_memory_allocator.h"
#include "xla/stream_executor/host/host_platform_id.h"
#include "xla/stream_executor/stream.h"
#include "xla/util.h"
#include "xla/xla_data.pb.h"
#include "tsl/framework/allocator.h"
#include "tsl/platform/env.h"
#include "tsl/platform/errors.h"
#include "tsl/platform/fingerprint.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/mem.h"
#include "tsl/platform/status.h"
#include "tsl/platform/statusor.h"
#include "tsl/platform/threadpool.h"
#include "tsl/profiler/lib/connected_traceme.h"
#include "tsl/profiler/lib/context_types.h"
#include "tsl/profiler/lib/traceme.h"
namespace xla {
PjRtPlatformId PjRtStreamExecutorDevice::platform_id() const {
return client_->platform_id();
}
absl::string_view PjRtStreamExecutorDevice::platform_name() const {
return client_->platform_name();
}
StatusOr<LocalDeviceState*> PjRtStreamExecutorDevice::GetLocalDeviceState()
const {
if (local_device_state_) {
return local_device_state_.get();
}
return InvalidArgument("Device %s is not a local device.", DebugString());
}
StatusOr<DeviceAssignment> DevicesToDeviceAssignment(
absl::Span<const std::vector<PjRtDevice*>> devices) {
if (devices.empty()) {
return InvalidArgument(
"Device assignment passed to Compile() must be non-empty.");
}
if (devices[0].empty()) {
return InvalidArgument(
"Device assignment passed to Compile() must have a nonzero number of "
"partitions per replica; replica 0 had 0 partitions.");
}
DeviceAssignment xla_assignment(devices.size(), devices[0].size());
for (int replica = 0; replica < devices.size(); ++replica) {
if (devices[replica].size() != devices[0].size()) {
return InvalidArgument(
"Device assignment passed to Compile() has different numbers of "
"partitions between replicas; %d partitions for replica %d versus %d "
"partitions for replica 0.",
devices[replica].size(), replica, devices[0].size());
}
for (int partition = 0; partition < devices[replica].size(); ++partition) {
if (devices[0][0]->client()->platform_id() !=
devices[replica][partition]->client()->platform_id()) {
return InvalidArgument(
"Device assignment passed to Compile() must have devices of a "
"single kind, got %s for replica 0 partition 0 and %s for replica "
"%d partition %d.",
devices[0][0]->client()->platform_name(),
devices[replica][partition]->client()->platform_name(), replica,
partition);
}
xla_assignment(replica, partition) = devices[replica][partition]->id();
}
}
return xla_assignment;
}
class CpuAllocator : public tsl::Allocator {
public:
CpuAllocator() = default;
std::string Name() override { return "cpu"; }
void* AllocateRaw(size_t alignment, size_t num_bytes) override {
return tsl::port::AlignedMalloc(num_bytes, alignment);
}
void DeallocateRaw(void* ptr) override { return tsl::port::AlignedFree(ptr); }
};
PjRtStreamExecutorClient::PjRtStreamExecutorClient(
std::string platform_name, LocalClient* client,
std::vector<std::unique_ptr<PjRtStreamExecutorDevice>> devices,
int process_index, std::unique_ptr<se::DeviceMemoryAllocator> allocator,
std::unique_ptr<tsl::Allocator> host_memory_allocator,
bool should_stage_host_to_device_transfers,
std::unique_ptr<gpu::GpuExecutableRunOptions> gpu_run_options)
: platform_id_(tsl::Fingerprint64(platform_name)),
platform_name_(std::move(platform_name)),
client_(client),
host_memory_allocator_(std::move(host_memory_allocator)),
owned_allocator_(std::move(allocator)),
owned_devices_(std::move(devices)),
process_index_(process_index),
should_stage_host_to_device_transfers_(
should_stage_host_to_device_transfers),
gpu_run_options_(std::move(gpu_run_options)),
thread_pool_(
tsl::Env::Default(), "pjrt_thread_pool",
std::max<int>(DefaultThreadPoolSize(), client->device_count())),
transpose_cache_(1024) {
if (owned_allocator_ != nullptr) {
allocator_ = owned_allocator_.get();
} else {
allocator_ = client_->backend().memory_allocator();
}
if (!host_memory_allocator_) {
host_memory_allocator_ = std::make_unique<CpuAllocator>();
}
for (const std::unique_ptr<PjRtStreamExecutorDevice>& device :
owned_devices_) {
devices_.push_back(device.get());
CHECK(id_to_device_.insert({device->id(), device.get()}).second)
<< "Duplicate device id: " << device->id();
if (device->IsAddressable()) {
addressable_devices_.push_back(device.get());
}
device->SetClient(this);
}
// TODO(phawkins): we don't really promise anything about the order of
// these devices, but users may be depending on the current order. Sort into
// device ordinal order, which is the historical order these values have
// appeared.
absl::c_sort(addressable_devices_,
[](const PjRtDevice* a, const PjRtDevice* b) {
return a->local_device_id() < b->local_device_id();
});
}
StatusOr<DeviceAssignment> PjRtStreamExecutorClient::GetDefaultDeviceAssignment(
int num_replicas, int num_partitions) const {
return client_->backend().computation_placer()->AssignDevices(num_replicas,
num_partitions);
}
StatusOr<Layout> PjRtStreamExecutorClient::GetDefaultLayout(
PrimitiveType element_type, absl::Span<const int64_t> dims) {
Shape shape = ShapeUtil::MakeShape(element_type, dims);
TF_ASSIGN_OR_RETURN(
shape,
client()->backend().transfer_manager()->ChooseCompactLayoutForShape(
shape));
return shape.layout();
}
StatusOr<std::unique_ptr<HloCostAnalysis>>
PjRtStreamExecutorClient::GetHloCostAnalysis() const {
return std::make_unique<HloCostAnalysis>(
client_->backend().compiler()->ShapeSizeBytesFunction());
}
namespace {
// Ensures that it is safe to deallocate any buffers that have been enqueued in
// an operation on stream. Called only in rare error cases that are triggered
// during enqueue. These cases generally correspond to resource exhaustion.
void StallStreamOnError(LocalDeviceState* local_device, se::Stream* stream) {
switch (local_device->allocation_model()) {
case LocalDeviceState::kAsynchronous:
// We can safely deallocate any dangling buffers immediately. NOTE: this
// assumes that any buffers enqueued on stream are local to stream's
// executor, and manual action may be needed if that condition is not met.
break;
case LocalDeviceState::kComputeSynchronized:
// This will stall computation but that's ok in this very rare error
// case.
if (stream != local_device->compute_stream()) {
auto status = local_device->compute_stream()->WaitFor(stream);
if (!status.ok()) {
LOG(ERROR) << "Stalling compute stream failed: " << status;
}
}
break;
case LocalDeviceState::kSynchronous:
// This will stall the calling thread but that's ok in this very rare
// error case. If the stall fails just crash, since we have no other
// way to synchronize.
TF_CHECK_OK(stream->BlockHostUntilDone());
break;
}
}
// Does all necessary bookkeeping, after a buffer is successfully enqueued onto
// a stream, to ensure that the buffer will be kept alive until its use on that
// stream is complete.
//
// device_buffer: the buffer that was enqueued.
// buffer_local_device: the device the buffer was allocated on.
// stream_local_device: the device that manages usage_stream.
// event: an event that was recorded on usage_stream
// after the usage of device_buffer was enqueued.
// usage_stream: the stream the operation using device_buffer
// was enqueued on.
// prefer_to_retain_reference: relevant only for the compute synchronous
// allocation model. If true, retain a reference
// to device_buffer until after the operation
// completes. If false then the compute stream
// will have to be synchronized past event before
// device_buffer can be freed.
//
// prefer_to_retain_reference encodes a heuristic set by the caller for the
// compute synchronous model:
//
// Generally when a buffer is the destination of a copy to a device, it will
// subsequently be used on the device's compute stream before being freed. In
// that case, there is no need to retain a reference to the buffer. If the
// buffer is freed before being used on the compute stream, the free will be
// delayed until the host knows that event has completed, but this is expected
// to be uncommon.
//
// When a buffer is the source of a copy from a device, we need to either retain
// a reference to the buffer until the copy completes or serialize the compute
// stream behind the copy. It is often better to retain a reference since while
// that keeps memory alive longer, it avoids stalling the compute stream.
void RecordUsage(PjRtStreamExecutorBuffer::ScopedHold device_buffer,
LocalDeviceState* buffer_local_device,
LocalDeviceState* stream_local_device,
std::shared_ptr<BufferSequencingEvent> event,
se::Stream* usage_stream, bool prefer_to_retain_reference,
std::vector<std::shared_ptr<TrackedDeviceBuffer>>*
buffers_to_release = nullptr) {
tsl::profiler::TraceMe traceme("RecordUsage");
bool retain_buffer_until_completion =
// If the buffer wasn't allocated on the same device as the stream, always
// retain a reference.
(stream_local_device != buffer_local_device) ||
// In the synchronous allocation model, always retain a reference.
(stream_local_device->allocation_model() ==
LocalDeviceState::kSynchronous) ||
// In the compute synchronous model, use the caller's heuristic.
(stream_local_device->allocation_model() ==
LocalDeviceState::kComputeSynchronized &&
prefer_to_retain_reference);
if (retain_buffer_until_completion) {
if (buffers_to_release) {
buffers_to_release->push_back(device_buffer.buffer());
} else {
buffer_local_device->ThenRelease(usage_stream, device_buffer.buffer())
.IgnoreError();
}
}
device_buffer.ConvertUsageHold(usage_stream, event,
retain_buffer_until_completion);
}
// Allocates the device buffers for a buffer that will be used as the
// destination of a copy, either from the host or another device. copy_stream
// may be nullptr, e.g., when allocating a buffer for a cross-host copy. If the
// buffer is a tuple then the tuple tables are allocated, and all necessary
// synchronization for them is dealt with, before the buffer is returned.
//
// It is safe to delete the returned PjRtBuffer without further
// synchronization if an error occurs before the buffer is used.
//
// The caller may optionally provide a definition event to be recorded in
// the buffer.
// TODO(phawkins): replace on_host_shape here with on_device_shape.
StatusOr<std::unique_ptr<PjRtStreamExecutorBuffer>> AllocateDestinationBuffer(
const Shape& on_host_shape, PjRtDevice* device,
LocalDeviceState* local_device, se::Stream* copy_stream,
bool is_uninitialized_create, PjRtStreamExecutorClient* client,
std::shared_ptr<BufferSequencingEvent> definition_event = nullptr) {
if (on_host_shape.IsTuple() && on_host_shape.tuple_shapes_size() == 0) {
return InvalidArgument("Can't make a buffer from an empty tuple");
}
auto* se_client = tensorflow::down_cast<PjRtStreamExecutorClient*>(client);
TransferManager* transfer_manager =
se_client->client()->backend().transfer_manager();
TF_ASSIGN_OR_RETURN(ScopedShapedBuffer dst_buffer,
transfer_manager->AllocateScopedShapedBuffer(
on_host_shape, se_client->allocator(),
local_device->local_device_id().value()));
if (local_device->allocation_model() ==
LocalDeviceState::kComputeSynchronized) {
if (copy_stream == nullptr) {
CHECK(is_uninitialized_create);
} else {
CHECK(copy_stream->WaitFor(local_device->compute_stream()).ok());
}
} else {
DCHECK(transfer_manager->CanShapedBufferBeAccessedNow(
local_device->compute_stream()->parent(), dst_buffer));
}
Shape on_device_shape = dst_buffer.on_device_shape();
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 2>
definition_events;
if (is_uninitialized_create) {
// There is not going to be any copy into the buffer so in general we don't
// need a definition event.
// But if the caller provided a definition event then we record that. Also
// put it as the first definition event so that we can guarantee only the
// first one might not have event recorded.
if (definition_event) {
definition_events.emplace_back(definition_event);
}
if (local_device->allocation_model() ==
LocalDeviceState::kComputeSynchronized) {
// The allocation is not valid until the compute stream passes this point,
// so add a definition event in the compute stream.
definition_events.emplace_back(
std::make_shared<BufferSequencingEvent>(client->thread_pool()));
TF_ASSIGN_OR_RETURN(EventPool::Handle event,
local_device->event_pool().ThenAllocateAndRecordEvent(
local_device->compute_stream()));
definition_events.back()->SetSequencingEvent(
std::move(event), local_device->compute_stream());
}
} else {
// We have at least one definition event, for the copy completing to
// the device buffers.
if (definition_event) {
definition_events.emplace_back(definition_event);
} else {
definition_events.emplace_back(
std::make_shared<BufferSequencingEvent>(client->thread_pool()));
}
}
se::Stream* tuple_table_stream = local_device->host_to_device_stream();
if (on_device_shape.IsTuple()) {
// We also need to copy the tuple tables, so we'll have an additional
// definition event for that copy to complete.
if (tuple_table_stream != copy_stream) {
if (local_device->allocation_model() ==
LocalDeviceState::kComputeSynchronized) {
DCHECK(
tuple_table_stream->WaitFor(local_device->compute_stream()).ok());
} else {
DCHECK(transfer_manager->CanShapedBufferBeAccessedNow(
local_device->compute_stream()->parent(), dst_buffer));
}
}
TF_RETURN_IF_ERROR(transfer_manager->WriteTupleIndexTablesAsync(
tuple_table_stream, dst_buffer));
// CAUTION: From this point onwards we need to be careful about returning
// from error cases because we have started a transfer and must not allow
// dst_buffer to be freed too soon in the non-async allocation models.
definition_events.emplace_back(
std::make_shared<BufferSequencingEvent>(client->thread_pool()));
StatusOr<EventPool::Handle> event_or =
local_device->event_pool().ThenAllocateAndRecordEvent(
tuple_table_stream);
if (!event_or.ok()) {
StallStreamOnError(local_device, tuple_table_stream);
return event_or.status();
}
definition_events.back()->SetSequencingEvent(std::move(event_or).value(),
tuple_table_stream);
}
std::shared_ptr<TrackedDeviceBuffer> dst_device_buffer =
TrackedDeviceBuffer::FromScopedShapedBuffer(&dst_buffer,
definition_events);
auto py_buffer = std::make_unique<PjRtStreamExecutorBuffer>(
on_device_shape, std::move(dst_device_buffer), client, device);
if (on_device_shape.IsTuple()) {
// Add a usage hold for the tuple table write and immediately convert it to
// the appropriate form of synchronization. prefer_to_retain_reference=false
// means don't retain a memory reference until the transfer is complete when
// using the ComputeSynchronized allocation model. This is a heuristic
// because in the common case destination buffers will be used on the
// compute stream and therefore don't require any synchronization before
// being freed. If the buffer is allocated and never used, the free will
// take longer and this is assumed to be ok.
RecordUsage(py_buffer->GetBufferWithUsageHold(), local_device, local_device,
definition_events.back(), tuple_table_stream,
/*prefer_to_retain_reference=*/false);
}
return py_buffer;
}
// Adds necessary synchronization after a copy has been enqueued to a buffer.
// definition_event was added when the buffer was allocated, but has not yet
// had an event recorded.
Status AddDestinationBufferSynchronization(
LocalDeviceState* local_device,
PjRtStreamExecutorBuffer::ScopedHold device_buffer,
std::shared_ptr<BufferSequencingEvent> definition_event,
se::Stream* copy_stream) {
StatusOr<EventPool::Handle> event_or =
local_device->event_pool().ThenAllocateAndRecordEvent(copy_stream);
if (!event_or.ok()) {
StallStreamOnError(local_device, copy_stream);
return event_or.status();
}
definition_event->SetSequencingEvent(std::move(event_or).value(),
copy_stream);
// prefer_to_retain_reference=false means don't retain a memory reference
// until the transfer is complete when using the ComputeSynchronized
// allocation model. This is a heuristic because in the common case
// destination buffers will be used on the compute stream and therefore don't
// require any synchronization before being freed. If the buffer is allocated
// and never used, the free will take longer and this is assumed to be ok.
RecordUsage(std::move(device_buffer), local_device, local_device,
definition_event, copy_stream,
/*prefer_to_retain_reference=*/false);
return OkStatus();
}
} // namespace
PjRtStreamExecutorBuffer::ScopedHold::~ScopedHold() {
if (ok()) {
parent_->DropHold(type_, buffer().get());
}
}
PjRtStreamExecutorBuffer::ScopedHold::ScopedHold(ScopedHold&& other)
: parent_(other.parent_),
type_(other.type_),
state_(other.state_),
status_(std::move(other.status_)),
buffer_(std::move(other.buffer_)) {
// Preserve the invariant that status is invalid if buffer == nullptr.
other.SetState(kMoved);
}
void PjRtStreamExecutorBuffer::ScopedHold::Acquire(
StatusOr<std::shared_ptr<TrackedDeviceBuffer>>&& buffer_or) {
CHECK(!ok());
if (buffer_or.ok()) {
buffer_ = buffer_or.value();
SetState(kValid);
} else {
status_ = buffer_or.status();
buffer_ = nullptr;
SetState(kError);
}
// Check the invariant holds.
CHECK(!ok() || buffer_ != nullptr);
}
PjRtStreamExecutorBuffer::ScopedHold::ForClosure
PjRtStreamExecutorBuffer::ScopedHold::ToClosure() {
CHECK(ok());
ForClosure for_closure(parent_, type_, state_, std::move(status_),
std::move(buffer_));
SetState(kReleased);
return for_closure;
}
void PjRtStreamExecutorBuffer::ScopedHold::ConvertUsageHold(
se::Stream* usage_stream, std::shared_ptr<BufferSequencingEvent> event,
bool reference_held) {
CHECK(ok());
CHECK_EQ(type_, kUsage);
parent_->ConvertUsageHold(buffer().get(), usage_stream, std::move(event),
reference_held);
SetState(kConverted);
}
void PjRtStreamExecutorBuffer::ScopedHold::ConfirmDonation() {
CHECK(ok());
CHECK_EQ(type_, kDonation);
parent_->ConfirmDonation(buffer().get());
SetState(kDonated);
}
void PjRtStreamExecutorBuffer::ScopedHold::AddToInput(
ShapeTree<MaybeOwningDeviceMemory>::iterator* iterator,
const ShapeTree<MaybeOwningDeviceMemory>::iterator& end,
ExecutionInput* execution_input,
se::DeviceMemoryAllocator* allocator) const {
CHECK(ok());
if (type_ == kDonation) {
buffer()->AddToInputAsDonated(iterator, end, execution_input, allocator);
} else {
CHECK_EQ(type_, kUsage);
buffer()->AddToInputAsImmutable(iterator, end);
}
}
bool PjRtStreamExecutorBuffer::IsOnCpu() const { return false; }
StatusOr<Shape> PjRtStreamExecutorBuffer::logical_on_device_shape() {
if (on_device_shape_.is_static()) {
return on_device_shape_;
}
auto* local_device = device_->local_device_state();
auto* stream = local_device->GetDeviceToHostStream();
ScopedHold device_buffer(this, ScopedHold::kUsage);
{
absl::MutexLock lock(&mu_);
// We can't perform any other action while a donation hold is in progress.
WaitForOutstandingDonationHold();
if (device_buffer_ == nullptr) {
return InvalidArgument(
"logical_on_device_shape() called on deleted or donated buffer");
}
AcquireHoldLocked(&device_buffer);
}
WaitForBufferDefinitionEventsOnStream(*device_buffer, stream);
ShapedBuffer shaped_buffer = device_buffer->AsShapedBuffer(on_device_shape_);
StatusOr<EventPool::Handle> event_or =
local_device->event_pool().AllocateEvent(stream->parent());
if (!event_or.ok()) {
return event_or.status();
}
Shape ret_shape = on_device_shape_;
TransferManager* transfer_manager =
client_->client()->backend().transfer_manager();
TF_RETURN_IF_ERROR(
transfer_manager->ReadDynamicShapes(stream, &shaped_buffer, &ret_shape));
return ret_shape;
}
namespace {
// Implements PjRtBuffer::ExternalReference as a wrapped
// ScopedHold::kExternalReference.
class ScopedHoldAsExternalReference : public PjRtBuffer::ExternalReference {
public:
explicit ScopedHoldAsExternalReference(
PjRtStreamExecutorBuffer::ScopedHold hold)
: external_reference_(std::move(hold)) {
CHECK(external_reference_.type() ==
PjRtStreamExecutorBuffer::ScopedHold::kExternalReference);
data_ptr_ = external_reference_->device_memory().front().opaque();
}
~ScopedHoldAsExternalReference() override = default;
Status WaitUntilBufferReadyOnStream(std::intptr_t stream) override {
for (const std::shared_ptr<BufferSequencingEvent>& event :
external_reference_->definition_events()) {
TF_RETURN_IF_ERROR(event->WaitForEventOnExternalStream(stream));
}
return OkStatus();
}
private:
PjRtStreamExecutorBuffer::ScopedHold external_reference_;
};
} // namespace
StatusOr<std::unique_ptr<PjRtBuffer::ExternalReference>>
PjRtStreamExecutorBuffer::AcquireExternalReference() {
ScopedHold hold = GetBufferWithExternalReference();
Status hold_status = hold.status();
if (!hold_status.ok()) return hold_status;
return std::unique_ptr<ExternalReference>(
std::make_unique<ScopedHoldAsExternalReference>(std::move(hold)));
}
class TrackedDeviceBufferExternalReference
: public PjRtBuffer::ExternalReference {
public:
explicit TrackedDeviceBufferExternalReference(
std::shared_ptr<TrackedDeviceBuffer> tracked_device_buffer)
: tracked_device_buffer_(std::move(tracked_device_buffer)) {
data_ptr_ = tracked_device_buffer_->device_memory()[0].opaque();
}
~TrackedDeviceBufferExternalReference() override = default;
private:
std::shared_ptr<TrackedDeviceBuffer> tracked_device_buffer_;
};
StatusOr<std::unique_ptr<PjRtBuffer::ExternalReference>>
PjRtStreamExecutorBuffer::ReleaseDeviceMemoryOwnership(
bool wait_for_operations_to_complete) {
if (on_device_shape_.IsTuple()) {
return InvalidArgument(
"ReleaseDeviceMemoryOwnership allowed only for non-tuple");
}
TF_ASSIGN_OR_RETURN(
std::shared_ptr<TrackedDeviceBuffer> tracked_device_buffer,
Release(wait_for_operations_to_complete));
std::unique_ptr<PjRtBuffer::ExternalReference> ref;
if (tracked_device_buffer) {
ref = std::make_unique<TrackedDeviceBufferExternalReference>(
std::move(tracked_device_buffer));
}
return ref;
}
absl::StatusOr<std::unique_ptr<PjRtBuffer>>
PjRtStreamExecutorBuffer::DonateWithControlDependency(PjRtFuture<> dependency) {
VLOG(1) << "PjRtStreamExecutorBuffer::DonateWithControlDependency";
std::unique_ptr<PjRtBuffer> new_buffer;
auto tracked_buffer =
GetBufferWithHold(PjRtStreamExecutorBuffer::ScopedHold::kDonation);
if (!tracked_buffer.ok()) {
return InvalidArgument(
"Invalid buffer passed to DonateWithControlDependency: %s",
tracked_buffer.status().ToString());
}
// Copy all the data in the existing tracked_buffer.
absl::InlinedVector<se::DeviceMemoryBase, 4> buffers(
tracked_buffer->device_memory().begin(),
tracked_buffer->device_memory().end());
auto original_definition_events = tracked_buffer->definition_events();
absl::InlinedVector<std::shared_ptr<BufferSequencingEvent>, 4>
definition_events;
auto definition_event_for_status =
std::make_shared<BufferSequencingEvent>(client()->thread_pool());
// definition_event_for_status must be the first one so that it blocks other
// actions like D2H transfer from execution before the buffer is ready.
definition_events.push_back(definition_event_for_status);
definition_events.insert(definition_events.end(),
original_definition_events.begin(),
original_definition_events.end());
auto new_device_buffer = std::make_shared<TrackedDeviceBuffer>(
tracked_buffer->allocator(), device()->local_device_id().value(),
std::move(buffers), std::move(definition_events),
/*on_delete_callback=*/nullptr);
// Make the new buffer which is identical to the old, except for the new
// definition event.
new_buffer =
std::unique_ptr<PjRtBuffer>(std::make_unique<PjRtStreamExecutorBuffer>(
on_device_shape(), std::move(new_device_buffer), client(), device()));
PjRtStreamExecutorDevice* device = this->device();
LocalDeviceState* local_device = device->local_device_state();
dependency.OnReady(
[definition_event_for_status = std::move(definition_event_for_status),
local_device](absl::Status status) mutable {
// Forward the absl::Status from the supplied dependency to the
// definition event.
auto stream = local_device->BorrowStreamFromPool();
auto event =
local_device->event_pool().ThenAllocateAndRecordEvent(stream.get());
TF_CHECK_OK(event.status());
definition_event_for_status->SetSequencingEvent(
std::move(event).value(), stream.get());
local_device->ReturnStreamToPool(std::move(stream));
});
tracked_buffer.ConfirmDonation();
return new_buffer;
}
StatusOr<std::unique_ptr<PjRtBuffer>>
PjRtStreamExecutorClient::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) {
tsl::profiler::TraceMe traceme(
"PjRtStreamExecutorClient::BufferFromHostBuffer");
Shape device_shape = ShapeUtil::MakeShape(type, dims);
VLOG(1) << "PjRtStreamExecutorClient::BufferFromHostBuffer: shape: "
<< device_shape.ToString() << " device: " << device->DebugString();
TF_ASSIGN_OR_RETURN(LocalDeviceState * local_device,
tensorflow::down_cast<PjRtStreamExecutorDevice*>(device)
->GetLocalDeviceState());
absl::InlinedVector<int64_t, 4> tmp_strides;
if (!byte_strides) {
tmp_strides.resize(dims.size());
TF_RETURN_IF_ERROR(
ShapeUtil::ByteStrides(device_shape, absl::MakeSpan(tmp_strides)));
byte_strides = tmp_strides;
}
int64_t size = ShapeUtil::ByteSizeOf(device_shape);
TransferManager* transfer_manager = client()->backend().transfer_manager();
if (device_layout != nullptr) {
*(device_shape.mutable_layout()) = *device_layout;
} else {
TF_ASSIGN_OR_RETURN(
device_shape,
transfer_manager->ChooseCompactLayoutForShape(device_shape));
}
absl::InlinedVector<int64_t, 4> shape_strides(device_shape.dimensions_size());
TF_RETURN_IF_ERROR(
ShapeUtil::ByteStrides(device_shape, absl::MakeSpan(shape_strides)));
bool host_and_device_strides_equal =
(size == 0 || *byte_strides == shape_strides);
TF_ASSIGN_OR_RETURN(
std::unique_ptr<PjRtStreamExecutorBuffer> py_buffer,
AllocateDestinationBuffer(device_shape, device, local_device,
local_device->host_to_device_stream(),
/*is_uninitialized_create=*/false, this));
PjRtStreamExecutorBuffer::ScopedHold device_buffer(
py_buffer->GetBufferWithUsageHold());
CHECK(device_buffer.ok());
std::shared_ptr<TransposePlan> transpose;
if (!host_and_device_strides_equal) {
absl::InlinedVector<int64_t, 4> permutation(dims.size());
absl::c_reverse_copy(device_shape.layout().minor_to_major(),
permutation.begin());
TransposePlan::Options options;
options.elem_size_in_bytes = primitive_util::ByteWidth(type);
options.dims = dims;
options.permutation = permutation;
options.input_layout = TransposePlan::Striding{*byte_strides};
absl::MutexLock lock(&transpose_mu_);
TF_ASSIGN_OR_RETURN(transpose, transpose_cache_.GetOrCreate(options));
}
bool should_pack = primitive_util::IsSubByteNonPredType(type) &&
transfer_manager->PackSubbyteTypes();
int64_t packed_size;
if (should_pack) {
packed_size =
CeilOfRatio<int64_t>(size, 8 / primitive_util::BitWidth(type));
} else {
packed_size = size;
}
// If necessary, allocate a host-side buffer for staging host-to-device
// transfers. On GPU this is a buffer in pinned memory.
std::shared_ptr<void> staging_buffer;
bool must_use_staging_buffer =
host_buffer_semantics == HostBufferSemantics::kImmutableOnlyDuringCall ||
!host_and_device_strides_equal || packed_size != size;
// Allocating multigigabyte pinned buffers can be very slow. In that case,
// using a staging buffer is probably worse than not using one.
// TODO(phawkins): add chunking for transfers.
if (must_use_staging_buffer || (should_stage_host_to_device_transfers() &&
packed_size < (int64_t{1} << 30))) {
void* ptr = host_memory_allocator()->AllocateRaw(
tsl::Allocator::kAllocatorAlignment, transpose ? size : packed_size);
staging_buffer = std::shared_ptr<void>(
ptr, [host_memory_allocator = host_memory_allocator()](void* ptr) {
host_memory_allocator->DeallocateRaw(ptr);
});
}
// Copy the buffer into a staging buffer before returning control to the
// caller if the caller only guaranteed that the buffer is valid for the
// duration of the call. Otherwise, we stage (if necessary) on a separate
// thread.
if (host_buffer_semantics == HostBufferSemantics::kImmutableOnlyDuringCall) {
if (transpose) {
transpose->Execute(data, staging_buffer.get());
if (should_pack) {
primitive_util::PackIntN(
type,
absl::MakeConstSpan(static_cast<const char*>(staging_buffer.get()),
size),
absl::MakeSpan(static_cast<char*>(staging_buffer.get()),
packed_size));
}
} else {
if (should_pack) {
primitive_util::PackIntN(
type, absl::MakeConstSpan(static_cast<const char*>(data), size),
absl::MakeSpan(static_cast<char*>(staging_buffer.get()),
packed_size));
} else {
std::memcpy(staging_buffer.get(), data, size);
}
}
if (on_done_with_host_buffer) {
std::move(on_done_with_host_buffer)();
on_done_with_host_buffer = nullptr;
}
}
// The host to device transfer is performed on a thread pool, mostly because
// it includes linearization that may be slow. It is OK to capture the
// py_buffer pointer because the py_buffer can't be deleted until all the
// usage holds have gone away.
// TODO(misard) assess if it would be preferable to introduce a heuristic to
// put the transfer into the calling thread for small literals.
auto transfer_h2d =
[local_client = client(), transfer_manager, local_device, data, size,
type, packed_size, movable_device_buffer{device_buffer.ToClosure()},
device_shape, should_pack, py_buffer{py_buffer.get()},
on_device_shape{py_buffer->on_device_shape()},
staging_buffer{std::move(staging_buffer)},
on_done_with_host_buffer =
on_done_with_host_buffer
? std::make_shared<absl::AnyInvocable<void() &&>>(
std::move(on_done_with_host_buffer))
: nullptr,
host_buffer_semantics, transpose{std::move(transpose)}]() {
PjRtStreamExecutorBuffer::ScopedHold device_buffer(
movable_device_buffer);
// This function uses TF_CHECK_OK and value() since we have no way
// to report failures from a callback. However, the operations here are
// unlikely to fail and not recoverable even if we were to fail: DMAs to
// memory that has already been allocated, and a possible Event
// allocation.
se::DeviceMemoryBase device_memory = device_buffer->device_memory()[0];
// If applicable on the backend, stage the transfer via host memory
// allocated via the host_memory_allocator. On GPU, this is pinned
// memory.
if (staging_buffer) {
// If we didn't already copy the input buffer into the staging buffer,
// do so now.
if (host_buffer_semantics !=
HostBufferSemantics::kImmutableOnlyDuringCall) {
if (transpose) {
transpose->Execute(data, staging_buffer.get());
if (should_pack) {
primitive_util::PackIntN(
type,
absl::MakeConstSpan(
static_cast<const char*>(staging_buffer.get()), size),
absl::MakeSpan(static_cast<char*>(staging_buffer.get()),
packed_size));
}
} else {
if (should_pack) {
primitive_util::PackIntN(
type,
absl::MakeConstSpan(static_cast<const char*>(data), size),
absl::MakeSpan(static_cast<char*>(staging_buffer.get()),
packed_size));
} else {
std::memcpy(staging_buffer.get(), data, size);
}
}
}
TF_CHECK_OK(local_device->host_to_device_stream()->Memcpy(
&device_memory, staging_buffer.get(), packed_size));
} else {
TF_CHECK_OK(local_device->host_to_device_stream()->Memcpy(
&device_memory, data, packed_size));
}
std::shared_ptr<BufferSequencingEvent> event =
device_buffer->definition_events()[0];
TF_CHECK_OK(AddDestinationBufferSynchronization(
local_device, std::move(device_buffer), event,
local_device->host_to_device_stream()));
TF_CHECK_OK(local_device->ThenExecuteCallback(
local_device->host_to_device_stream(),
[staging_buffer{std::move(staging_buffer)},
on_done_with_host_buffer{
std::move(on_done_with_host_buffer)}]() mutable {
if (on_done_with_host_buffer) {
std::move (*on_done_with_host_buffer)();
}
}));
};
thread_pool()->Schedule(transfer_h2d);
return std::unique_ptr<PjRtBuffer>(std::move(py_buffer));
}
StatusOr<std::unique_ptr<PjRtBuffer>>
PjRtStreamExecutorClient::BufferFromHostBuffer(
const void* data, PrimitiveType type, absl::Span<int64_t const> dims,