Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h +442 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h +73 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h +90 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h +110 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h +66 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h +187 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h +76 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h +472 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h +171 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h +78 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h +54 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/AmpKernels.h +33 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +337 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h +124 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h +178 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h +319 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h +51 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CanUse32BitIndexMath.h +18 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h +102 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h +39 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h +268 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ConvUtils.h +480 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h +19 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Copy.h +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h +19 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h +234 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h +500 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Distance.h +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h +399 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Distributions.h +524 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/EmbeddingBag.h +159 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Fill.h +26 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ForeachUtils.h +385 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FractionalMaxPooling.h +85 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FunctionOfAMatrixUtils.h +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedAdagrad.h +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedAdam.h +32 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedSGD.h +26 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Gelu.h +38 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h +303 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h +116 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GroupedMMUtils.h +172 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Histogram.h +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/IndexKernel.h +46 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/IndexingUtils.h +186 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h +51 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebra.h +22 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h +629 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LossMulti.h +74 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Math.h +0 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/mps/MPSAllocatorInterface.h>
|
| 7 |
+
#include <ATen/mps/MPSEvent.h>
|
| 8 |
+
#include <ATen/mps/MPSStream.h>
|
| 9 |
+
|
| 10 |
+
#include <c10/util/flat_hash_map.h>
|
| 11 |
+
#include <mach/vm_page_size.h>
|
| 12 |
+
#include <cstdio>
|
| 13 |
+
#include <mutex>
|
| 14 |
+
#include <set>
|
| 15 |
+
#include <unordered_set>
|
| 16 |
+
|
| 17 |
+
// this implementation is based on CUDACachingAllocator.
|
| 18 |
+
// It utilizes Metal Heaps to improve the performance with buffer allocation.
|
| 19 |
+
// Do not include this header. Use MPSAllocatorInterface.h instead.
|
| 20 |
+
// TODO: Unify the logic with CUDACachingAllocator and remove redundant code.
|
| 21 |
+
namespace at::mps::HeapAllocator {
|
| 22 |
+
|
| 23 |
+
static const size_t kMaxSmallAlloc = MB(1); // largest "small" allocation is 1 MiB
|
| 24 |
+
static const size_t kMinLargeAlloc = MB(10); // allocations between 1 and 10 MiB may use kLargeHeap
|
| 25 |
+
static const size_t kRoundLarge = MB(2); // round up large allocations to 2 MiB
|
| 26 |
+
static const size_t kSmallHeap = MB(8); // "small" allocations are packed in 8 MiB heaps
|
| 27 |
+
static const size_t kLargeHeap = MB(32); // "large" allocations may be packed in 32 MiB heaps
|
| 28 |
+
static const size_t kXLargeHeapD =
|
| 29 |
+
MB(128); // "extra large" allocations on Discrete devices may be packed in 128 MiB heaps
|
| 30 |
+
static const size_t kXLargeHeapU =
|
| 31 |
+
MB(1024); // "extra large" allocations on Unified devices may be packed in 1 GiB heaps
|
| 32 |
+
static const size_t kMaxScalarAlloc = (sizeof(int64_t)); // largest "scalar" allocation
|
| 33 |
+
|
| 34 |
+
// buffer pools could be customized with a combination of usage flags
|
| 35 |
+
enum UsageFlags : uint32_t {
|
| 36 |
+
PRIVATE = 0,
|
| 37 |
+
SMALL = (1 << 0), // small heaps have sizes of kSmallHeap, and large ones kLargeHeap
|
| 38 |
+
SHARED = (1 << 1), // shared pools allocated on devices with unified memory; otherwise, private between host/device
|
| 39 |
+
MANAGED = (1 << 2), // managed storage mode
|
| 40 |
+
HAZARD = (1 << 3), // enables Automatic Hazard Tracking for the resources allocated on the pool
|
| 41 |
+
SCALAR = (1 << 4), // used to import CPU scalar values to GPU and use them in MPS Stream
|
| 42 |
+
};
|
| 43 |
+
// debug verbosity flags
|
| 44 |
+
enum DebugVerbosity : uint32_t {
|
| 45 |
+
SILENT = 0,
|
| 46 |
+
PROFILING = (1 << 0), // print generic profiling data for total system memory usage
|
| 47 |
+
ALLOCATIONS = (1 << 1), // print buffer allocations
|
| 48 |
+
RECYCLES = (1 << 2), // print buffer recycling
|
| 49 |
+
RELEASES = (1 << 3), // print buffer releases
|
| 50 |
+
LARGE_ONLY = (1 << 4), // only log large buffer pool transactions
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
struct HeapBlock;
|
| 54 |
+
|
| 55 |
+
struct BufferBlock {
|
| 56 |
+
id<MTLBuffer> buffer;
|
| 57 |
+
void* cpu_ptr = nullptr; // stores the pointer to CPU mapping of a Shared MTLBuffer
|
| 58 |
+
size_t size; // size after alignment
|
| 59 |
+
size_t requested_size; // requested size (before alignment)
|
| 60 |
+
// buffer shape is used for retrieving base of views in cached graphs
|
| 61 |
+
std::vector<int64_t> shape;
|
| 62 |
+
bool in_use = false;
|
| 63 |
+
HeapBlock* heap;
|
| 64 |
+
id_t buf_id;
|
| 65 |
+
// counter to candidate least recently used buffers for garbage collection
|
| 66 |
+
uint32_t gc_count = 0;
|
| 67 |
+
uint32_t use_count = 0;
|
| 68 |
+
// counter to assign unique ids to buffer blocks
|
| 69 |
+
static uint64_t buffer_counter;
|
| 70 |
+
// Metal events used to sync GPU/CPU operations on the shared-storage buffers
|
| 71 |
+
MPSEventPtr event;
|
| 72 |
+
|
| 73 |
+
BufferBlock(size_t Size, size_t RequestedSize = 0, const id<MTLBuffer> Buffer = nullptr, HeapBlock* Heap = nullptr)
|
| 74 |
+
: buffer(Buffer), size(Size), requested_size(RequestedSize), heap(Heap), buf_id(Buffer ? ++buffer_counter : 0) {}
|
| 75 |
+
|
| 76 |
+
static bool Comparator(const BufferBlock* a, const BufferBlock* b) {
|
| 77 |
+
return (a->size != b->size) ? a->size < b->size : (uintptr_t)a->buffer < (uintptr_t)b->buffer;
|
| 78 |
+
}
|
| 79 |
+
static size_t alignUp(size_t Size, size_t Alignment) {
|
| 80 |
+
assert(((Alignment - 1) & Alignment) == 0);
|
| 81 |
+
return ((Size + Alignment - 1) & ~(Alignment - 1));
|
| 82 |
+
}
|
| 83 |
+
uint32_t retainCount() const {
|
| 84 |
+
return [buffer retainCount];
|
| 85 |
+
}
|
| 86 |
+
};
|
| 87 |
+
typedef bool (*BufferComparison)(const BufferBlock*, const BufferBlock*);
|
| 88 |
+
|
| 89 |
+
struct BufferPool;
|
| 90 |
+
struct AllocParams {
|
| 91 |
+
AllocParams(size_t Alloc_Size, size_t Requested_Size, BufferPool* Pool)
|
| 92 |
+
: search_key(Alloc_Size), pool(Pool), requested_size(Requested_Size) {}
|
| 93 |
+
size_t size() const {
|
| 94 |
+
return search_key.size;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
BufferBlock search_key;
|
| 98 |
+
BufferPool* pool;
|
| 99 |
+
BufferBlock* buffer_block = nullptr;
|
| 100 |
+
size_t requested_size;
|
| 101 |
+
// true if we exceed the low watermark limit. In this case
|
| 102 |
+
// we apply strategies to relieve the pressure before allocation.
|
| 103 |
+
bool has_memory_pressure = false;
|
| 104 |
+
// true if we're allocating on a unified memory device
|
| 105 |
+
bool has_unified_memory = true;
|
| 106 |
+
};
|
| 107 |
+
|
| 108 |
+
struct HeapBlock {
|
| 109 |
+
id<MTLHeap> heap;
|
| 110 |
+
struct {
|
| 111 |
+
size_t total, available;
|
| 112 |
+
} size;
|
| 113 |
+
BufferPool* pool;
|
| 114 |
+
unsigned int n_buffers = 0;
|
| 115 |
+
id_t heap_id;
|
| 116 |
+
// indicates if we split this heap to sub-allocate 'several' buffers (otherwise single buffer)
|
| 117 |
+
bool is_split;
|
| 118 |
+
// counter to assign unique ids to heap blocks
|
| 119 |
+
static uint64_t heap_counter;
|
| 120 |
+
|
| 121 |
+
HeapBlock(size_t Size, const id<MTLHeap> Heap = nullptr, BufferPool* Pool = nullptr)
|
| 122 |
+
: heap(Heap),
|
| 123 |
+
size({.total = Size, .available = Size}),
|
| 124 |
+
pool(Pool),
|
| 125 |
+
heap_id(Heap ? ++heap_counter : 0),
|
| 126 |
+
is_split(true) {}
|
| 127 |
+
|
| 128 |
+
static MTLResourceOptions getOptions(uint32_t usage) {
|
| 129 |
+
// TODO: check the caching performance of write-combined mode
|
| 130 |
+
MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache;
|
| 131 |
+
|
| 132 |
+
if (usage & UsageFlags::MANAGED)
|
| 133 |
+
options |= MTLResourceStorageModeManaged;
|
| 134 |
+
else if (usage & UsageFlags::SHARED)
|
| 135 |
+
options |= MTLResourceStorageModeShared;
|
| 136 |
+
else
|
| 137 |
+
options |= MTLResourceStorageModePrivate;
|
| 138 |
+
|
| 139 |
+
options |=
|
| 140 |
+
(usage & UsageFlags::HAZARD) ? MTLResourceHazardTrackingModeTracked : MTLResourceHazardTrackingModeUntracked;
|
| 141 |
+
|
| 142 |
+
return options;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
static HeapBlock* createHeapBlock(AllocParams& params, id<MTLDevice> device, uint32_t usage) {
|
| 146 |
+
HeapBlock* heapBlock = nullptr;
|
| 147 |
+
bool is_split = true;
|
| 148 |
+
const size_t size = params.size();
|
| 149 |
+
MTLHeapDescriptor* d = [MTLHeapDescriptor new];
|
| 150 |
+
if (d) {
|
| 151 |
+
const size_t kXLargeHeap = params.has_unified_memory ? kXLargeHeapU : kXLargeHeapD;
|
| 152 |
+
if (size <= kMaxSmallAlloc) {
|
| 153 |
+
d.size = kSmallHeap;
|
| 154 |
+
} else if (size < kMinLargeAlloc) {
|
| 155 |
+
d.size = kLargeHeap;
|
| 156 |
+
} else if (size < kXLargeHeap / 2 && !params.has_memory_pressure) {
|
| 157 |
+
d.size = kXLargeHeap;
|
| 158 |
+
} else {
|
| 159 |
+
d.size = kRoundLarge * ((size + kRoundLarge - 1) / kRoundLarge);
|
| 160 |
+
is_split = false;
|
| 161 |
+
}
|
| 162 |
+
d.storageMode = (usage & UsageFlags::SHARED) ? MTLStorageModeShared : MTLStorageModePrivate;
|
| 163 |
+
d.cpuCacheMode = MTLCPUCacheModeDefaultCache;
|
| 164 |
+
// this automatically handles Metal buffer access synchronizations at the
|
| 165 |
+
// cost of slightly lower performance.
|
| 166 |
+
d.hazardTrackingMode =
|
| 167 |
+
(usage & UsageFlags::HAZARD) ? MTLHazardTrackingModeTracked : MTLHazardTrackingModeUntracked;
|
| 168 |
+
d.resourceOptions = getOptions(usage);
|
| 169 |
+
d.type = MTLHeapTypeAutomatic;
|
| 170 |
+
id<MTLHeap> heap = [device newHeapWithDescriptor:d];
|
| 171 |
+
if (heap) {
|
| 172 |
+
[heap setPurgeableState:MTLPurgeableStateNonVolatile];
|
| 173 |
+
const size_t heap_size = heapAvailableSize(heap);
|
| 174 |
+
heapBlock = new HeapBlock(heap_size, heap, params.pool);
|
| 175 |
+
if (heapBlock) {
|
| 176 |
+
heapBlock->is_split = is_split;
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
[d release];
|
| 180 |
+
}
|
| 181 |
+
return heapBlock;
|
| 182 |
+
}
|
| 183 |
+
static bool Comparator(const HeapBlock* a, const HeapBlock* b) {
|
| 184 |
+
return (a->size.available != b->size.available) ? a->size.available < b->size.available
|
| 185 |
+
: (uintptr_t)a->heap < (uintptr_t)b->heap;
|
| 186 |
+
}
|
| 187 |
+
static NSUInteger heapAvailableSize(id<MTLHeap> heap, size_t Alignment = vm_page_size) {
|
| 188 |
+
return [heap maxAvailableSizeWithAlignment:Alignment];
|
| 189 |
+
}
|
| 190 |
+
NSUInteger Size() {
|
| 191 |
+
return [heap size];
|
| 192 |
+
}
|
| 193 |
+
id<MTLBuffer> newMTLBuffer(size_t length, uint32_t usage) {
|
| 194 |
+
id<MTLBuffer> buf = [heap newBufferWithLength:length options:getOptions(usage)];
|
| 195 |
+
if (buf) {
|
| 196 |
+
updateAvailableSize();
|
| 197 |
+
n_buffers++;
|
| 198 |
+
}
|
| 199 |
+
return buf;
|
| 200 |
+
}
|
| 201 |
+
// returns the retainCount before releasing the buffer
|
| 202 |
+
uint32_t releaseMTLBuffer(id<MTLBuffer>& buffer) {
|
| 203 |
+
const uint32_t retainCount = [buffer retainCount];
|
| 204 |
+
[buffer release];
|
| 205 |
+
buffer = nil;
|
| 206 |
+
updateAvailableSize();
|
| 207 |
+
n_buffers--;
|
| 208 |
+
return retainCount;
|
| 209 |
+
}
|
| 210 |
+
// returns the retainCount before releasing the heap
|
| 211 |
+
uint32_t releaseMTLHeap() {
|
| 212 |
+
const uint32_t retainCount = [heap retainCount];
|
| 213 |
+
TORCH_INTERNAL_ASSERT(!n_buffers); // assert if heap isn't empty
|
| 214 |
+
[heap setPurgeableState:MTLPurgeableStateEmpty];
|
| 215 |
+
[heap release];
|
| 216 |
+
heap = nil;
|
| 217 |
+
size.available = 0;
|
| 218 |
+
return retainCount;
|
| 219 |
+
}
|
| 220 |
+
uint32_t retainCount() const {
|
| 221 |
+
return [heap retainCount];
|
| 222 |
+
}
|
| 223 |
+
void updateAvailableSize() {
|
| 224 |
+
size.available = heapAvailableSize(heap);
|
| 225 |
+
}
|
| 226 |
+
};
|
| 227 |
+
typedef bool (*HeapComparison)(const HeapBlock*, const HeapBlock*);
|
| 228 |
+
|
| 229 |
+
struct BufferPool {
|
| 230 |
+
enum class Kind {
|
| 231 |
+
PRIVATE_SMALL,
|
| 232 |
+
PRIVATE_LARGE,
|
| 233 |
+
SHARED_SMALL,
|
| 234 |
+
SHARED_LARGE,
|
| 235 |
+
SCALAR,
|
| 236 |
+
};
|
| 237 |
+
|
| 238 |
+
BufferPool(const id<MTLDevice> Device, uint32_t Usage)
|
| 239 |
+
: device(Device), usage(Usage), heaps(HeapBlock::Comparator), available_buffers(BufferBlock::Comparator) {}
|
| 240 |
+
|
| 241 |
+
const id<MTLDevice> device;
|
| 242 |
+
// usage flags to customize the pool for various purposes (see UsageFlags enum)
|
| 243 |
+
const uint32_t usage;
|
| 244 |
+
// total number of buffers in the pool
|
| 245 |
+
uint32_t n_buffers = 0;
|
| 246 |
+
// total allocations size on this pool
|
| 247 |
+
size_t allocated_size = 0;
|
| 248 |
+
// total memory available in the pool
|
| 249 |
+
size_t available_size = 0;
|
| 250 |
+
// list of heaps ordered by their "available" (not total) memory size
|
| 251 |
+
std::set<HeapBlock*, HeapComparison> heaps;
|
| 252 |
+
// list of only "available" buffers in the pool (i.e., buffers not in-use)
|
| 253 |
+
std::set<BufferBlock*, BufferComparison> available_buffers;
|
| 254 |
+
// list of buffers that are in a state of "limbo" where they've already been freed
|
| 255 |
+
// from PyTorch-side, but were not returned to pool due to still being
|
| 256 |
+
// in-use by command buffers with retainCount > 1. In this state, the buffer is
|
| 257 |
+
// neither ready to be recycled, nor could be returned to pool as available.
|
| 258 |
+
// These buffers will be returned to pool once the command buffer's
|
| 259 |
+
// completionHandler callbacks are called.
|
| 260 |
+
std::unordered_set<BufferBlock*> buffers_pending_free;
|
| 261 |
+
// list of heaps pending size update
|
| 262 |
+
std::unordered_set<HeapBlock*> heaps_pending_update;
|
| 263 |
+
};
|
| 264 |
+
|
| 265 |
+
class MPSHeapAllocatorImpl {
|
| 266 |
+
public:
|
| 267 |
+
explicit MPSHeapAllocatorImpl()
|
| 268 |
+
: m_device(at::mps::MPSDevice::getInstance()->device()),
|
| 269 |
+
m_max_buffer_size([m_device maxBufferLength]),
|
| 270 |
+
m_stream(getDefaultMPSStream()),
|
| 271 |
+
m_event_pool(getMPSEventPool()) {
|
| 272 |
+
init_allocator();
|
| 273 |
+
}
|
| 274 |
+
~MPSHeapAllocatorImpl() {
|
| 275 |
+
emptyCache();
|
| 276 |
+
}
|
| 277 |
+
// interface exposed to at::Allocator
|
| 278 |
+
id<MTLBuffer> malloc(size_t size, uint32_t usage);
|
| 279 |
+
// frees a buffer and returns it into buffer pool
|
| 280 |
+
void free(void* ptr);
|
| 281 |
+
// releases all the cached buffers and their associated heaps
|
| 282 |
+
void emptyCache();
|
| 283 |
+
// free inactive buffers that are pending to be freed
|
| 284 |
+
void freeInactiveBuffers();
|
| 285 |
+
// returns true if buffer was allocated from the shared pool
|
| 286 |
+
bool isSharedBuffer(const void* ptr);
|
| 287 |
+
// get the requested unaligned size of an MTLBuffer
|
| 288 |
+
ssize_t getUnalignedBufferSize(const void* ptr);
|
| 289 |
+
// set the shape of a base tensor from a view tensor
|
| 290 |
+
void setBufferShape(const void* ptr, const IntArrayRef& shape);
|
| 291 |
+
// retrieve the shape of a base tensor from a view tensor
|
| 292 |
+
IntArrayRef getBufferShape(const void* ptr);
|
| 293 |
+
// get the unique ID of the buffer
|
| 294 |
+
id_t getBufferId(const void* ptr);
|
| 295 |
+
// allocate a buffer from a specialized pool to import CPU scalars into GPU
|
| 296 |
+
id<MTLBuffer> allocScalarBufferWithValue(void* value, size_t size);
|
| 297 |
+
// returns a CPU-mapping of the input buffer and its retainCount,
|
| 298 |
+
// if only it has Shared storage-mode and allocated on MPSAllocator
|
| 299 |
+
std::pair<const void*, uint32_t> getSharedBufferPtr(const void* buffer);
|
| 300 |
+
// records events for a list of MTLBuffers (list is used to lock the mutex once)
|
| 301 |
+
// returns true if records any event (given if passed buffers exist and are shared-storage)
|
| 302 |
+
bool recordEvents(c10::ArrayRef<const void*> buffers);
|
| 303 |
+
// waits for the event to signal the completion of GPU execution
|
| 304 |
+
// on the passed shared buffers (list is used to lock the mutex once)
|
| 305 |
+
// returns true if actually waited on any event
|
| 306 |
+
bool waitForEvents(c10::ArrayRef<const void*> buffers);
|
| 307 |
+
// this indicates how far (in Megabytes) the current total allocations are from the
|
| 308 |
+
// low watermark limit which is used to detect if we're under memory pressure
|
| 309 |
+
// This returns zero if we've reached the low watermark limit
|
| 310 |
+
ssize_t getLowWatermarkValue();
|
| 311 |
+
// (see m_low_watermark_ratio for description)
|
| 312 |
+
void setLowWatermarkRatio(double ratio);
|
| 313 |
+
// (see m_high_watermark_ratio for description)
|
| 314 |
+
void setHighWatermarkRatio(double ratio);
|
| 315 |
+
// (see m_low_watermark_limit for description)
|
| 316 |
+
size_t getLowWatermarkLimit() const {
|
| 317 |
+
return m_low_watermark_limit;
|
| 318 |
+
}
|
| 319 |
+
// (see m_max_total_allowed_size for description)
|
| 320 |
+
size_t getHighWatermarkLimit() const {
|
| 321 |
+
return m_max_total_allowed_size;
|
| 322 |
+
}
|
| 323 |
+
// (see m_total_allocated_memory for description)
|
| 324 |
+
size_t getTotalAllocatedMemory() const {
|
| 325 |
+
return m_total_allocated_memory;
|
| 326 |
+
}
|
| 327 |
+
// (see m_current_allocated_memory for description)
|
| 328 |
+
size_t getCurrentAllocatedMemory() const {
|
| 329 |
+
return m_current_allocated_memory;
|
| 330 |
+
}
|
| 331 |
+
// total GPU memory allocated in the process by Metal driver; including
|
| 332 |
+
// implicit allocations from MPS/MPSGraph frameworks and MPSHeapAllocatorImpl.
|
| 333 |
+
size_t getDriverAllocatedMemory() const {
|
| 334 |
+
return current_allocated_size();
|
| 335 |
+
}
|
| 336 |
+
// recommended Max memory for Metal
|
| 337 |
+
size_t getRecommendedMaxMemory() const {
|
| 338 |
+
return max_device_size();
|
| 339 |
+
}
|
| 340 |
+
// (see enum DebugVerbosity for description)
|
| 341 |
+
uint32_t getDebugVerbosity() const {
|
| 342 |
+
return m_debug_verbosity;
|
| 343 |
+
}
|
| 344 |
+
// returns the device that we allocate from
|
| 345 |
+
inline id<MTLDevice> Device() const {
|
| 346 |
+
return m_device;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
inline std::string format_size(uint64_t size) const;
|
| 350 |
+
|
| 351 |
+
private:
|
| 352 |
+
// (see m_high_watermark_ratio for description)
|
| 353 |
+
constexpr static double default_high_watermark_ratio = 1.7;
|
| 354 |
+
// we set the allowed upper bound to twice the size of recommendedMaxWorkingSetSize.
|
| 355 |
+
constexpr static double default_high_watermark_upper_bound = 2.0;
|
| 356 |
+
// (see m_low_watermark_ratio for description)
|
| 357 |
+
// on unified memory, we could allocate beyond the recommendedMaxWorkingSetSize
|
| 358 |
+
constexpr static double default_low_watermark_ratio_unified = 1.4;
|
| 359 |
+
constexpr static double default_low_watermark_ratio_discrete = 1.0;
|
| 360 |
+
|
| 361 |
+
const id<MTLDevice> m_device;
|
| 362 |
+
std::recursive_mutex m_mutex;
|
| 363 |
+
// allocated buffers by device pointer
|
| 364 |
+
ska::flat_hash_map<const void*, BufferBlock*> m_allocated_buffers;
|
| 365 |
+
// using a container for pools to simplify iterating them
|
| 366 |
+
ska::flat_hash_map<BufferPool::Kind, std::unique_ptr<BufferPool>> m_pools;
|
| 367 |
+
// total memory allocated by HeapAllocator (including blocks in pools)
|
| 368 |
+
size_t m_total_allocated_memory = 0;
|
| 369 |
+
// currently active memory allocations in use (i.e., blocks not in pools)
|
| 370 |
+
size_t m_current_allocated_memory = 0;
|
| 371 |
+
// max buffer size allowed by Metal
|
| 372 |
+
size_t m_max_buffer_size = 0;
|
| 373 |
+
// maximum total size allowed to be allocated
|
| 374 |
+
size_t m_max_total_allowed_size = 0;
|
| 375 |
+
// high watermark ratio is a hard limit for the total allowed allocations
|
| 376 |
+
// 0. : disables high watermark limit (may cause system failure if system-wide OOM occurs)
|
| 377 |
+
// 1. : recommended maximum allocation size (i.e., device.recommendedMaxWorkingSetSize)
|
| 378 |
+
// >1.: allows limits beyond the device.recommendedMaxWorkingSetSize
|
| 379 |
+
// e.g., value 0.95 means we allocate up to 95% of recommended maximum
|
| 380 |
+
// allocation size; beyond that, the allocations would fail with OOM error.
|
| 381 |
+
double m_high_watermark_ratio;
|
| 382 |
+
// low watermark ratio is a soft limit to attempt limiting memory allocations up to the lower watermark
|
| 383 |
+
// level by garbage collection or committing command buffers more frequently (a.k.a, adaptive commit).
|
| 384 |
+
// Value between 0 to m_high_watermark_ratio (setting 0.0 disables adaptive commit and garbage collection)
|
| 385 |
+
// e.g., value 0.9 means we 'attempt' to limit allocations up to 90% of recommended maximum
|
| 386 |
+
// allocation size.
|
| 387 |
+
double m_low_watermark_ratio;
|
| 388 |
+
// low watermark size limit (in Bytes) at the time we initialize the allocator
|
| 389 |
+
size_t m_low_watermark_limit;
|
| 390 |
+
// use "PYTORCH_DEBUG_MPS_ALLOCATOR" env-var to set debug verbosity
|
| 391 |
+
uint32_t m_debug_verbosity;
|
| 392 |
+
// default MPS stream
|
| 393 |
+
MPSStream* m_stream;
|
| 394 |
+
// we hold a reference to MPSEventPool so it could get destroyed after MPSAllocator
|
| 395 |
+
std::shared_ptr<MPSEventPool> m_event_pool;
|
| 396 |
+
|
| 397 |
+
void init_allocator();
|
| 398 |
+
void init_buffer_pools();
|
| 399 |
+
HeapBlock* get_free_heap(AllocParams& params);
|
| 400 |
+
bool get_free_buffer(AllocParams& params);
|
| 401 |
+
BufferBlock* get_allocated_buffer_block(const void* ptr);
|
| 402 |
+
BufferBlock* alloc_buffer_block(size_t size, uint32_t usage);
|
| 403 |
+
bool alloc_buffer(AllocParams& params);
|
| 404 |
+
void free_buffer(BufferBlock* buffer_block);
|
| 405 |
+
// returns true if the container heap is also released
|
| 406 |
+
bool release_buffer(BufferBlock* buffer_block, bool remove_empty_heap = true);
|
| 407 |
+
void release_buffers(BufferPool& pool);
|
| 408 |
+
bool release_available_cached_buffers(AllocParams& params);
|
| 409 |
+
bool release_cached_buffers();
|
| 410 |
+
// free unused cached blocks to reclaim GPU memory if memory pressure is high
|
| 411 |
+
void garbage_collect_cached_buffers(AllocParams& params);
|
| 412 |
+
// returns the suitable buffer pool type for the usage or
|
| 413 |
+
// requested/allocated sizes
|
| 414 |
+
BufferPool& get_pool(size_t requested_size, size_t aligned_size, uint32_t usage);
|
| 415 |
+
// returns the aligned allocation size that is optimized
|
| 416 |
+
// for the buffers to get reused frequently
|
| 417 |
+
size_t get_allocation_size(size_t size, uint32_t usage) const;
|
| 418 |
+
// maximum size of device memory available for allocation in current process
|
| 419 |
+
// Note: the recommendedMaxWorkingSetSize is typically 75% of the total system memory.
|
| 420 |
+
size_t max_device_size() const {
|
| 421 |
+
return [m_device recommendedMaxWorkingSetSize];
|
| 422 |
+
}
|
| 423 |
+
// there are implicit allocations from MPS backend, so we need to query the 'device' for
|
| 424 |
+
// total allocated size instead of manually tracking in MPSAllocator
|
| 425 |
+
size_t current_allocated_size() const {
|
| 426 |
+
return [m_device currentAllocatedSize];
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
bool trigger_memory_callbacks(BufferBlock* buffer_block, IMpsAllocatorCallback::EventType event) const {
|
| 430 |
+
for (const auto& name : MPSAllocatorCallbacksRegistry()->Keys()) {
|
| 431 |
+
MPSAllocatorCallbacksRegistry()->Create(name)->executeMPSAllocatorCallback(
|
| 432 |
+
buffer_block ? buffer_block->buffer : nullptr, event);
|
| 433 |
+
}
|
| 434 |
+
return true;
|
| 435 |
+
}
|
| 436 |
+
};
|
| 437 |
+
|
| 438 |
+
} // namespace at::mps::HeapAllocator
|
| 439 |
+
|
| 440 |
+
#else
|
| 441 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 442 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2023 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/core/ATen_fwd.h>
|
| 7 |
+
#include <c10/core/Allocator.h>
|
| 8 |
+
#include <c10/util/Registry.h>
|
| 9 |
+
|
| 10 |
+
#define MB(x) (x * 1048576UL)
|
| 11 |
+
|
| 12 |
+
namespace at::mps {
|
| 13 |
+
|
| 14 |
+
// this is a public interface to access MPSAllocator.
|
| 15 |
+
// Do not declare methods that would depend on MPS or Metal frameworks.
|
| 16 |
+
class IMPSAllocator : public c10::Allocator {
|
| 17 |
+
public:
|
| 18 |
+
// see the comments in MPSAllocator.h for the description of these methods.
|
| 19 |
+
virtual void emptyCache() const = 0;
|
| 20 |
+
virtual void freeInactiveBuffers() const = 0;
|
| 21 |
+
virtual ssize_t getUnalignedBufferSize(const void* ptr) const = 0;
|
| 22 |
+
virtual IntArrayRef getBufferShape(const void* ptr) const = 0;
|
| 23 |
+
virtual id_t getBufferId(const void* ptr) const = 0;
|
| 24 |
+
virtual void setBufferShape(const void* ptr, const IntArrayRef& shape)
|
| 25 |
+
const = 0;
|
| 26 |
+
virtual bool isSharedBuffer(const void* ptr) const = 0;
|
| 27 |
+
virtual bool isSharedStorageSupported() const = 0;
|
| 28 |
+
virtual c10::DataPtr allocScalarBufferWithValue(void* value, size_t size)
|
| 29 |
+
const = 0;
|
| 30 |
+
virtual std::string formatSize(size_t size) const = 0;
|
| 31 |
+
virtual void setLowWatermarkRatio(double ratio) const = 0;
|
| 32 |
+
virtual void setHighWatermarkRatio(double ratio) const = 0;
|
| 33 |
+
virtual ssize_t getLowWatermarkValue() const = 0;
|
| 34 |
+
virtual size_t getLowWatermarkLimit() const = 0;
|
| 35 |
+
virtual size_t getHighWatermarkLimit() const = 0;
|
| 36 |
+
virtual size_t getTotalAllocatedMemory() const = 0;
|
| 37 |
+
virtual size_t getCurrentAllocatedMemory() const = 0;
|
| 38 |
+
virtual size_t getDriverAllocatedMemory() const = 0;
|
| 39 |
+
virtual size_t getRecommendedMaxMemory() const = 0;
|
| 40 |
+
virtual std::pair<const void*, uint32_t> getSharedBufferPtr(
|
| 41 |
+
const void* ptr) const = 0;
|
| 42 |
+
virtual bool recordEvents(c10::ArrayRef<const void*> buffers) const = 0;
|
| 43 |
+
virtual bool waitForEvents(c10::ArrayRef<const void*> buffers) const = 0;
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
class IMpsAllocatorCallback {
|
| 47 |
+
public:
|
| 48 |
+
enum class EventType {
|
| 49 |
+
ALLOCATED, // buffer got allocated to be used immediately
|
| 50 |
+
RECYCLED, // buffer pulled from free list to be reused
|
| 51 |
+
FREED, // buffer put to free list for future recycling
|
| 52 |
+
RELEASED, // buffer memory released
|
| 53 |
+
ALLOCATION_FAILED // buffer allocation failed
|
| 54 |
+
};
|
| 55 |
+
virtual ~IMpsAllocatorCallback() = default;
|
| 56 |
+
virtual void executeMPSAllocatorCallback(void* ptr, EventType event) = 0;
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
// MPS allocator will execute every registered callback when a block of memory
|
| 60 |
+
// is freed.
|
| 61 |
+
TORCH_DECLARE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback);
|
| 62 |
+
#define REGISTER_MPS_ALLOCATOR_CALLBACK(name, ...) \
|
| 63 |
+
C10_REGISTER_CLASS(MPSAllocatorCallbacksRegistry, name, __VA_ARGS__)
|
| 64 |
+
|
| 65 |
+
IMPSAllocator* getIMPSAllocator(bool sharedAllocator = false);
|
| 66 |
+
|
| 67 |
+
bool isMPSPinnedPtr(const void* data);
|
| 68 |
+
|
| 69 |
+
} // namespace at::mps
|
| 70 |
+
|
| 71 |
+
#else
|
| 72 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 73 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
#include <ATen/Device.h>
|
| 6 |
+
#include <c10/core/Allocator.h>
|
| 7 |
+
#include <c10/macros/Macros.h>
|
| 8 |
+
#include <c10/util/Exception.h>
|
| 9 |
+
|
| 10 |
+
#ifdef __OBJC__
|
| 11 |
+
#include <Foundation/Foundation.h>
|
| 12 |
+
#include <Metal/Metal.h>
|
| 13 |
+
typedef id<MTLDevice> MTLDevice_t;
|
| 14 |
+
#else
|
| 15 |
+
typedef void* MTLDevice_t;
|
| 16 |
+
#endif
|
| 17 |
+
|
| 18 |
+
namespace at::mps {
|
| 19 |
+
|
| 20 |
+
// Helper enum to check if a MPSGraph op is supported in a given macOS version
|
| 21 |
+
enum class MacOSVersion : uint32_t {
|
| 22 |
+
MACOS_VER_14_4_PLUS = 0,
|
| 23 |
+
MACOS_VER_15_0_PLUS,
|
| 24 |
+
MACOS_VER_15_1_PLUS,
|
| 25 |
+
MACOS_VER_15_2_PLUS,
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
//-----------------------------------------------------------------
|
| 29 |
+
// MPSDevice
|
| 30 |
+
//
|
| 31 |
+
// MPSDevice is a singleton class that returns the default device
|
| 32 |
+
//-----------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
class TORCH_API MPSDevice {
|
| 35 |
+
public:
|
| 36 |
+
/**
|
| 37 |
+
* MPSDevice should not be cloneable.
|
| 38 |
+
*/
|
| 39 |
+
MPSDevice(MPSDevice& other) = delete;
|
| 40 |
+
/**
|
| 41 |
+
* MPSDevice should not be assignable.
|
| 42 |
+
*/
|
| 43 |
+
void operator=(const MPSDevice&) = delete;
|
| 44 |
+
/**
|
| 45 |
+
* Gets single instance of the Device.
|
| 46 |
+
*/
|
| 47 |
+
static MPSDevice* getInstance();
|
| 48 |
+
/**
|
| 49 |
+
* Returns the single device.
|
| 50 |
+
*/
|
| 51 |
+
MTLDevice_t device() {
|
| 52 |
+
return _mtl_device;
|
| 53 |
+
}
|
| 54 |
+
/**
|
| 55 |
+
* Returns whether running on Ventura or newer
|
| 56 |
+
*/
|
| 57 |
+
bool isMacOS13Plus(MacOSVersion version) const;
|
| 58 |
+
|
| 59 |
+
/**
|
| 60 |
+
* Returns device name
|
| 61 |
+
*/
|
| 62 |
+
std::string getName() const;
|
| 63 |
+
|
| 64 |
+
/**
|
| 65 |
+
* Returns number of GPU cores.
|
| 66 |
+
* 1 Core = 16 ExecutionUnit x 8 ALU x 24 threads
|
| 67 |
+
*/
|
| 68 |
+
unsigned getCoreCount() const;
|
| 69 |
+
|
| 70 |
+
~MPSDevice();
|
| 71 |
+
|
| 72 |
+
private:
|
| 73 |
+
static MPSDevice* _device;
|
| 74 |
+
MTLDevice_t _mtl_device;
|
| 75 |
+
MPSDevice();
|
| 76 |
+
};
|
| 77 |
+
|
| 78 |
+
TORCH_API bool is_available();
|
| 79 |
+
TORCH_API bool is_macos_13_or_newer(MacOSVersion version);
|
| 80 |
+
TORCH_API at::Allocator* GetMPSAllocator(bool useSharedAllocator = false);
|
| 81 |
+
|
| 82 |
+
inline Device getDeviceFromPtr(void* ptr) {
|
| 83 |
+
return {c10::DeviceType::MPS, 0};
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
} // namespace at::mps
|
| 87 |
+
|
| 88 |
+
#else
|
| 89 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 90 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2023 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/mps/MPSStream.h>
|
| 7 |
+
#include <ctime>
|
| 8 |
+
#include <stack>
|
| 9 |
+
|
| 10 |
+
namespace at::mps {
|
| 11 |
+
|
| 12 |
+
// NOTE: don't create instances of this class directly.
|
| 13 |
+
// Use MPSEventPool to acquire instances of MPSEvent.
|
| 14 |
+
class MPSEvent {
|
| 15 |
+
public:
|
| 16 |
+
explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing);
|
| 17 |
+
~MPSEvent();
|
| 18 |
+
|
| 19 |
+
// records an event on the stream
|
| 20 |
+
void record(bool needsLock, bool syncEvent = false);
|
| 21 |
+
// makes all future work submitted to the stream wait for this event.
|
| 22 |
+
bool wait(bool needsLock, bool syncEvent = false);
|
| 23 |
+
// schedules a notifyListener callback for the event.
|
| 24 |
+
bool notify(bool needsLock, MTLSharedEventNotificationBlock block);
|
| 25 |
+
// checks if events are already signaled.
|
| 26 |
+
bool query() const;
|
| 27 |
+
// blocks the CPU thread until all the GPU work that were scheduled
|
| 28 |
+
// prior to recording this event are completed.
|
| 29 |
+
bool synchronize();
|
| 30 |
+
// resets this event with new parameters in case it gets reused from the event
|
| 31 |
+
// pool
|
| 32 |
+
void reset(MPSStream* stream, bool enable_timing);
|
| 33 |
+
// returns the unique ID of the event instance
|
| 34 |
+
id_t getID() const {
|
| 35 |
+
return m_id;
|
| 36 |
+
}
|
| 37 |
+
// returns the completion timestamp of the event
|
| 38 |
+
uint64_t getCompletionTime() const {
|
| 39 |
+
return m_completion_time;
|
| 40 |
+
}
|
| 41 |
+
// if already recorded, waits for cpu_sync_cv to be signaled
|
| 42 |
+
void waitForCpuSync();
|
| 43 |
+
|
| 44 |
+
private:
|
| 45 |
+
id_t m_id;
|
| 46 |
+
// enables measuring the completion time of the notifyListener of this event
|
| 47 |
+
bool m_enable_timing;
|
| 48 |
+
uint64_t m_signalCounter = 0;
|
| 49 |
+
MPSStream* m_stream = nullptr;
|
| 50 |
+
MTLSharedEvent_t m_event = nullptr;
|
| 51 |
+
MTLSharedEventListener* m_listener = nullptr;
|
| 52 |
+
// used to sync the events created on this Stream with CPU
|
| 53 |
+
std::mutex m_cpu_sync_mutex{};
|
| 54 |
+
std::condition_variable m_cpu_sync_cv{};
|
| 55 |
+
// CondVar predicate to sync the events created on this Stream with CPU
|
| 56 |
+
bool m_cpu_sync_completed = false;
|
| 57 |
+
// used to compute elapsed time
|
| 58 |
+
uint64_t m_completion_time = 0;
|
| 59 |
+
|
| 60 |
+
void recordLocked(bool syncEvent);
|
| 61 |
+
bool waitLocked(bool syncEvent);
|
| 62 |
+
bool notifyLocked(MTLSharedEventNotificationBlock block);
|
| 63 |
+
void notifyCpuSync();
|
| 64 |
+
static uint64_t getTime() {
|
| 65 |
+
return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
|
| 66 |
+
}
|
| 67 |
+
};
|
| 68 |
+
|
| 69 |
+
typedef std::unique_ptr<MPSEvent, std::function<void(MPSEvent*)>> MPSEventPtr;
|
| 70 |
+
|
| 71 |
+
class MPSEventPool {
|
| 72 |
+
public:
|
| 73 |
+
explicit MPSEventPool(MPSStream* default_stream);
|
| 74 |
+
~MPSEventPool();
|
| 75 |
+
|
| 76 |
+
MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream);
|
| 77 |
+
void emptyCache();
|
| 78 |
+
|
| 79 |
+
// these are mainly used for MPSHooks and torch.mps.Event() bindings
|
| 80 |
+
id_t acquireEvent(bool enable_timing);
|
| 81 |
+
void releaseEvent(id_t event_id);
|
| 82 |
+
void recordEvent(id_t event_id, bool syncEvent);
|
| 83 |
+
void waitForEvent(id_t event_id, bool syncEvent);
|
| 84 |
+
void synchronizeEvent(id_t event_id);
|
| 85 |
+
bool queryEvent(id_t event_id);
|
| 86 |
+
// returns elapsed time between two recorded events in milliseconds
|
| 87 |
+
double elapsedTime(id_t start_event_id, id_t end_event_id);
|
| 88 |
+
|
| 89 |
+
private:
|
| 90 |
+
MPSStream* m_default_stream = nullptr;
|
| 91 |
+
std::recursive_mutex m_mutex;
|
| 92 |
+
std::stack<std::unique_ptr<MPSEvent>> m_pool{};
|
| 93 |
+
// dictionary to associate event IDs with event objects
|
| 94 |
+
// used to retain in-use events out of the pool
|
| 95 |
+
// for torch.mps.Event() bindings.
|
| 96 |
+
std::unordered_map<id_t, MPSEventPtr> m_in_use_events{};
|
| 97 |
+
uint64_t m_event_counter = 0;
|
| 98 |
+
std::function<void(MPSEvent*)> m_default_deleter;
|
| 99 |
+
|
| 100 |
+
MPSEvent* getInUseEvent(id_t event_id, bool locked = true);
|
| 101 |
+
};
|
| 102 |
+
|
| 103 |
+
// shared_ptr is used to get MPSEventPool destroyed after dependent instances
|
| 104 |
+
std::shared_ptr<MPSEventPool> getMPSEventPool();
|
| 105 |
+
|
| 106 |
+
} // namespace at::mps
|
| 107 |
+
|
| 108 |
+
#else
|
| 109 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 110 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/core/Generator.h>
|
| 7 |
+
#include <ATen/core/PhiloxRNGEngine.h>
|
| 8 |
+
#include <c10/core/GeneratorImpl.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
|
| 11 |
+
namespace at {
|
| 12 |
+
namespace mps::detail {
|
| 13 |
+
|
| 14 |
+
constexpr uint32_t PHILOX_STATE_N = 7;
|
| 15 |
+
struct rng_data_pod {
|
| 16 |
+
std::array<uint32_t, PHILOX_STATE_N> state{1};
|
| 17 |
+
uint64_t seed = default_rng_seed_val;
|
| 18 |
+
};
|
| 19 |
+
|
| 20 |
+
TORCH_API const Generator& getDefaultMPSGenerator();
|
| 21 |
+
TORCH_API Generator
|
| 22 |
+
createMPSGenerator(uint64_t seed_val = default_rng_seed_val);
|
| 23 |
+
|
| 24 |
+
} // namespace mps::detail
|
| 25 |
+
|
| 26 |
+
struct TORCH_API MPSGeneratorImpl : public c10::GeneratorImpl {
|
| 27 |
+
// Constructors
|
| 28 |
+
MPSGeneratorImpl(uint64_t seed_in = default_rng_seed_val);
|
| 29 |
+
~MPSGeneratorImpl() override = default;
|
| 30 |
+
|
| 31 |
+
// MPSGeneratorImpl methods
|
| 32 |
+
std::shared_ptr<MPSGeneratorImpl> clone() const;
|
| 33 |
+
void set_current_seed(uint64_t seed) override;
|
| 34 |
+
void set_offset(uint64_t offset) override;
|
| 35 |
+
uint64_t get_offset() const override;
|
| 36 |
+
uint64_t current_seed() const override;
|
| 37 |
+
uint64_t seed() override;
|
| 38 |
+
void set_state(const c10::TensorImpl& new_state) override;
|
| 39 |
+
c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
|
| 40 |
+
void update_philox_counters();
|
| 41 |
+
|
| 42 |
+
void set_engine(at::Philox4_32 engine) {
|
| 43 |
+
engine_ = engine;
|
| 44 |
+
}
|
| 45 |
+
at::Philox4_32 engine() {
|
| 46 |
+
return engine_;
|
| 47 |
+
}
|
| 48 |
+
uint32_t* state_data() {
|
| 49 |
+
return data_.state.data();
|
| 50 |
+
}
|
| 51 |
+
static DeviceType device_type() {
|
| 52 |
+
return DeviceType::MPS;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
private:
|
| 56 |
+
mps::detail::rng_data_pod data_;
|
| 57 |
+
at::Philox4_32 engine_;
|
| 58 |
+
|
| 59 |
+
MPSGeneratorImpl* clone_impl() const override;
|
| 60 |
+
};
|
| 61 |
+
|
| 62 |
+
} // namespace at
|
| 63 |
+
|
| 64 |
+
#else
|
| 65 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 66 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/mps/MPSEvent.h>
|
| 7 |
+
#include <ATen/mps/MPSStream.h>
|
| 8 |
+
#include <c10/core/impl/DeviceGuardImplInterface.h>
|
| 9 |
+
#include <c10/macros/Macros.h>
|
| 10 |
+
#include <c10/util/Exception.h>
|
| 11 |
+
|
| 12 |
+
#ifdef __OBJC__
|
| 13 |
+
#include <Foundation/Foundation.h>
|
| 14 |
+
#include <Metal/Metal.h>
|
| 15 |
+
#include <MetalPerformanceShaders/MetalPerformanceShaders.h>
|
| 16 |
+
#endif
|
| 17 |
+
|
| 18 |
+
#include <ATen/Tensor.h>
|
| 19 |
+
#include <c10/core/MemoryFormat.h>
|
| 20 |
+
#include <c10/core/Storage.h>
|
| 21 |
+
#include <c10/core/TensorImpl.h>
|
| 22 |
+
#include <c10/core/UndefinedTensorImpl.h>
|
| 23 |
+
#include <c10/util/intrusive_ptr.h>
|
| 24 |
+
#include <sys/_types/_size_t.h>
|
| 25 |
+
#include <memory>
|
| 26 |
+
|
| 27 |
+
namespace at::mps {
|
| 28 |
+
|
| 29 |
+
typedef MPSEvent* mpsEvent_t;
|
| 30 |
+
|
| 31 |
+
// TODO: Move the MPSGuardImpl to inherit from NoOpDeviceGuardImpl
|
| 32 |
+
// https://github.com/pytorch/pytorch/issues/77170
|
| 33 |
+
struct TORCH_API MPSGuardImpl final
|
| 34 |
+
: public c10::impl::DeviceGuardImplInterface {
|
| 35 |
+
static constexpr c10::DeviceType static_type = c10::DeviceType::MPS;
|
| 36 |
+
|
| 37 |
+
// constructor
|
| 38 |
+
MPSGuardImpl() {}
|
| 39 |
+
explicit MPSGuardImpl(c10::DeviceType t) {
|
| 40 |
+
TORCH_CHECK(
|
| 41 |
+
t == DeviceType::MPS,
|
| 42 |
+
"MPSGuardImpl initialized with non-MPS DeviceType: ",
|
| 43 |
+
t);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// returns the type
|
| 47 |
+
c10::DeviceType type() const override {
|
| 48 |
+
return c10::DeviceType::MPS;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
Device exchangeDevice(Device d) const override {
|
| 52 |
+
return Device(c10::DeviceType::MPS, 0);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
Device getDevice() const override {
|
| 56 |
+
return Device(c10::DeviceType::MPS, 0);
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
std::optional<Device> uncheckedGetDevice() const noexcept {
|
| 60 |
+
return Device(c10::DeviceType::MPS, 0);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
void setDevice(Device d) const override {
|
| 64 |
+
TORCH_CHECK(d.is_mps(), "Expected a MPS device, but got ", d);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
void uncheckedSetDevice(Device d) const noexcept override {
|
| 68 |
+
// TODO: Currently setting only device 0
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
Stream getStream(Device d) const override {
|
| 72 |
+
return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
Stream getNewStream(Device, int priority = 0) const override {
|
| 76 |
+
(void)priority;
|
| 77 |
+
return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
Stream getDefaultStream(Device d) const override {
|
| 81 |
+
return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// NB: These do NOT set the current device
|
| 85 |
+
Stream exchangeStream(Stream s) const override {
|
| 86 |
+
return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
|
| 87 |
+
}
|
| 88 |
+
DeviceIndex deviceCount() const noexcept override {
|
| 89 |
+
if (at::hasMPS()) {
|
| 90 |
+
// TODO: extend it for multi-device case
|
| 91 |
+
return 1;
|
| 92 |
+
} else {
|
| 93 |
+
return 0;
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
// Event-related functions
|
| 98 |
+
void createEvent(mpsEvent_t* event, const EventFlag flag) const;
|
| 99 |
+
|
| 100 |
+
void destroyEvent(void* event, const DeviceIndex device_index)
|
| 101 |
+
const noexcept override;
|
| 102 |
+
|
| 103 |
+
void record(
|
| 104 |
+
void** event,
|
| 105 |
+
const Stream& stream,
|
| 106 |
+
const DeviceIndex device_index,
|
| 107 |
+
const EventFlag flag) const override;
|
| 108 |
+
|
| 109 |
+
void block(void* event, const Stream& stream) const override;
|
| 110 |
+
|
| 111 |
+
bool queryEvent(void* event) const override;
|
| 112 |
+
|
| 113 |
+
void synchronizeEvent(void* event) const override;
|
| 114 |
+
|
| 115 |
+
double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
|
| 116 |
+
const override;
|
| 117 |
+
|
| 118 |
+
void synchronizeDevice(const DeviceIndex device_index) const override;
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
/// A variant of OptionalDeviceGuard that is specialized for MPS.
|
| 122 |
+
struct OptionalMPSGuard {
|
| 123 |
+
explicit OptionalMPSGuard() : guard_() {}
|
| 124 |
+
|
| 125 |
+
explicit OptionalMPSGuard(std::optional<Device> device_opt)
|
| 126 |
+
: guard_(device_opt) {}
|
| 127 |
+
|
| 128 |
+
/// Set the current MPS device to the passed device index, if it is not
|
| 129 |
+
/// nullopt
|
| 130 |
+
explicit OptionalMPSGuard(std::optional<DeviceIndex> device_index_opt)
|
| 131 |
+
: guard_(device_index_opt) {}
|
| 132 |
+
|
| 133 |
+
// Copy is not allowed
|
| 134 |
+
OptionalMPSGuard(const OptionalMPSGuard&) = delete;
|
| 135 |
+
OptionalMPSGuard& operator=(const OptionalMPSGuard&) = delete;
|
| 136 |
+
OptionalMPSGuard(OptionalMPSGuard&& other) = delete;
|
| 137 |
+
OptionalMPSGuard& operator=(OptionalMPSGuard&& other) = delete;
|
| 138 |
+
|
| 139 |
+
/// Sets the MPS device to the given device, initializing the guard if it
|
| 140 |
+
/// is not already initialized. Errors if the given device is not a MPS
|
| 141 |
+
/// device.
|
| 142 |
+
void set_device(Device device) {
|
| 143 |
+
guard_.set_device(device);
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
/// Sets the MPS device to the given device, initializing the guard if it is
|
| 147 |
+
/// not already initialized. Errors if the given device is not a MPS device.
|
| 148 |
+
void reset_device(Device device) {
|
| 149 |
+
guard_.reset_device(device);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
/// Sets the MPS device to the given device index, initializing the guard if
|
| 153 |
+
/// it is not already initialized.
|
| 154 |
+
void set_index(DeviceIndex device_index) {
|
| 155 |
+
guard_.set_index(device_index);
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
/// Returns the device that was set immediately prior to initialization of the
|
| 159 |
+
/// guard, or nullopt if the guard is uninitialized.
|
| 160 |
+
std::optional<Device> original_device() const {
|
| 161 |
+
return guard_.original_device();
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
/// Returns the most recent device that was set using this device guard,
|
| 165 |
+
/// either from construction, or via set_device, if the guard is initialized,
|
| 166 |
+
/// or nullopt if the guard is uninitialized.
|
| 167 |
+
std::optional<Device> current_device() const {
|
| 168 |
+
return guard_.current_device();
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
/// Restore the original MPS device, resetting this guard to uninitialized
|
| 172 |
+
/// state.
|
| 173 |
+
void reset() {
|
| 174 |
+
guard_.reset();
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
private:
|
| 178 |
+
c10::impl::InlineOptionalDeviceGuard<MPSGuardImpl> guard_;
|
| 179 |
+
};
|
| 180 |
+
|
| 181 |
+
C10_REGISTER_GUARD_IMPL(MPS, MPSGuardImpl)
|
| 182 |
+
|
| 183 |
+
} // namespace at::mps
|
| 184 |
+
|
| 185 |
+
#else
|
| 186 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 187 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/Generator.h>
|
| 7 |
+
#include <ATen/detail/MPSHooksInterface.h>
|
| 8 |
+
#include <ATen/mps/MPSEvent.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
|
| 11 |
+
namespace at::mps {
|
| 12 |
+
|
| 13 |
+
// The real implementation of MPSHooksInterface
|
| 14 |
+
struct MPSHooks : public at::MPSHooksInterface {
|
| 15 |
+
MPSHooks(at::MPSHooksArgs) {}
|
| 16 |
+
void init() const override;
|
| 17 |
+
|
| 18 |
+
// MPSDevice interface
|
| 19 |
+
bool hasMPS() const override;
|
| 20 |
+
bool isOnMacOSorNewer(unsigned major, unsigned minor) const override;
|
| 21 |
+
|
| 22 |
+
Device getDeviceFromPtr(void* data) const override;
|
| 23 |
+
|
| 24 |
+
// MPSGeneratorImpl interface
|
| 25 |
+
const Generator& getDefaultGenerator(
|
| 26 |
+
DeviceIndex device_index = -1) const override;
|
| 27 |
+
Generator getNewGenerator(DeviceIndex device_index = -1) const override;
|
| 28 |
+
|
| 29 |
+
// MPSStream interface
|
| 30 |
+
void deviceSynchronize() const override;
|
| 31 |
+
void commitStream() const override;
|
| 32 |
+
void* getCommandBuffer() const override;
|
| 33 |
+
void* getDispatchQueue() const override;
|
| 34 |
+
|
| 35 |
+
// MPSAllocator interface
|
| 36 |
+
Allocator* getMPSDeviceAllocator() const override;
|
| 37 |
+
void emptyCache() const override;
|
| 38 |
+
size_t getCurrentAllocatedMemory() const override;
|
| 39 |
+
size_t getDriverAllocatedMemory() const override;
|
| 40 |
+
size_t getRecommendedMaxMemory() const override;
|
| 41 |
+
void setMemoryFraction(double ratio) const override;
|
| 42 |
+
bool isPinnedPtr(const void* data) const override;
|
| 43 |
+
Allocator* getPinnedMemoryAllocator() const override;
|
| 44 |
+
|
| 45 |
+
// MPSProfiler interface
|
| 46 |
+
void profilerStartTrace(const std::string& mode, bool waitUntilCompleted)
|
| 47 |
+
const override;
|
| 48 |
+
void profilerStopTrace() const override;
|
| 49 |
+
|
| 50 |
+
// MPSEvent interface
|
| 51 |
+
uint32_t acquireEvent(bool enable_timing) const override;
|
| 52 |
+
void releaseEvent(uint32_t event_id) const override;
|
| 53 |
+
void recordEvent(uint32_t event_id) const override;
|
| 54 |
+
void waitForEvent(uint32_t event_id) const override;
|
| 55 |
+
void synchronizeEvent(uint32_t event_id) const override;
|
| 56 |
+
bool queryEvent(uint32_t event_id) const override;
|
| 57 |
+
double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id)
|
| 58 |
+
const override;
|
| 59 |
+
|
| 60 |
+
bool isBuilt() const override {
|
| 61 |
+
return true;
|
| 62 |
+
}
|
| 63 |
+
bool isAvailable() const override {
|
| 64 |
+
return hasMPS();
|
| 65 |
+
}
|
| 66 |
+
bool hasPrimaryContext(DeviceIndex device_index) const override {
|
| 67 |
+
// When MPS is available, it is always in use for the one device.
|
| 68 |
+
return true;
|
| 69 |
+
}
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
} // namespace at::mps
|
| 73 |
+
|
| 74 |
+
#else
|
| 75 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 76 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/Tensor.h>
|
| 7 |
+
#include <ATen/mps/MPSAllocatorInterface.h>
|
| 8 |
+
#include <ATen/mps/MPSStream.h>
|
| 9 |
+
|
| 10 |
+
#include <os/log.h>
|
| 11 |
+
#include <os/signpost.h>
|
| 12 |
+
|
| 13 |
+
#include <atomic>
|
| 14 |
+
#include <ctime>
|
| 15 |
+
#include <sstream>
|
| 16 |
+
#include <string>
|
| 17 |
+
#include <unordered_map>
|
| 18 |
+
#include <utility>
|
| 19 |
+
|
| 20 |
+
#ifndef __OBJC__
|
| 21 |
+
typedef void* MTLCaptureManager;
|
| 22 |
+
#endif
|
| 23 |
+
|
| 24 |
+
namespace at::mps {
|
| 25 |
+
|
| 26 |
+
namespace Profiler {
|
| 27 |
+
|
| 28 |
+
struct BaseInfo {
|
| 29 |
+
// profiling info types
|
| 30 |
+
enum class Type {
|
| 31 |
+
GRAPH,
|
| 32 |
+
KERNEL,
|
| 33 |
+
COPY,
|
| 34 |
+
CPU_FALLBACK,
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
+
BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle)
|
| 38 |
+
: type(infoType), profileId(Id), handle(Handle) {}
|
| 39 |
+
virtual ~BaseInfo() = default;
|
| 40 |
+
|
| 41 |
+
// type of profiling info
|
| 42 |
+
Type type;
|
| 43 |
+
// unique profile ID for execution instances of operations or copies
|
| 44 |
+
uint64_t profileId;
|
| 45 |
+
// ID generated by os_signpost
|
| 46 |
+
// since it's possible to use event and interval-based signposts at the
|
| 47 |
+
// same time, we need separate IDs for each.
|
| 48 |
+
os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0;
|
| 49 |
+
// accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime -
|
| 50 |
+
// GPUStartTime")
|
| 51 |
+
std::atomic<double> totalGpuTime{0.0};
|
| 52 |
+
// accumulated Scheduling time in ms (obtained from CompletionHandler's
|
| 53 |
+
// "KernelEndTime - KernelStartTime")
|
| 54 |
+
std::atomic<double> totalSchedulingTime{0.0};
|
| 55 |
+
// indicates if the operation or copy execution has completed
|
| 56 |
+
std::atomic_bool completed{false};
|
| 57 |
+
// handle used to identify the profile info's instance (usually the pointer)
|
| 58 |
+
const uintptr_t handle;
|
| 59 |
+
|
| 60 |
+
virtual const std::string toString(
|
| 61 |
+
double gpuTime = 0,
|
| 62 |
+
double schedulingTime = 0) const;
|
| 63 |
+
// builds a string for a tensor (format: Device:ScalarType[tensor.sizes()])
|
| 64 |
+
static std::string buildTensorString(
|
| 65 |
+
const Tensor& tensor,
|
| 66 |
+
bool includeBufferId = false);
|
| 67 |
+
static uint64_t getTime() {
|
| 68 |
+
return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
|
| 69 |
+
}
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
struct OperationInfo : BaseInfo {
|
| 73 |
+
OperationInfo(
|
| 74 |
+
const void* Handle,
|
| 75 |
+
bool IsGraph,
|
| 76 |
+
uint64_t Id,
|
| 77 |
+
const std::string& StrKey)
|
| 78 |
+
: BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)),
|
| 79 |
+
strKey(StrKey) {}
|
| 80 |
+
|
| 81 |
+
uint64_t runCount = 0;
|
| 82 |
+
std::string strKey;
|
| 83 |
+
|
| 84 |
+
const std::string toString(double gpuTime = 0, double schedulingTime = 0)
|
| 85 |
+
const override;
|
| 86 |
+
|
| 87 |
+
// builds a string for a kernel
|
| 88 |
+
static std::string buildKernelString(
|
| 89 |
+
const std::string& kernelName,
|
| 90 |
+
const TensorList& tensors,
|
| 91 |
+
bool includeBufferId = false) {
|
| 92 |
+
std::stringstream kernelStr;
|
| 93 |
+
kernelStr << kernelName;
|
| 94 |
+
for (const Tensor& tensor : tensors) {
|
| 95 |
+
kernelStr << ':' << BaseInfo::buildTensorString(tensor, includeBufferId);
|
| 96 |
+
}
|
| 97 |
+
return kernelStr.str();
|
| 98 |
+
}
|
| 99 |
+
};
|
| 100 |
+
|
| 101 |
+
struct CpuFbInfo : BaseInfo {
|
| 102 |
+
CpuFbInfo(uint64_t Id, const std::string& OpName)
|
| 103 |
+
: BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {}
|
| 104 |
+
|
| 105 |
+
uint64_t runCount = 0;
|
| 106 |
+
// the current and total overhead of copies in bytes required to convert the
|
| 107 |
+
// Op's input tensors from MPS to CPU and then output from CPU back to MPS
|
| 108 |
+
size_t currentCopyOverhead = 0;
|
| 109 |
+
size_t totalCopyOverhead = 0;
|
| 110 |
+
std::string opName;
|
| 111 |
+
std::string strKey;
|
| 112 |
+
uint64_t startTime = 0;
|
| 113 |
+
|
| 114 |
+
const std::string toString(double gpuTime = 0, double schedulingTime = 0)
|
| 115 |
+
const override;
|
| 116 |
+
|
| 117 |
+
void updateCopyOverhead(const TensorList& tensors) {
|
| 118 |
+
currentCopyOverhead = 0;
|
| 119 |
+
for (const Tensor& tensor : tensors) {
|
| 120 |
+
if (tensor.defined()) {
|
| 121 |
+
currentCopyOverhead += tensor.nbytes();
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
totalCopyOverhead += currentCopyOverhead;
|
| 125 |
+
}
|
| 126 |
+
};
|
| 127 |
+
|
| 128 |
+
struct CopyInfo : BaseInfo {
|
| 129 |
+
enum class Kind {
|
| 130 |
+
MPS_TO_MPS,
|
| 131 |
+
MPS_TO_CPU,
|
| 132 |
+
CPU_TO_MPS,
|
| 133 |
+
};
|
| 134 |
+
|
| 135 |
+
CopyInfo(
|
| 136 |
+
const void* Handle,
|
| 137 |
+
size_t Length,
|
| 138 |
+
uint64_t Id,
|
| 139 |
+
bool IsNonBlocking,
|
| 140 |
+
bool UsesBlitter)
|
| 141 |
+
: BaseInfo(Type::COPY, Id, uintptr_t(Handle)),
|
| 142 |
+
kind(Kind::MPS_TO_MPS),
|
| 143 |
+
length(Length),
|
| 144 |
+
isNonBlocking(IsNonBlocking),
|
| 145 |
+
usesBlitter(UsesBlitter) {}
|
| 146 |
+
|
| 147 |
+
Kind kind;
|
| 148 |
+
size_t length;
|
| 149 |
+
bool isNonBlocking;
|
| 150 |
+
bool usesBlitter;
|
| 151 |
+
std::string srcStrKey;
|
| 152 |
+
std::string dstStrKey;
|
| 153 |
+
// for copies that don't use blitters, we measure CPU time
|
| 154 |
+
uint64_t startTime = 0;
|
| 155 |
+
|
| 156 |
+
const std::string toString(double gpuTime = 0, double schedulingTime = 0)
|
| 157 |
+
const override;
|
| 158 |
+
|
| 159 |
+
static std::string buildTensorString(
|
| 160 |
+
const void* buffer,
|
| 161 |
+
const OptionalTensorRef tensor,
|
| 162 |
+
bool includeBufferId = false);
|
| 163 |
+
|
| 164 |
+
static bool isStorageOnMPS(
|
| 165 |
+
const void* buffer,
|
| 166 |
+
const OptionalTensorRef tensor) {
|
| 167 |
+
if (tensor.has_value()) {
|
| 168 |
+
return tensor->device().type() == at::kMPS;
|
| 169 |
+
}
|
| 170 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer);
|
| 171 |
+
// getUnalignedBufferSize() returns -1 if input buffer is not on MPS device
|
| 172 |
+
return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
static Kind getCopyKind(
|
| 176 |
+
const void* srcBuffer,
|
| 177 |
+
const void* dstBuffer,
|
| 178 |
+
const OptionalTensorRef srcTensor,
|
| 179 |
+
const OptionalTensorRef dstTensor) {
|
| 180 |
+
const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor);
|
| 181 |
+
const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor);
|
| 182 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS);
|
| 183 |
+
if (isSrcOnMPS && !isDstOnMPS) {
|
| 184 |
+
return Kind::MPS_TO_CPU;
|
| 185 |
+
} else if (!isSrcOnMPS && isDstOnMPS) {
|
| 186 |
+
return Kind::CPU_TO_MPS;
|
| 187 |
+
}
|
| 188 |
+
return Kind::MPS_TO_MPS;
|
| 189 |
+
}
|
| 190 |
+
};
|
| 191 |
+
|
| 192 |
+
struct CopyStat : CopyInfo {
|
| 193 |
+
explicit CopyStat(std::string CopyKindStr)
|
| 194 |
+
: CopyInfo(nullptr, 0, 0, false, false),
|
| 195 |
+
kindStr(std::move(CopyKindStr)) {}
|
| 196 |
+
// total number of copies
|
| 197 |
+
size_t totalCount = 0;
|
| 198 |
+
// number of Scalar copies (i.e., less than sizeof(int64))
|
| 199 |
+
size_t scalarsCount = 0;
|
| 200 |
+
// number of blocking copies (i.e., require syncing to GPU)
|
| 201 |
+
size_t blockingCount = 0;
|
| 202 |
+
// number of copies that used memcpy(), instead of Metal Blit Encoder
|
| 203 |
+
size_t memcpyCount = 0;
|
| 204 |
+
// accumulated GPU time in ms for the scalar copies
|
| 205 |
+
std::atomic<double> scalarsGpuTime{0.0};
|
| 206 |
+
// copy kind in string type
|
| 207 |
+
std::string kindStr;
|
| 208 |
+
};
|
| 209 |
+
|
| 210 |
+
class MPSProfiler {
|
| 211 |
+
public:
|
| 212 |
+
// lower 16 bits used for profiler options
|
| 213 |
+
enum ProfileOptions : uint32_t {
|
| 214 |
+
OPTIONS_NONE = 0,
|
| 215 |
+
// ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK,
|
| 216 |
+
// etc.) (used for convenience to not compute bit flags by OR-ing manually)
|
| 217 |
+
// trace all signpost types using events
|
| 218 |
+
ALL_SIGNPOST_EVENTS = (1 << 0),
|
| 219 |
+
// trace all signpost types using intervals
|
| 220 |
+
ALL_SIGNPOST_INTERVALS = (1 << 1),
|
| 221 |
+
// always wait for command buffer to finish executing after each commit
|
| 222 |
+
WAIT_UNTIL_COMPLETED = (1 << 2),
|
| 223 |
+
// for interval-based signposts, include the scheduling portion of
|
| 224 |
+
// Graph/Kernel/Copy executions as well.
|
| 225 |
+
// if flag is disable, only "GPU run time" is included in interval,
|
| 226 |
+
// and not schedule time.
|
| 227 |
+
INCLUDE_SCHEDULE_INTERVAL = (1 << 3),
|
| 228 |
+
|
| 229 |
+
// use these if you need to trace signposts types individually (rarely
|
| 230 |
+
// required) trace signpost using intervals
|
| 231 |
+
USE_INTERVALS = (1 << 4),
|
| 232 |
+
// trace signpost by emitting events
|
| 233 |
+
USE_EVENTS = (1 << 5),
|
| 234 |
+
// used for sanity check (Change this when new option added)
|
| 235 |
+
OPTIONS_COUNT = (USE_EVENTS << 1) - 1,
|
| 236 |
+
};
|
| 237 |
+
|
| 238 |
+
// when adding new types, #define the type string in MPSProfiler.mm as well.
|
| 239 |
+
// upper 16 bits used for event types
|
| 240 |
+
enum SignpostTypes : uint32_t {
|
| 241 |
+
SIGNPOST_NONE = 0,
|
| 242 |
+
// trace signposts for PyTorch operation executions
|
| 243 |
+
RUN_OPERATION = (1 << 16),
|
| 244 |
+
// trace signposts for blitter copies
|
| 245 |
+
BLIT_COPY = (1 << 17),
|
| 246 |
+
// trace signposts for ops that fall back on CPU
|
| 247 |
+
CPU_FALLBACK = (1 << 18),
|
| 248 |
+
// used for sanity check (Change this when new type added)
|
| 249 |
+
SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1,
|
| 250 |
+
};
|
| 251 |
+
|
| 252 |
+
enum LogOptions : uint32_t {
|
| 253 |
+
LOG_NONE = 0,
|
| 254 |
+
|
| 255 |
+
// Info logging options during execution
|
| 256 |
+
// -------------------------------------
|
| 257 |
+
// prints operation info (id/key/run_count) during execution
|
| 258 |
+
OPERATION_INFO = (1 << 0),
|
| 259 |
+
// prints copy info (src/dst tensors/buffers, size, etc.) during execution
|
| 260 |
+
COPY_INFO = (1 << 1),
|
| 261 |
+
// prints CPU Fallback info (id/runCount/opName/copyOverhead) during
|
| 262 |
+
// execution
|
| 263 |
+
CPU_FALLBACK_INFO = (1 << 2),
|
| 264 |
+
|
| 265 |
+
// Profiling Statistics logging options when process terminates
|
| 266 |
+
// ------------------------------------------------------------
|
| 267 |
+
// prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before
|
| 268 |
+
// process terminates this is convenient to not combine following stats bit
|
| 269 |
+
// flags manually
|
| 270 |
+
ALL_STATS = (1 << 3),
|
| 271 |
+
// prints operation stats (GPU times, run count, etc.) before process
|
| 272 |
+
// terminates
|
| 273 |
+
OPERATION_STATS = (1 << 4),
|
| 274 |
+
// prints copies stats (GPU times, copy kinds, sizes, etc.) before process
|
| 275 |
+
// terminates
|
| 276 |
+
COPY_STATS = (1 << 5),
|
| 277 |
+
// prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies
|
| 278 |
+
// for tensors, etc.) before process terminates
|
| 279 |
+
CPU_FALLBACK_STATS = (1 << 6),
|
| 280 |
+
|
| 281 |
+
// Metadata format options when logging the info
|
| 282 |
+
// ---------------------------------------------
|
| 283 |
+
// if enabled, includes GPU run time in metadata (i.e.,
|
| 284 |
+
// GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324
|
| 285 |
+
// ms])
|
| 286 |
+
INCLUDE_GPU_TIME = (1 << 7),
|
| 287 |
+
// if enabled, includes GPU scheduling time in metadata separately
|
| 288 |
+
// (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers)
|
| 289 |
+
// e.g., [GPU=0.324 ms, KRNL=0.036 ms]
|
| 290 |
+
INCLUDE_KERNEL_TIME = (1 << 8),
|
| 291 |
+
// if enabled, includes the unique buffer ID in metadata for the storage
|
| 292 |
+
// of a tensor that was allocated on MPSAllocator. This is useful (along
|
| 293 |
+
// with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are
|
| 294 |
+
// involved with various operations.
|
| 295 |
+
INCLUDE_BUFFER_ID = (1 << 9),
|
| 296 |
+
|
| 297 |
+
// used for sanity check (Change this when new option added)
|
| 298 |
+
LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1,
|
| 299 |
+
};
|
| 300 |
+
|
| 301 |
+
explicit MPSProfiler();
|
| 302 |
+
~MPSProfiler();
|
| 303 |
+
|
| 304 |
+
// the handle is either "MPSGraph*" or "id<MTLComputePipelineState>" for Metal
|
| 305 |
+
// Kernels the beginProfile*() functions return a profileId which is unique
|
| 306 |
+
// per graph/kernel/copy
|
| 307 |
+
uint64_t beginProfileKernel(
|
| 308 |
+
const void* handle,
|
| 309 |
+
const std::string& strKey,
|
| 310 |
+
bool isGraph);
|
| 311 |
+
uint64_t beginProfileKernel(
|
| 312 |
+
const void* handle,
|
| 313 |
+
const std::string& kernelName,
|
| 314 |
+
const TensorList& tensors);
|
| 315 |
+
uint64_t beginProfileCopy(
|
| 316 |
+
const void* srcBuffer,
|
| 317 |
+
const void* dstBuffer,
|
| 318 |
+
const OptionalTensorRef srcTensor,
|
| 319 |
+
const OptionalTensorRef dstTensor,
|
| 320 |
+
size_t length,
|
| 321 |
+
bool isNonBlocking,
|
| 322 |
+
bool usesBlitter = true);
|
| 323 |
+
uint64_t beginProfileCPUFallback(
|
| 324 |
+
const std::string& opName,
|
| 325 |
+
const TensorList& tensors);
|
| 326 |
+
void beginProfileGPUInterval(const void* handle);
|
| 327 |
+
|
| 328 |
+
void endProfileCopy(uint64_t profileId, SyncType syncType);
|
| 329 |
+
void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE);
|
| 330 |
+
void endProfileCPUFallback(const std::string& opName);
|
| 331 |
+
|
| 332 |
+
// these are used to hook into Python bindings for torch.mps.profiler module.
|
| 333 |
+
// this enables generating OS Signpost traces from MPSProfiler on-demand
|
| 334 |
+
// during runtime (instead of environment variables).
|
| 335 |
+
// The "mode" could be either "interval", "event", or both "interval,event"
|
| 336 |
+
// for interval-based and/or event-based signpost tracing.
|
| 337 |
+
void StartTrace(const std::string& mode, bool waitUntilCompleted);
|
| 338 |
+
void StopTrace();
|
| 339 |
+
|
| 340 |
+
// Abstractions for GPU trace capturing
|
| 341 |
+
bool isCaptureEnabled() const;
|
| 342 |
+
bool isCapturing() const;
|
| 343 |
+
void startCapture(const std::string& name, MPSStream* stream = nullptr);
|
| 344 |
+
void stopCapture(MPSStream* stream = nullptr);
|
| 345 |
+
|
| 346 |
+
// convenience functions to indicate whether signpost tracing or
|
| 347 |
+
// logging are enabled for the SignpostTypes
|
| 348 |
+
bool isOperationProfilingEnabled() const {
|
| 349 |
+
return (m_signpost_types & SignpostTypes::RUN_OPERATION) ||
|
| 350 |
+
(m_log_options &
|
| 351 |
+
(LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS));
|
| 352 |
+
}
|
| 353 |
+
bool isCopyProfilingEnabled() const {
|
| 354 |
+
return (m_signpost_types & SignpostTypes::BLIT_COPY) ||
|
| 355 |
+
(m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS));
|
| 356 |
+
}
|
| 357 |
+
bool isCPUFallbackProfilingEnabled() const {
|
| 358 |
+
return (m_signpost_types & SignpostTypes::CPU_FALLBACK) ||
|
| 359 |
+
(m_log_options &
|
| 360 |
+
(LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS));
|
| 361 |
+
}
|
| 362 |
+
bool isSignpostTracingEnabled() const {
|
| 363 |
+
return (m_signpost_types != SignpostTypes::SIGNPOST_NONE);
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
private:
|
| 367 |
+
// indicates what type of signpost types are enabled and traced by MPS
|
| 368 |
+
// profiler.
|
| 369 |
+
uint32_t m_signpost_types = 0;
|
| 370 |
+
uint32_t m_profile_options = 0;
|
| 371 |
+
uint32_t m_log_options = 0;
|
| 372 |
+
uint64_t m_kernel_counter = 0;
|
| 373 |
+
uint64_t m_graph_counter = 0;
|
| 374 |
+
uint64_t m_cpu_fb_counter = 0;
|
| 375 |
+
uint64_t m_copy_counter = 0;
|
| 376 |
+
// technically, it's possible to trace both events and intervals at the same
|
| 377 |
+
// time so we use separate os_log categories for them
|
| 378 |
+
os_log_t m_os_log_events;
|
| 379 |
+
os_log_t m_os_log_intervals;
|
| 380 |
+
// stats logging could run either from destructor or signal handler
|
| 381 |
+
// so this is used to check if logging has already started.
|
| 382 |
+
std::atomic_bool hasLoggedStats{false};
|
| 383 |
+
// indicates there are pending completionHandler callbacks that haven't been
|
| 384 |
+
// called yet.
|
| 385 |
+
std::atomic_bool hasPendingCompletionHandlers{false};
|
| 386 |
+
// used to capture sigint signal to log profiling stats
|
| 387 |
+
static struct sigaction currentSigint, previousSigint;
|
| 388 |
+
|
| 389 |
+
// We use the following lists for two reasons:
|
| 390 |
+
// 1- for interval-based signposts the "begin" point won't be in same function
|
| 391 |
+
// as the "end" point where we need to be able to retrieve signpost's info
|
| 392 |
+
// 2- if Operations info need to be logged when process ends using
|
| 393 |
+
// LogOptions::OPERATION_INFO.
|
| 394 |
+
|
| 395 |
+
// the pointer key for this map is either "MPSGraph*" or
|
| 396 |
+
// "id<MTLComputePipelineState>" for Metal Kernels this list is retained and
|
| 397 |
+
// could be logged along with aggregate profiling numbers when the process
|
| 398 |
+
// ends.
|
| 399 |
+
std::unordered_map<uintptr_t, std::unique_ptr<OperationInfo>>
|
| 400 |
+
m_op_info_list{};
|
| 401 |
+
// the string key for this map is the op name that we fall back to execute on
|
| 402 |
+
// CPU this list is retained and could be logged along with aggregate
|
| 403 |
+
// profiling numbers when the process ends.
|
| 404 |
+
std::unordered_map<std::string, std::unique_ptr<CpuFbInfo>>
|
| 405 |
+
m_cpu_fb_info_list{};
|
| 406 |
+
// this list contains the info for copies, and its key is the unique profileId
|
| 407 |
+
// which is generated from m_copy_counter
|
| 408 |
+
// The copyInfo list is not retained.
|
| 409 |
+
std::unordered_map<uint64_t, std::unique_ptr<CopyInfo>> m_copy_info_list{};
|
| 410 |
+
// a short list that contains copy stats
|
| 411 |
+
std::unordered_map<CopyInfo::Kind, std::unique_ptr<CopyStat>>
|
| 412 |
+
m_copy_stat_list{};
|
| 413 |
+
|
| 414 |
+
mutable MTLCaptureManager* captureManager = nil;
|
| 415 |
+
unsigned captureCount = 0;
|
| 416 |
+
|
| 417 |
+
void initialize();
|
| 418 |
+
void beginProfileExecution(BaseInfo& info, bool cpuExecution = false);
|
| 419 |
+
void endProfileExecution(
|
| 420 |
+
BaseInfo& info,
|
| 421 |
+
os_signpost_id_t event_signpost_id,
|
| 422 |
+
os_signpost_id_t interval_signpost_id,
|
| 423 |
+
double gpuTime,
|
| 424 |
+
double schedulingTime);
|
| 425 |
+
void addProfilerScheduledHandler(BaseInfo& info);
|
| 426 |
+
void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType);
|
| 427 |
+
void emitSignpostEvent(
|
| 428 |
+
SignpostTypes signpost_type,
|
| 429 |
+
os_signpost_id_t signpost_id,
|
| 430 |
+
const std::string& msg) const;
|
| 431 |
+
void beginSignpostInterval(
|
| 432 |
+
SignpostTypes signpost_type,
|
| 433 |
+
os_signpost_id_t signpost_id,
|
| 434 |
+
const std::string& msg) const;
|
| 435 |
+
void endSignpostInterval(
|
| 436 |
+
SignpostTypes signpost_type,
|
| 437 |
+
os_signpost_id_t signpost_id) const;
|
| 438 |
+
|
| 439 |
+
void updateCopyStats(
|
| 440 |
+
const CopyInfo& copyInfo,
|
| 441 |
+
double gpuTime,
|
| 442 |
+
double schedulingTime);
|
| 443 |
+
// returns true if logging the profiling info "during the execution" is
|
| 444 |
+
// enabled
|
| 445 |
+
bool isProfileInfoLoggingEnabled(
|
| 446 |
+
BaseInfo::Type infoType,
|
| 447 |
+
bool isExecutionEnded);
|
| 448 |
+
// logs all the profiling stats that are enabled
|
| 449 |
+
void logProfilingStats();
|
| 450 |
+
// logs kernel profiling stats when the process ends.
|
| 451 |
+
void logOperationsProfilingStats(std::FILE* f) const;
|
| 452 |
+
// logs CPU Fallback profiling stats when the process ends.
|
| 453 |
+
void logCPUFallbackProfilingStats(std::FILE* f) const;
|
| 454 |
+
// logs copy profiling stats when the process ends.
|
| 455 |
+
void logCopyProfilingStats(std::FILE* f) const;
|
| 456 |
+
|
| 457 |
+
os_signpost_id_t generateSignpostId(
|
| 458 |
+
os_signpost_type_t signpostType,
|
| 459 |
+
const void* ptr = nullptr);
|
| 460 |
+
static SignpostTypes getSignpostType(BaseInfo::Type infoType);
|
| 461 |
+
static void handleIntSignal(int signal);
|
| 462 |
+
};
|
| 463 |
+
|
| 464 |
+
} // namespace Profiler
|
| 465 |
+
|
| 466 |
+
Profiler::MPSProfiler& getMPSProfiler();
|
| 467 |
+
|
| 468 |
+
} // namespace at::mps
|
| 469 |
+
|
| 470 |
+
#else
|
| 471 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 472 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Copyright © 2022 Apple Inc.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <cstdint>
|
| 7 |
+
#include <utility>
|
| 8 |
+
|
| 9 |
+
#include <ATen/mps/MPSDevice.h>
|
| 10 |
+
#include <c10/core/DeviceGuard.h>
|
| 11 |
+
#include <c10/core/Stream.h>
|
| 12 |
+
#include <c10/util/Exception.h>
|
| 13 |
+
|
| 14 |
+
#ifdef __OBJC__
|
| 15 |
+
#include <Foundation/Foundation.h>
|
| 16 |
+
#include <Metal/Metal.h>
|
| 17 |
+
#include <MetalPerformanceShaders/MetalPerformanceShaders.h>
|
| 18 |
+
#include <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
|
| 19 |
+
typedef MPSCommandBuffer* MPSCommandBuffer_t;
|
| 20 |
+
typedef id<MTLCommandQueue> MTLCommandQueue_t;
|
| 21 |
+
typedef id<MTLComputeCommandEncoder> MTLComputeCommandEncoder_t;
|
| 22 |
+
typedef id<MTLSharedEvent> MTLSharedEvent_t;
|
| 23 |
+
typedef id<MTLDevice> MTLDevice_t;
|
| 24 |
+
typedef id<MTLBuffer> MTLBuffer_t;
|
| 25 |
+
#else
|
| 26 |
+
#include <dispatch/dispatch.h>
|
| 27 |
+
typedef void* MPSCommandBuffer_t;
|
| 28 |
+
typedef void* MPSGraph;
|
| 29 |
+
typedef void* MPSGraphExecutionDescriptor;
|
| 30 |
+
typedef void* MPSGraphCompilationDescriptor;
|
| 31 |
+
typedef void* MTLCommandQueue_t;
|
| 32 |
+
typedef void* MTLComputeCommandEncoder_t;
|
| 33 |
+
typedef void* MTLSharedEvent_t;
|
| 34 |
+
typedef void* MTLDevice_t;
|
| 35 |
+
typedef void* MTLBuffer_t;
|
| 36 |
+
typedef void* MTLCommandBufferHandler;
|
| 37 |
+
typedef void* NSDictionary;
|
| 38 |
+
#define nil NULL
|
| 39 |
+
#endif
|
| 40 |
+
|
| 41 |
+
namespace at::mps {
|
| 42 |
+
|
| 43 |
+
//-----------------------------------------------------------------
|
| 44 |
+
// MPSStream
|
| 45 |
+
//-----------------------------------------------------------------
|
| 46 |
+
|
| 47 |
+
enum class SyncType {
|
| 48 |
+
NONE, // no commit to command buffer
|
| 49 |
+
COMMIT, // commit and flush the command buffer
|
| 50 |
+
COMMIT_AND_WAIT, // flush and wait for command buffer execution to finish
|
| 51 |
+
COMMIT_AND_CONTINUE, // commit and continue with a new underlying command buffer
|
| 52 |
+
COMMIT_ADAPTIVE, // commit adaptively based on available memory
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
class TORCH_API MPSStream {
|
| 56 |
+
public:
|
| 57 |
+
enum Unchecked { UNCHECKED };
|
| 58 |
+
|
| 59 |
+
/// Construct a MPSStream from a Stream. This construction is checked,
|
| 60 |
+
/// and will raise an error if the Stream is not, in fact, a MPS stream.
|
| 61 |
+
explicit MPSStream(Stream stream);
|
| 62 |
+
|
| 63 |
+
~MPSStream();
|
| 64 |
+
|
| 65 |
+
MTLCommandQueue_t commandQueue() const {
|
| 66 |
+
return _commandQueue;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
dispatch_queue_t queue() const {
|
| 70 |
+
return _serialQueue;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
MPSCommandBuffer_t commandBuffer();
|
| 74 |
+
MTLComputeCommandEncoder_t commandEncoder();
|
| 75 |
+
void endKernelCoalescing();
|
| 76 |
+
void synchronize(SyncType syncType);
|
| 77 |
+
void fill(MTLBuffer_t buffer, uint8_t value, size_t length, size_t offset, SyncType syncType = SyncType::NONE);
|
| 78 |
+
void copy(MTLBuffer_t srcBuffer,
|
| 79 |
+
MTLBuffer_t dstBuffer,
|
| 80 |
+
size_t length,
|
| 81 |
+
size_t srcOffset,
|
| 82 |
+
size_t dstOffset,
|
| 83 |
+
uint64_t profileId,
|
| 84 |
+
SyncType syncType = SyncType::NONE);
|
| 85 |
+
void copy_and_sync(MTLBuffer_t srcBuffer,
|
| 86 |
+
MTLBuffer_t dstBuffer,
|
| 87 |
+
size_t length,
|
| 88 |
+
size_t srcOffset,
|
| 89 |
+
size_t dstOffset,
|
| 90 |
+
bool non_blocking,
|
| 91 |
+
uint64_t profileId);
|
| 92 |
+
void executeMPSGraph(MPSGraph* mpsGraph,
|
| 93 |
+
NSDictionary* feeds,
|
| 94 |
+
NSDictionary* results,
|
| 95 |
+
SyncType syncType = SyncType::NONE);
|
| 96 |
+
void addCompletedHandler(MTLCommandBufferHandler block);
|
| 97 |
+
|
| 98 |
+
/// Get the MPS device index that this stream is associated with.
|
| 99 |
+
c10::DeviceIndex device_index() const {
|
| 100 |
+
return _stream.device_index();
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
MTLCommandQueue_t stream() const {
|
| 104 |
+
return _commandQueue;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
MTLDevice_t device() const;
|
| 108 |
+
|
| 109 |
+
/// Explicit conversion to Stream.
|
| 110 |
+
Stream unwrap() const {
|
| 111 |
+
return _stream;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
MTLBuffer_t getErrorBuffer();
|
| 115 |
+
void checkLastError();
|
| 116 |
+
|
| 117 |
+
private:
|
| 118 |
+
Stream _stream;
|
| 119 |
+
MTLCommandQueue_t _commandQueue = nil;
|
| 120 |
+
MPSCommandBuffer_t _commandBuffer = nil;
|
| 121 |
+
MPSCommandBuffer_t _prevCommandBuffer = nil;
|
| 122 |
+
MTLComputeCommandEncoder_t _commandEncoder = nil;
|
| 123 |
+
MPSGraphExecutionDescriptor* _executionDescriptor = nil;
|
| 124 |
+
MPSGraphCompilationDescriptor* _compilationDescriptor = nil;
|
| 125 |
+
dispatch_queue_t _serialQueue = nullptr;
|
| 126 |
+
// CommitAndContinue is enabled by default
|
| 127 |
+
bool _enableCommitAndContinue = true;
|
| 128 |
+
// Buffer that contains last raised error
|
| 129 |
+
MTLBuffer_t _errorBuffer = nil;
|
| 130 |
+
|
| 131 |
+
// use synchronize() to access any of these commit functions outside MPSStream
|
| 132 |
+
void commit();
|
| 133 |
+
void commitAndWait();
|
| 134 |
+
void commitAndContinue();
|
| 135 |
+
void flush();
|
| 136 |
+
};
|
| 137 |
+
|
| 138 |
+
/**
|
| 139 |
+
* Get the current MPS stream
|
| 140 |
+
*/
|
| 141 |
+
TORCH_API MPSStream* getCurrentMPSStream();
|
| 142 |
+
|
| 143 |
+
/**
|
| 144 |
+
* Get the default MPS stream
|
| 145 |
+
*/
|
| 146 |
+
TORCH_API MPSStream* getDefaultMPSStream();
|
| 147 |
+
|
| 148 |
+
//-----------------------------------------------------------------
|
| 149 |
+
// MPSStreamImpl
|
| 150 |
+
//-----------------------------------------------------------------
|
| 151 |
+
|
| 152 |
+
class TORCH_API MPSStreamImpl {
|
| 153 |
+
public:
|
| 154 |
+
/**
|
| 155 |
+
* Gets single instance of the MPSStream.
|
| 156 |
+
*/
|
| 157 |
+
static MPSStream* getInstance();
|
| 158 |
+
|
| 159 |
+
private:
|
| 160 |
+
static MPSStream* _stream;
|
| 161 |
+
MPSStreamImpl();
|
| 162 |
+
};
|
| 163 |
+
|
| 164 |
+
#ifdef __OBJC__
|
| 165 |
+
void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)());
|
| 166 |
+
#endif
|
| 167 |
+
} // namespace at::mps
|
| 168 |
+
|
| 169 |
+
#else
|
| 170 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 171 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
#include <ATen/native/Gelu.h>
|
| 6 |
+
#include <c10/util/Exception.h>
|
| 7 |
+
|
| 8 |
+
namespace c10 {
|
| 9 |
+
class Scalar;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
namespace at {
|
| 13 |
+
struct TensorIterator;
|
| 14 |
+
struct TensorIteratorBase;
|
| 15 |
+
class TensorBase;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
namespace at::native {
|
| 19 |
+
|
| 20 |
+
using structured_activation_fn = void (*)(TensorIteratorBase&);
|
| 21 |
+
using structured_activation_backward_fn = void (*)(TensorIteratorBase&);
|
| 22 |
+
|
| 23 |
+
using activation_fn = void (*)(TensorIterator&);
|
| 24 |
+
using activation_backward_fn = void (*)(TensorIterator&);
|
| 25 |
+
using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
|
| 26 |
+
using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
|
| 27 |
+
using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
|
| 28 |
+
using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&);
|
| 29 |
+
using hardsigmoid_fn = void(*)(TensorIteratorBase&);
|
| 30 |
+
using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&);
|
| 31 |
+
using hardswish_fn = void(*)(TensorIterator&);
|
| 32 |
+
using hardswish_backward_fn = void(*)(TensorIterator&);
|
| 33 |
+
using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
|
| 34 |
+
using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
|
| 35 |
+
using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
|
| 36 |
+
using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&);
|
| 37 |
+
using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool);
|
| 38 |
+
using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
|
| 39 |
+
using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
|
| 40 |
+
using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&);
|
| 41 |
+
using gelu_fn = void (*)(TensorIteratorBase&, GeluType);
|
| 42 |
+
using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType);
|
| 43 |
+
using glu_jvp_fn = void (*)(TensorIteratorBase&);
|
| 44 |
+
|
| 45 |
+
DECLARE_DISPATCH(elu_fn, elu_stub)
|
| 46 |
+
DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub)
|
| 47 |
+
DECLARE_DISPATCH(softplus_fn, softplus_stub)
|
| 48 |
+
DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub)
|
| 49 |
+
DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub)
|
| 50 |
+
DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub)
|
| 51 |
+
DECLARE_DISPATCH(threshold_fn, threshold_stub)
|
| 52 |
+
DECLARE_DISPATCH(gelu_fn, GeluKernel)
|
| 53 |
+
DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel)
|
| 54 |
+
DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub)
|
| 55 |
+
DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub)
|
| 56 |
+
DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub)
|
| 57 |
+
DECLARE_DISPATCH(hardswish_fn, hardswish_stub)
|
| 58 |
+
DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub)
|
| 59 |
+
DECLARE_DISPATCH(shrink_fn, hardshrink_stub)
|
| 60 |
+
DECLARE_DISPATCH(softshrink_fn, softshrink_stub)
|
| 61 |
+
DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub)
|
| 62 |
+
DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub)
|
| 63 |
+
DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub)
|
| 64 |
+
DECLARE_DISPATCH(structured_activation_fn, glu_stub)
|
| 65 |
+
DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub)
|
| 66 |
+
DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub)
|
| 67 |
+
DECLARE_DISPATCH(structured_activation_fn, silu_stub)
|
| 68 |
+
DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub)
|
| 69 |
+
DECLARE_DISPATCH(structured_activation_fn, mish_stub)
|
| 70 |
+
DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub)
|
| 71 |
+
DECLARE_DISPATCH(activation_fn, prelu_stub)
|
| 72 |
+
DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub)
|
| 73 |
+
|
| 74 |
+
} // namespace at::native
|
| 75 |
+
|
| 76 |
+
#else
|
| 77 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 78 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <ATen/native/DispatchStub.h>
|
| 6 |
+
#include <c10/util/ArrayRef.h>
|
| 7 |
+
#include <c10/util/irange.h>
|
| 8 |
+
#include <cmath>
|
| 9 |
+
|
| 10 |
+
namespace at::native {
|
| 11 |
+
|
| 12 |
+
using adaptive_avg_pooling2d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
|
| 13 |
+
using adaptive_avg_pooling2d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
|
| 14 |
+
DECLARE_DISPATCH(adaptive_avg_pooling2d_fn, adaptive_avg_pool2d_kernel)
|
| 15 |
+
DECLARE_DISPATCH(adaptive_avg_pooling2d_backward_fn, adaptive_avg_pool2d_backward_kernel)
|
| 16 |
+
|
| 17 |
+
using adaptive_max_pooling2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
|
| 18 |
+
using adaptive_max_pooling2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
|
| 19 |
+
DECLARE_DISPATCH(adaptive_max_pooling2d_fn, adaptive_max_pool2d_kernel)
|
| 20 |
+
DECLARE_DISPATCH(adaptive_max_pooling2d_backward_fn, adaptive_max_pool2d_backward_kernel)
|
| 21 |
+
|
| 22 |
+
using adaptive_avg_pooling3d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
|
| 23 |
+
using adaptive_avg_pooling3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
|
| 24 |
+
DECLARE_DISPATCH(adaptive_avg_pooling3d_fn, adaptive_avg_pool3d_kernel)
|
| 25 |
+
DECLARE_DISPATCH(adaptive_avg_pooling3d_backward_fn, adaptive_avg_pool3d_backward_kernel)
|
| 26 |
+
|
| 27 |
+
using adaptive_max_pooling3d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
|
| 28 |
+
using adaptive_max_pooling3d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
|
| 29 |
+
DECLARE_DISPATCH(adaptive_max_pooling3d_fn, adaptive_max_pool3d_kernel)
|
| 30 |
+
DECLARE_DISPATCH(adaptive_max_pooling3d_backward_fn, adaptive_max_pool3d_backward_kernel)
|
| 31 |
+
|
| 32 |
+
inline int64_t start_index(int64_t a, int64_t b, int64_t c) {
|
| 33 |
+
return (a / b) * c + ((a % b) * c) / b;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
inline int64_t end_index(int64_t a, int64_t b, int64_t c) {
|
| 37 |
+
return 1 + ((a + 1) * c - 1) / b;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) {
|
| 41 |
+
int64_t ndim = gradOutput_.ndimension();
|
| 42 |
+
for (const auto i : c10::irange(1, ndim)) {
|
| 43 |
+
TORCH_CHECK(gradOutput_.size(i) > 0,
|
| 44 |
+
arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, "
|
| 45 |
+
"but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i,
|
| 46 |
+
" being empty");
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
} // namespace at::native
|
| 51 |
+
|
| 52 |
+
#else
|
| 53 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 54 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/AmpKernels.h
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
#include <ATen/core/ATen_fwd.h>
|
| 6 |
+
|
| 7 |
+
namespace at {
|
| 8 |
+
class Tensor;
|
| 9 |
+
|
| 10 |
+
namespace native {
|
| 11 |
+
|
| 12 |
+
using _amp_foreach_non_finite_check_and_unscale_cpu__fn = void (*)(
|
| 13 |
+
TensorList,
|
| 14 |
+
Tensor&,
|
| 15 |
+
const Tensor&);
|
| 16 |
+
|
| 17 |
+
using _amp_update_scale_cpu__fn = Tensor& (*)(
|
| 18 |
+
Tensor&,
|
| 19 |
+
Tensor&,
|
| 20 |
+
const Tensor&,
|
| 21 |
+
double,
|
| 22 |
+
double,
|
| 23 |
+
int64_t);
|
| 24 |
+
|
| 25 |
+
DECLARE_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu__fn, _amp_foreach_non_finite_check_and_unscale_cpu_stub)
|
| 26 |
+
DECLARE_DISPATCH(_amp_update_scale_cpu__fn, _amp_update_scale_cpu_stub)
|
| 27 |
+
|
| 28 |
+
} // namespace native
|
| 29 |
+
} // namespace at
|
| 30 |
+
|
| 31 |
+
#else
|
| 32 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 33 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <optional>
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <ATen/Config.h>
|
| 7 |
+
#include <ATen/native/DispatchStub.h>
|
| 8 |
+
|
| 9 |
+
// Forward declare TI
|
| 10 |
+
namespace at {
|
| 11 |
+
class Tensor;
|
| 12 |
+
struct TensorIterator;
|
| 13 |
+
|
| 14 |
+
namespace native {
|
| 15 |
+
enum class TransposeType;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
namespace at::native {
|
| 21 |
+
|
| 22 |
+
enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
|
| 23 |
+
|
| 24 |
+
#if AT_BUILD_WITH_LAPACK()
|
| 25 |
+
// Define per-batch functions to be used in the implementation of batched
|
| 26 |
+
// linear algebra operations
|
| 27 |
+
|
| 28 |
+
template <class scalar_t>
|
| 29 |
+
void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
|
| 30 |
+
|
| 31 |
+
template <class scalar_t>
|
| 32 |
+
void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
|
| 33 |
+
|
| 34 |
+
template <class scalar_t, class value_t=scalar_t>
|
| 35 |
+
void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
|
| 36 |
+
|
| 37 |
+
template <class scalar_t>
|
| 38 |
+
void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
|
| 39 |
+
|
| 40 |
+
template <class scalar_t>
|
| 41 |
+
void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
|
| 42 |
+
|
| 43 |
+
template <class scalar_t>
|
| 44 |
+
void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
|
| 45 |
+
|
| 46 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 47 |
+
void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
|
| 48 |
+
|
| 49 |
+
template <class scalar_t>
|
| 50 |
+
void lapackGels(char trans, int m, int n, int nrhs,
|
| 51 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 52 |
+
scalar_t *work, int lwork, int *info);
|
| 53 |
+
|
| 54 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 55 |
+
void lapackGelsd(int m, int n, int nrhs,
|
| 56 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 57 |
+
value_t *s, value_t rcond, int *rank,
|
| 58 |
+
scalar_t* work, int lwork,
|
| 59 |
+
value_t *rwork, int* iwork, int *info);
|
| 60 |
+
|
| 61 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 62 |
+
void lapackGelsy(int m, int n, int nrhs,
|
| 63 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 64 |
+
int *jpvt, value_t rcond, int *rank,
|
| 65 |
+
scalar_t *work, int lwork, value_t* rwork, int *info);
|
| 66 |
+
|
| 67 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 68 |
+
void lapackGelss(int m, int n, int nrhs,
|
| 69 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 70 |
+
value_t *s, value_t rcond, int *rank,
|
| 71 |
+
scalar_t *work, int lwork,
|
| 72 |
+
value_t *rwork, int *info);
|
| 73 |
+
|
| 74 |
+
template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
|
| 75 |
+
struct lapackLstsq_impl;
|
| 76 |
+
|
| 77 |
+
template <class scalar_t, class value_t>
|
| 78 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
|
| 79 |
+
static void call(
|
| 80 |
+
char trans, int m, int n, int nrhs,
|
| 81 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 82 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 83 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 84 |
+
value_t *s, // Gelss flavor
|
| 85 |
+
int *iwork // Gelsd flavor
|
| 86 |
+
) {
|
| 87 |
+
lapackGels<scalar_t>(
|
| 88 |
+
trans, m, n, nrhs,
|
| 89 |
+
a, lda, b, ldb,
|
| 90 |
+
work, lwork, info);
|
| 91 |
+
}
|
| 92 |
+
};
|
| 93 |
+
|
| 94 |
+
template <class scalar_t, class value_t>
|
| 95 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
|
| 96 |
+
static void call(
|
| 97 |
+
char trans, int m, int n, int nrhs,
|
| 98 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 99 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 100 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 101 |
+
value_t *s, // Gelss flavor
|
| 102 |
+
int *iwork // Gelsd flavor
|
| 103 |
+
) {
|
| 104 |
+
lapackGelsy<scalar_t, value_t>(
|
| 105 |
+
m, n, nrhs,
|
| 106 |
+
a, lda, b, ldb,
|
| 107 |
+
jpvt, rcond, rank,
|
| 108 |
+
work, lwork, rwork, info);
|
| 109 |
+
}
|
| 110 |
+
};
|
| 111 |
+
|
| 112 |
+
template <class scalar_t, class value_t>
|
| 113 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
|
| 114 |
+
static void call(
|
| 115 |
+
char trans, int m, int n, int nrhs,
|
| 116 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 117 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 118 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 119 |
+
value_t *s, // Gelss flavor
|
| 120 |
+
int *iwork // Gelsd flavor
|
| 121 |
+
) {
|
| 122 |
+
lapackGelsd<scalar_t, value_t>(
|
| 123 |
+
m, n, nrhs,
|
| 124 |
+
a, lda, b, ldb,
|
| 125 |
+
s, rcond, rank,
|
| 126 |
+
work, lwork,
|
| 127 |
+
rwork, iwork, info);
|
| 128 |
+
}
|
| 129 |
+
};
|
| 130 |
+
|
| 131 |
+
template <class scalar_t, class value_t>
|
| 132 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
|
| 133 |
+
static void call(
|
| 134 |
+
char trans, int m, int n, int nrhs,
|
| 135 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 136 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 137 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 138 |
+
value_t *s, // Gelss flavor
|
| 139 |
+
int *iwork // Gelsd flavor
|
| 140 |
+
) {
|
| 141 |
+
lapackGelss<scalar_t, value_t>(
|
| 142 |
+
m, n, nrhs,
|
| 143 |
+
a, lda, b, ldb,
|
| 144 |
+
s, rcond, rank,
|
| 145 |
+
work, lwork,
|
| 146 |
+
rwork, info);
|
| 147 |
+
}
|
| 148 |
+
};
|
| 149 |
+
|
| 150 |
+
template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
|
| 151 |
+
void lapackLstsq(
|
| 152 |
+
char trans, int m, int n, int nrhs,
|
| 153 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 154 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 155 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 156 |
+
value_t *s, // Gelss flavor
|
| 157 |
+
int *iwork // Gelsd flavor
|
| 158 |
+
) {
|
| 159 |
+
lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
|
| 160 |
+
trans, m, n, nrhs,
|
| 161 |
+
a, lda, b, ldb,
|
| 162 |
+
work, lwork, info,
|
| 163 |
+
jpvt, rcond, rank, rwork,
|
| 164 |
+
s,
|
| 165 |
+
iwork);
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
template <class scalar_t>
|
| 169 |
+
void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
|
| 170 |
+
|
| 171 |
+
template <class scalar_t>
|
| 172 |
+
void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
|
| 173 |
+
|
| 174 |
+
template <class scalar_t>
|
| 175 |
+
void lapackLdlHermitian(
|
| 176 |
+
char uplo,
|
| 177 |
+
int n,
|
| 178 |
+
scalar_t* a,
|
| 179 |
+
int lda,
|
| 180 |
+
int* ipiv,
|
| 181 |
+
scalar_t* work,
|
| 182 |
+
int lwork,
|
| 183 |
+
int* info);
|
| 184 |
+
|
| 185 |
+
template <class scalar_t>
|
| 186 |
+
void lapackLdlSymmetric(
|
| 187 |
+
char uplo,
|
| 188 |
+
int n,
|
| 189 |
+
scalar_t* a,
|
| 190 |
+
int lda,
|
| 191 |
+
int* ipiv,
|
| 192 |
+
scalar_t* work,
|
| 193 |
+
int lwork,
|
| 194 |
+
int* info);
|
| 195 |
+
|
| 196 |
+
template <class scalar_t>
|
| 197 |
+
void lapackLdlSolveHermitian(
|
| 198 |
+
char uplo,
|
| 199 |
+
int n,
|
| 200 |
+
int nrhs,
|
| 201 |
+
scalar_t* a,
|
| 202 |
+
int lda,
|
| 203 |
+
int* ipiv,
|
| 204 |
+
scalar_t* b,
|
| 205 |
+
int ldb,
|
| 206 |
+
int* info);
|
| 207 |
+
|
| 208 |
+
template <class scalar_t>
|
| 209 |
+
void lapackLdlSolveSymmetric(
|
| 210 |
+
char uplo,
|
| 211 |
+
int n,
|
| 212 |
+
int nrhs,
|
| 213 |
+
scalar_t* a,
|
| 214 |
+
int lda,
|
| 215 |
+
int* ipiv,
|
| 216 |
+
scalar_t* b,
|
| 217 |
+
int ldb,
|
| 218 |
+
int* info);
|
| 219 |
+
|
| 220 |
+
template<class scalar_t, class value_t=scalar_t>
|
| 221 |
+
void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
|
| 222 |
+
#endif
|
| 223 |
+
|
| 224 |
+
#if AT_BUILD_WITH_BLAS()
|
| 225 |
+
template <class scalar_t>
|
| 226 |
+
void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
|
| 227 |
+
#endif
|
| 228 |
+
|
| 229 |
+
using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
|
| 230 |
+
DECLARE_DISPATCH(cholesky_fn, cholesky_stub)
|
| 231 |
+
|
| 232 |
+
using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
|
| 233 |
+
|
| 234 |
+
DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub)
|
| 235 |
+
|
| 236 |
+
using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
|
| 237 |
+
|
| 238 |
+
DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub)
|
| 239 |
+
|
| 240 |
+
// Converts LAPACK's real-valued eigenvector encoding to complex eigenvectors
|
| 241 |
+
TORCH_API void linalg_eig_make_complex_eigenvectors(
|
| 242 |
+
const Tensor& complex_vectors,
|
| 243 |
+
const Tensor& complex_values,
|
| 244 |
+
const Tensor& real_vectors);
|
| 245 |
+
|
| 246 |
+
DECLARE_DISPATCH(
|
| 247 |
+
void(*)(const Tensor&, const Tensor&, const Tensor&),
|
| 248 |
+
linalg_eig_make_complex_eigenvectors_stub)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
|
| 252 |
+
DECLARE_DISPATCH(geqrf_fn, geqrf_stub)
|
| 253 |
+
|
| 254 |
+
using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
|
| 255 |
+
DECLARE_DISPATCH(orgqr_fn, orgqr_stub)
|
| 256 |
+
|
| 257 |
+
using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
|
| 258 |
+
DECLARE_DISPATCH(ormqr_fn, ormqr_stub)
|
| 259 |
+
|
| 260 |
+
using linalg_eigh_fn = void (*)(
|
| 261 |
+
const Tensor& /*eigenvalues*/,
|
| 262 |
+
const Tensor& /*eigenvectors*/,
|
| 263 |
+
const Tensor& /*infos*/,
|
| 264 |
+
bool /*upper*/,
|
| 265 |
+
bool /*compute_eigenvectors*/);
|
| 266 |
+
DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub)
|
| 267 |
+
|
| 268 |
+
using lstsq_fn = void (*)(
|
| 269 |
+
const Tensor& /*a*/,
|
| 270 |
+
Tensor& /*b*/,
|
| 271 |
+
Tensor& /*rank*/,
|
| 272 |
+
Tensor& /*singular_values*/,
|
| 273 |
+
Tensor& /*infos*/,
|
| 274 |
+
double /*rcond*/,
|
| 275 |
+
std::string /*driver_name*/);
|
| 276 |
+
DECLARE_DISPATCH(lstsq_fn, lstsq_stub)
|
| 277 |
+
|
| 278 |
+
using triangular_solve_fn = void (*)(
|
| 279 |
+
const Tensor& /*A*/,
|
| 280 |
+
const Tensor& /*B*/,
|
| 281 |
+
bool /*left*/,
|
| 282 |
+
bool /*upper*/,
|
| 283 |
+
TransposeType /*transpose*/,
|
| 284 |
+
bool /*unitriangular*/);
|
| 285 |
+
DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub)
|
| 286 |
+
|
| 287 |
+
using lu_factor_fn = void (*)(
|
| 288 |
+
const Tensor& /*input*/,
|
| 289 |
+
const Tensor& /*pivots*/,
|
| 290 |
+
const Tensor& /*infos*/,
|
| 291 |
+
bool /*compute_pivots*/);
|
| 292 |
+
DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub)
|
| 293 |
+
|
| 294 |
+
using unpack_pivots_fn = void(*)(
|
| 295 |
+
TensorIterator& iter,
|
| 296 |
+
const int64_t dim_size,
|
| 297 |
+
const int64_t max_pivot);
|
| 298 |
+
DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub)
|
| 299 |
+
|
| 300 |
+
using lu_solve_fn = void (*)(
|
| 301 |
+
const Tensor& /*LU*/,
|
| 302 |
+
const Tensor& /*pivots*/,
|
| 303 |
+
const Tensor& /*B*/,
|
| 304 |
+
TransposeType /*trans*/);
|
| 305 |
+
DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub)
|
| 306 |
+
|
| 307 |
+
using ldl_factor_fn = void (*)(
|
| 308 |
+
const Tensor& /*LD*/,
|
| 309 |
+
const Tensor& /*pivots*/,
|
| 310 |
+
const Tensor& /*info*/,
|
| 311 |
+
bool /*upper*/,
|
| 312 |
+
bool /*hermitian*/);
|
| 313 |
+
DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub)
|
| 314 |
+
|
| 315 |
+
using svd_fn = void (*)(
|
| 316 |
+
const Tensor& /*A*/,
|
| 317 |
+
const bool /*full_matrices*/,
|
| 318 |
+
const bool /*compute_uv*/,
|
| 319 |
+
const std::optional<std::string_view>& /*driver*/,
|
| 320 |
+
const Tensor& /*U*/,
|
| 321 |
+
const Tensor& /*S*/,
|
| 322 |
+
const Tensor& /*Vh*/,
|
| 323 |
+
const Tensor& /*info*/);
|
| 324 |
+
DECLARE_DISPATCH(svd_fn, svd_stub)
|
| 325 |
+
|
| 326 |
+
using ldl_solve_fn = void (*)(
|
| 327 |
+
const Tensor& /*LD*/,
|
| 328 |
+
const Tensor& /*pivots*/,
|
| 329 |
+
const Tensor& /*result*/,
|
| 330 |
+
bool /*upper*/,
|
| 331 |
+
bool /*hermitian*/);
|
| 332 |
+
DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub)
|
| 333 |
+
} // namespace at::native
|
| 334 |
+
|
| 335 |
+
#else
|
| 336 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 337 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/TensorBase.h>
|
| 5 |
+
#include <ATen/native/DispatchStub.h>
|
| 6 |
+
#include <c10/core/Scalar.h>
|
| 7 |
+
#include <c10/util/TypeSafeSignMath.h>
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
namespace at {
|
| 11 |
+
struct TensorIterator;
|
| 12 |
+
struct TensorIteratorBase;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
namespace at::native {
|
| 16 |
+
|
| 17 |
+
inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
|
| 18 |
+
TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
|
| 19 |
+
"Boolean alpha only supported for Boolean results.");
|
| 20 |
+
TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
|
| 21 |
+
|| alpha.isIntegral(true),
|
| 22 |
+
"For integral input tensors, argument alpha must not be a floating point number.");
|
| 23 |
+
TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
|
| 24 |
+
"For non-complex input tensors, argument alpha must not be a complex number.")
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
// Basic checking for all sub functions.
|
| 28 |
+
inline void sub_check(const TensorBase& self, const TensorBase& other) {
|
| 29 |
+
TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
|
| 30 |
+
"Subtraction, the `-` operator, with two bool tensors is not supported. "
|
| 31 |
+
"Use the `^` or `logical_xor()` operator instead.")
|
| 32 |
+
TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
|
| 33 |
+
"Subtraction, the `-` operator, with a bool tensor is not supported. "
|
| 34 |
+
"If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
inline void sub_check(const TensorBase& self, const Scalar& scalar) {
|
| 38 |
+
TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
|
| 39 |
+
"Subtraction, the `-` operator, with two bool tensors is not supported. "
|
| 40 |
+
"Use the `^` or `logical_xor()` operator instead.")
|
| 41 |
+
TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
|
| 42 |
+
"Subtraction, the `-` operator, with a bool tensor is not supported. "
|
| 43 |
+
"If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
|
| 47 |
+
using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
|
| 48 |
+
using structured_binary_fn = void(*)(TensorIteratorBase&);
|
| 49 |
+
|
| 50 |
+
using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
|
| 51 |
+
using binary_fn_double = void(*)(TensorIterator&, double);
|
| 52 |
+
using binary_fn = void(*)(TensorIterator&);
|
| 53 |
+
using binary_clamp_fn_alpha =
|
| 54 |
+
void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
|
| 55 |
+
|
| 56 |
+
// NB: codegenned
|
| 57 |
+
DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub)
|
| 58 |
+
|
| 59 |
+
DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub)
|
| 60 |
+
DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub)
|
| 61 |
+
DECLARE_DISPATCH(structured_binary_fn, mul_stub)
|
| 62 |
+
DECLARE_DISPATCH(structured_binary_fn, div_true_stub)
|
| 63 |
+
DECLARE_DISPATCH(structured_binary_fn, div_floor_stub)
|
| 64 |
+
DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub)
|
| 65 |
+
DECLARE_DISPATCH(structured_binary_fn, atan2_stub)
|
| 66 |
+
DECLARE_DISPATCH(structured_binary_fn, remainder_stub)
|
| 67 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub)
|
| 68 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub)
|
| 69 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub)
|
| 70 |
+
DECLARE_DISPATCH(structured_binary_fn, lshift_stub)
|
| 71 |
+
DECLARE_DISPATCH(structured_binary_fn, rshift_stub)
|
| 72 |
+
DECLARE_DISPATCH(binary_fn, logical_xor_stub)
|
| 73 |
+
DECLARE_DISPATCH(binary_fn, logical_and_stub)
|
| 74 |
+
DECLARE_DISPATCH(binary_fn, logical_or_stub)
|
| 75 |
+
DECLARE_DISPATCH(structured_binary_fn, lt_stub)
|
| 76 |
+
DECLARE_DISPATCH(structured_binary_fn, le_stub)
|
| 77 |
+
DECLARE_DISPATCH(structured_binary_fn, gt_stub)
|
| 78 |
+
DECLARE_DISPATCH(structured_binary_fn, ge_stub)
|
| 79 |
+
DECLARE_DISPATCH(structured_binary_fn, eq_stub)
|
| 80 |
+
DECLARE_DISPATCH(structured_binary_fn, ne_stub)
|
| 81 |
+
DECLARE_DISPATCH(binary_fn, max_elementwise_stub)
|
| 82 |
+
DECLARE_DISPATCH(binary_fn, min_elementwise_stub)
|
| 83 |
+
DECLARE_DISPATCH(structured_binary_fn, maximum_stub)
|
| 84 |
+
DECLARE_DISPATCH(structured_binary_fn, minimum_stub)
|
| 85 |
+
DECLARE_DISPATCH(structured_binary_fn, fmax_stub)
|
| 86 |
+
DECLARE_DISPATCH(structured_binary_fn, fmin_stub)
|
| 87 |
+
DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub)
|
| 88 |
+
DECLARE_DISPATCH(binary_fn_double, huber_stub)
|
| 89 |
+
DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub)
|
| 90 |
+
DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub)
|
| 91 |
+
DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub)
|
| 92 |
+
DECLARE_DISPATCH(structured_binary_fn, mse_stub)
|
| 93 |
+
DECLARE_DISPATCH(structured_binary_fn, fmod_stub)
|
| 94 |
+
DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub)
|
| 95 |
+
DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub)
|
| 96 |
+
DECLARE_DISPATCH(structured_binary_fn, gcd_stub)
|
| 97 |
+
DECLARE_DISPATCH(structured_binary_fn, lcm_stub)
|
| 98 |
+
DECLARE_DISPATCH(structured_binary_fn, hypot_stub)
|
| 99 |
+
DECLARE_DISPATCH(structured_binary_fn, igamma_stub)
|
| 100 |
+
DECLARE_DISPATCH(structured_binary_fn, igammac_stub)
|
| 101 |
+
DECLARE_DISPATCH(structured_binary_fn, nextafter_stub)
|
| 102 |
+
DECLARE_DISPATCH(structured_binary_fn, heaviside_stub)
|
| 103 |
+
DECLARE_DISPATCH(structured_binary_fn, copysign_stub)
|
| 104 |
+
DECLARE_DISPATCH(structured_binary_fn, xlogy_stub)
|
| 105 |
+
DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub)
|
| 106 |
+
DECLARE_DISPATCH(structured_binary_fn, zeta_stub)
|
| 107 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub)
|
| 108 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub)
|
| 109 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub)
|
| 110 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub)
|
| 111 |
+
DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub)
|
| 112 |
+
DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub)
|
| 113 |
+
DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub)
|
| 114 |
+
DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub)
|
| 115 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub)
|
| 116 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub)
|
| 117 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub)
|
| 118 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub)
|
| 119 |
+
|
| 120 |
+
} // namespace at::native
|
| 121 |
+
|
| 122 |
+
#else
|
| 123 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 124 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <ATen/native/TypeProperties.h>
|
| 6 |
+
#include <ATen/ScalarOps.h>
|
| 7 |
+
|
| 8 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 9 |
+
#include <ATen/NativeFunctions.h>
|
| 10 |
+
#else
|
| 11 |
+
#include <ATen/ops/result_type.h>
|
| 12 |
+
#endif
|
| 13 |
+
|
| 14 |
+
namespace at::native {
|
| 15 |
+
|
| 16 |
+
// original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to
|
| 17 |
+
// the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not
|
| 18 |
+
// match, will change them to be a common super type so comparisons are done between the same types.
|
| 19 |
+
// For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the
|
| 20 |
+
// corresponding raw_* version should be used since it was already contiguous of the right type.
|
| 21 |
+
inline void searchsorted_maybe_trim_input_tensors(
|
| 22 |
+
Tensor& trimmed_input,
|
| 23 |
+
Tensor& trimmed_boundaries,
|
| 24 |
+
Tensor& trimmed_sorter,
|
| 25 |
+
const Tensor& raw_input,
|
| 26 |
+
const Tensor& raw_boundaries,
|
| 27 |
+
const Tensor& raw_sorter) {
|
| 28 |
+
bool in_is_contiguous = raw_input.is_contiguous();
|
| 29 |
+
bool bd_is_contiguous = raw_boundaries.is_contiguous();
|
| 30 |
+
bool sort_is_contiguous = raw_sorter.is_contiguous();
|
| 31 |
+
|
| 32 |
+
if (!in_is_contiguous) {
|
| 33 |
+
TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due "
|
| 34 |
+
"to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value "
|
| 35 |
+
"tensor if possible. This message will only appear once per program.");
|
| 36 |
+
trimmed_input = raw_input.contiguous();
|
| 37 |
+
}
|
| 38 |
+
if (!bd_is_contiguous) {
|
| 39 |
+
TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due "
|
| 40 |
+
"to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary "
|
| 41 |
+
"tensor if possible. This message will only appear once per program.");
|
| 42 |
+
trimmed_boundaries = raw_boundaries.contiguous();
|
| 43 |
+
}
|
| 44 |
+
if (!sort_is_contiguous) {
|
| 45 |
+
TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due "
|
| 46 |
+
"to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter "
|
| 47 |
+
"tensor if possible. This message will only appear once per program.");
|
| 48 |
+
trimmed_sorter = raw_sorter.contiguous();
|
| 49 |
+
}
|
| 50 |
+
if (raw_input.dtype() != raw_boundaries.dtype()) {
|
| 51 |
+
at::native::ResultTypeState state = {};
|
| 52 |
+
state = at::native::update_result_type_state(raw_boundaries, state);
|
| 53 |
+
state = at::native::update_result_type_state(raw_input, state);
|
| 54 |
+
ScalarType common_stype = at::native::result_type(state);
|
| 55 |
+
|
| 56 |
+
TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined);
|
| 57 |
+
if (common_stype != raw_input.scalar_type()) {
|
| 58 |
+
trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype);
|
| 59 |
+
}
|
| 60 |
+
if (common_stype != raw_boundaries.scalar_type()) {
|
| 61 |
+
trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype);
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
/* unused but needed for internal jagged tensor class */
|
| 67 |
+
inline void searchsorted_maybe_trim_input_tensors(
|
| 68 |
+
Tensor& trimmed_input,
|
| 69 |
+
Tensor& trimmed_boundaries,
|
| 70 |
+
const Tensor& raw_input,
|
| 71 |
+
const Tensor& raw_boundaries) {
|
| 72 |
+
Tensor trimmed_sorter;
|
| 73 |
+
Tensor raw_sorter;
|
| 74 |
+
searchsorted_maybe_trim_input_tensors(
|
| 75 |
+
trimmed_input,
|
| 76 |
+
trimmed_boundaries,
|
| 77 |
+
trimmed_sorter,
|
| 78 |
+
raw_input,
|
| 79 |
+
raw_boundaries,
|
| 80 |
+
raw_sorter);
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) {
|
| 84 |
+
if (boundaries.dim() != input.dim()) {
|
| 85 |
+
return false;
|
| 86 |
+
}
|
| 87 |
+
const auto& dims_bd = boundaries.sizes();
|
| 88 |
+
const auto& dims_in = input.sizes();
|
| 89 |
+
for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) {
|
| 90 |
+
if (dims_bd[dim] != dims_in[dim]) {
|
| 91 |
+
return false;
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
return true;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) {
|
| 98 |
+
auto tensor = c10::scalar_to_tensor(scalar, device);
|
| 99 |
+
// This is to adopt the scalar promotion rules defined in native/TypeProperties.h
|
| 100 |
+
// So we have the same type promotion rules as binary operations.
|
| 101 |
+
tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
|
| 102 |
+
return tensor;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
inline void searchsorted_pre_check(
|
| 106 |
+
const Tensor& boundaries,
|
| 107 |
+
const Tensor& input,
|
| 108 |
+
const Tensor& output,
|
| 109 |
+
const bool out_int32,
|
| 110 |
+
const bool right,
|
| 111 |
+
const std::optional<std::string_view> side_opt,
|
| 112 |
+
const Tensor& sorter) {
|
| 113 |
+
if (side_opt) {
|
| 114 |
+
const std::string_view side = *side_opt;
|
| 115 |
+
TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ",
|
| 116 |
+
"got ", side);
|
| 117 |
+
|
| 118 |
+
// assume the user has not explicitly set (right=False, side="right")
|
| 119 |
+
TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side "
|
| 120 |
+
"of ", side, " while right was True");
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ",
|
| 124 |
+
"should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ",
|
| 125 |
+
"tensor device type ", input.device());
|
| 126 |
+
|
| 127 |
+
if (sorter.defined()) {
|
| 128 |
+
TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ",
|
| 129 |
+
"have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ",
|
| 130 |
+
"device type ", boundaries.device());
|
| 131 |
+
|
| 132 |
+
TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same "
|
| 133 |
+
"size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes());
|
| 134 |
+
|
| 135 |
+
TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ",
|
| 136 |
+
"dtype but got dtype ", sorter.scalar_type());
|
| 137 |
+
|
| 138 |
+
if (sorter.numel() > 0) {
|
| 139 |
+
auto minmax = sorter.aminmax();
|
| 140 |
+
int64_t vmin = std::get<0>(minmax).item().toLong();
|
| 141 |
+
int64_t vmax = std::get<1>(minmax).item().toLong();
|
| 142 |
+
TORCH_CHECK(vmin >= 0 && vmax < sorter.sizes().back(), "torch.searchsorted(): sorter index out of range");
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1),
|
| 147 |
+
"torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ",
|
| 148 |
+
"boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(",
|
| 149 |
+
input.numel(), ")");
|
| 150 |
+
|
| 151 |
+
TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ",
|
| 152 |
+
"got 0 dimension");
|
| 153 |
+
|
| 154 |
+
TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input),
|
| 155 |
+
"torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ",
|
| 156 |
+
"and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ",
|
| 157 |
+
input.sizes());
|
| 158 |
+
|
| 159 |
+
ScalarType output_dtype = output.scalar_type();
|
| 160 |
+
TORCH_CHECK(
|
| 161 |
+
(output_dtype == ScalarType::Long && !out_int32) ||
|
| 162 |
+
(output_dtype == ScalarType::Int && out_int32),
|
| 163 |
+
"torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ",
|
| 164 |
+
"whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype,
|
| 165 |
+
" and out_int32 flag is ", (out_int32 ? "True" : "False"));
|
| 166 |
+
|
| 167 |
+
if (out_int32) {
|
| 168 |
+
TORCH_CHECK(boundaries.sizes().back() < INT_MAX,
|
| 169 |
+
"torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ",
|
| 170 |
+
boundaries.sizes().back());
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
} // namespace at::native
|
| 175 |
+
|
| 176 |
+
#else
|
| 177 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 178 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/OpMathType.h>
|
| 5 |
+
#include <ATen/native/DispatchStub.h>
|
| 6 |
+
#include <ATen/native/TransposeType.h>
|
| 7 |
+
#include <c10/util/complex.h>
|
| 8 |
+
#include <c10/core/ScalarType.h>
|
| 9 |
+
#include <c10/core/Scalar.h>
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
namespace at::native::cpublas {
|
| 13 |
+
|
| 14 |
+
namespace internal {
|
| 15 |
+
void normalize_last_dims(
|
| 16 |
+
TransposeType transa, TransposeType transb,
|
| 17 |
+
int64_t m, int64_t n, int64_t k,
|
| 18 |
+
int64_t *lda, int64_t *ldb, int64_t *ldc);
|
| 19 |
+
} // namespace internal
|
| 20 |
+
|
| 21 |
+
using gemm_fn = void(*)(
|
| 22 |
+
at::ScalarType type,
|
| 23 |
+
TransposeType transa, TransposeType transb,
|
| 24 |
+
int64_t m, int64_t n, int64_t k,
|
| 25 |
+
const Scalar& alpha,
|
| 26 |
+
const void *a, int64_t lda,
|
| 27 |
+
const void *b, int64_t ldb,
|
| 28 |
+
const Scalar& beta,
|
| 29 |
+
void *c, int64_t ldc);
|
| 30 |
+
|
| 31 |
+
DECLARE_DISPATCH(gemm_fn, gemm_stub)
|
| 32 |
+
|
| 33 |
+
using gemm_no_downcast_fn = void(*)(
|
| 34 |
+
at::ScalarType type,
|
| 35 |
+
TransposeType transa, TransposeType transb,
|
| 36 |
+
int64_t m, int64_t n, int64_t k,
|
| 37 |
+
const Scalar& alpha,
|
| 38 |
+
const void *a, int64_t lda,
|
| 39 |
+
const void *b, int64_t ldb,
|
| 40 |
+
const Scalar& beta,
|
| 41 |
+
void *c, int64_t ldc);
|
| 42 |
+
|
| 43 |
+
DECLARE_DISPATCH(gemm_no_downcast_fn, gemm_no_downcast_stub)
|
| 44 |
+
|
| 45 |
+
template <typename scalar_t>
|
| 46 |
+
void gemm(
|
| 47 |
+
TransposeType transa, TransposeType transb,
|
| 48 |
+
int64_t m, int64_t n, int64_t k,
|
| 49 |
+
at::opmath_type<scalar_t> alpha,
|
| 50 |
+
const scalar_t *a, int64_t lda,
|
| 51 |
+
const scalar_t *b, int64_t ldb,
|
| 52 |
+
at::opmath_type<scalar_t> beta,
|
| 53 |
+
scalar_t *c, int64_t ldc) {
|
| 54 |
+
internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc);
|
| 55 |
+
gemm_stub(
|
| 56 |
+
kCPU, c10::CppTypeToScalarType<scalar_t>::value,
|
| 57 |
+
transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
void gemm(
|
| 61 |
+
TransposeType transa, TransposeType transb,
|
| 62 |
+
int64_t m, int64_t n, int64_t k,
|
| 63 |
+
double alpha,
|
| 64 |
+
const double *a, int64_t lda,
|
| 65 |
+
const double *b, int64_t ldb,
|
| 66 |
+
double beta,
|
| 67 |
+
double *c, int64_t ldc);
|
| 68 |
+
|
| 69 |
+
void gemm(
|
| 70 |
+
TransposeType transa, TransposeType transb,
|
| 71 |
+
int64_t m, int64_t n, int64_t k,
|
| 72 |
+
float alpha,
|
| 73 |
+
const float *a, int64_t lda,
|
| 74 |
+
const float *b, int64_t ldb,
|
| 75 |
+
float beta,
|
| 76 |
+
float *c, int64_t ldc);
|
| 77 |
+
|
| 78 |
+
void gemm(
|
| 79 |
+
TransposeType transa, TransposeType transb,
|
| 80 |
+
int64_t m, int64_t n, int64_t k,
|
| 81 |
+
float alpha,
|
| 82 |
+
const at::BFloat16 *a, int64_t lda,
|
| 83 |
+
const at::BFloat16 *b, int64_t ldb,
|
| 84 |
+
float beta,
|
| 85 |
+
at::BFloat16 *c, int64_t ldc);
|
| 86 |
+
|
| 87 |
+
void gemm(
|
| 88 |
+
TransposeType transa, TransposeType transb,
|
| 89 |
+
int64_t m, int64_t n, int64_t k,
|
| 90 |
+
const float alpha,
|
| 91 |
+
const at::BFloat16 *a, int64_t lda,
|
| 92 |
+
const at::BFloat16 *b, int64_t ldb,
|
| 93 |
+
const float beta,
|
| 94 |
+
float *c, int64_t ldc);
|
| 95 |
+
|
| 96 |
+
void gemm(
|
| 97 |
+
TransposeType transa, TransposeType transb,
|
| 98 |
+
int64_t m, int64_t n, int64_t k,
|
| 99 |
+
float alpha,
|
| 100 |
+
const at::Half *a, int64_t lda,
|
| 101 |
+
const at::Half *b, int64_t ldb,
|
| 102 |
+
float beta,
|
| 103 |
+
at::Half *c, int64_t ldc);
|
| 104 |
+
|
| 105 |
+
void gemm(
|
| 106 |
+
TransposeType transa, TransposeType transb,
|
| 107 |
+
int64_t m, int64_t n, int64_t k,
|
| 108 |
+
const float alpha,
|
| 109 |
+
const at::Half *a, int64_t lda,
|
| 110 |
+
const at::Half *b, int64_t ldb,
|
| 111 |
+
const float beta,
|
| 112 |
+
float *c, int64_t ldc);
|
| 113 |
+
|
| 114 |
+
void gemm(
|
| 115 |
+
TransposeType transa, TransposeType transb,
|
| 116 |
+
int64_t m, int64_t n, int64_t k,
|
| 117 |
+
c10::complex<double> alpha,
|
| 118 |
+
const c10::complex<double> *a, int64_t lda,
|
| 119 |
+
const c10::complex<double> *b, int64_t ldb,
|
| 120 |
+
c10::complex<double> beta,
|
| 121 |
+
c10::complex<double> *c, int64_t ldc);
|
| 122 |
+
|
| 123 |
+
void gemm(
|
| 124 |
+
TransposeType transa, TransposeType transb,
|
| 125 |
+
int64_t m, int64_t n, int64_t k,
|
| 126 |
+
c10::complex<float> alpha,
|
| 127 |
+
const c10::complex<float> *a, int64_t lda,
|
| 128 |
+
const c10::complex<float> *b, int64_t ldb,
|
| 129 |
+
c10::complex<float> beta,
|
| 130 |
+
c10::complex<float> *c, int64_t ldc);
|
| 131 |
+
|
| 132 |
+
void gemm(
|
| 133 |
+
TransposeType transa, TransposeType transb,
|
| 134 |
+
int64_t m, int64_t n, int64_t k,
|
| 135 |
+
int64_t alpha,
|
| 136 |
+
const int64_t *a, int64_t lda,
|
| 137 |
+
const int64_t *b, int64_t ldb,
|
| 138 |
+
int64_t beta,
|
| 139 |
+
int64_t *c, int64_t ldc);
|
| 140 |
+
|
| 141 |
+
template <typename scalar_t>
|
| 142 |
+
void gemm_batched(
|
| 143 |
+
TransposeType transa, TransposeType transb,
|
| 144 |
+
int64_t batch_size, int64_t m, int64_t n, int64_t k,
|
| 145 |
+
scalar_t alpha,
|
| 146 |
+
const scalar_t * const *a, int64_t lda,
|
| 147 |
+
const scalar_t * const *b, int64_t ldb,
|
| 148 |
+
const scalar_t beta,
|
| 149 |
+
scalar_t * const *c, int64_t ldc);
|
| 150 |
+
|
| 151 |
+
template <typename scalar_t>
|
| 152 |
+
void gemm_batched_with_stride(
|
| 153 |
+
TransposeType transa, TransposeType transb,
|
| 154 |
+
int64_t batch_size, int64_t m, int64_t n, int64_t k,
|
| 155 |
+
scalar_t alpha,
|
| 156 |
+
const scalar_t *a, int64_t lda, int64_t batch_stride_a,
|
| 157 |
+
const scalar_t *b, int64_t ldb, int64_t batch_stride_b,
|
| 158 |
+
scalar_t beta,
|
| 159 |
+
scalar_t *c, int64_t ldc, int64_t batch_stride_c);
|
| 160 |
+
|
| 161 |
+
using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy);
|
| 162 |
+
|
| 163 |
+
DECLARE_DISPATCH(axpy_fn, axpy_stub)
|
| 164 |
+
|
| 165 |
+
template<typename scalar_t>
|
| 166 |
+
void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){
|
| 167 |
+
if(n == 1)
|
| 168 |
+
{
|
| 169 |
+
incx = 1;
|
| 170 |
+
incy = 1;
|
| 171 |
+
}
|
| 172 |
+
axpy_stub(
|
| 173 |
+
kCPU, c10::CppTypeToScalarType<scalar_t>::value,
|
| 174 |
+
n, a, x, incx, y, incy);
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy);
|
| 178 |
+
void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy);
|
| 179 |
+
void axpy(int64_t n, c10::complex<double> a, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
|
| 180 |
+
void axpy(int64_t n, c10::complex<float> a, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
|
| 181 |
+
|
| 182 |
+
using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy);
|
| 183 |
+
|
| 184 |
+
DECLARE_DISPATCH(copy_fn, copy_stub)
|
| 185 |
+
|
| 186 |
+
template<typename scalar_t>
|
| 187 |
+
void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) {
|
| 188 |
+
if(n == 1)
|
| 189 |
+
{
|
| 190 |
+
incx = 1;
|
| 191 |
+
incy = 1;
|
| 192 |
+
}
|
| 193 |
+
copy_stub(
|
| 194 |
+
kCPU, c10::CppTypeToScalarType<scalar_t>::value,
|
| 195 |
+
n, x, incx, y, incy);
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy);
|
| 199 |
+
void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy);
|
| 200 |
+
void copy(int64_t n, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
|
| 201 |
+
void copy(int64_t n, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
|
| 202 |
+
|
| 203 |
+
// Batch-reduce GEMM
|
| 204 |
+
// Operates by the following formula:
|
| 205 |
+
// C = SUM(A[i] x B[i]) + C if add_C is true, i = 0 to batch size
|
| 206 |
+
// A Base pointer to a tensor A.
|
| 207 |
+
// B Base pointer to a tensor B.
|
| 208 |
+
// C Pointer to a tensor C (accumulation buffer).
|
| 209 |
+
// Note only batch size 1 is used currently
|
| 210 |
+
|
| 211 |
+
// Define macros for available brgemm APIs
|
| 212 |
+
// so that callers can determine which APIs are available
|
| 213 |
+
#define CPUBLAS_BRGEMM_F16F16F32 // half * half -> float
|
| 214 |
+
#define CPUBLAS_BRGEMM_BF16BF16F32 // bfloat16 * bfloat16 -> float
|
| 215 |
+
#define CPUBLAS_BRGEMM_F32F32F32 // float * float -> float
|
| 216 |
+
#define CPUBLAS_BRGEMM_U8U8I32 // unsigned char * unsigned char -> int32
|
| 217 |
+
#define CPUBLAS_BRGEMM_U8I8I32 // unsigned char * signed char -> int32
|
| 218 |
+
#define CPUBLAS_BRGEMM_I8I8I32 // signed char * signed char -> int32
|
| 219 |
+
|
| 220 |
+
TORCH_API void brgemm(
|
| 221 |
+
int64_t M,
|
| 222 |
+
int64_t N,
|
| 223 |
+
int64_t K,
|
| 224 |
+
int64_t ld_a,
|
| 225 |
+
int64_t ld_b,
|
| 226 |
+
int64_t ld_c,
|
| 227 |
+
const bool add_C,
|
| 228 |
+
const at::Half* A,
|
| 229 |
+
const at::Half* B,
|
| 230 |
+
float* C,
|
| 231 |
+
bool is_vnni = true);
|
| 232 |
+
|
| 233 |
+
TORCH_API void brgemm(
|
| 234 |
+
int64_t M,
|
| 235 |
+
int64_t N,
|
| 236 |
+
int64_t K,
|
| 237 |
+
int64_t ld_a,
|
| 238 |
+
int64_t ld_b,
|
| 239 |
+
int64_t ld_c,
|
| 240 |
+
const bool add_C,
|
| 241 |
+
const at::BFloat16* A,
|
| 242 |
+
const at::BFloat16* B,
|
| 243 |
+
float* C,
|
| 244 |
+
bool is_vnni = true);
|
| 245 |
+
|
| 246 |
+
TORCH_API void brgemm(
|
| 247 |
+
int64_t M,
|
| 248 |
+
int64_t N,
|
| 249 |
+
int64_t K,
|
| 250 |
+
int64_t ld_a,
|
| 251 |
+
int64_t ld_b,
|
| 252 |
+
int64_t ld_c,
|
| 253 |
+
const bool add_C,
|
| 254 |
+
const float* A,
|
| 255 |
+
const float* B,
|
| 256 |
+
float* C,
|
| 257 |
+
bool is_vnni = false);
|
| 258 |
+
|
| 259 |
+
TORCH_API void brgemm(
|
| 260 |
+
int64_t M,
|
| 261 |
+
int64_t N,
|
| 262 |
+
int64_t K,
|
| 263 |
+
int64_t ld_a,
|
| 264 |
+
int64_t ld_b,
|
| 265 |
+
int64_t ld_c,
|
| 266 |
+
const bool add_C,
|
| 267 |
+
const unsigned char* A,
|
| 268 |
+
const unsigned char* B,
|
| 269 |
+
int32_t* C,
|
| 270 |
+
bool is_vnni = true);
|
| 271 |
+
|
| 272 |
+
TORCH_API void brgemm(
|
| 273 |
+
int64_t M,
|
| 274 |
+
int64_t N,
|
| 275 |
+
int64_t K,
|
| 276 |
+
int64_t ld_a,
|
| 277 |
+
int64_t ld_b,
|
| 278 |
+
int64_t ld_c,
|
| 279 |
+
const bool add_C,
|
| 280 |
+
const unsigned char* A,
|
| 281 |
+
const signed char* B,
|
| 282 |
+
int32_t* C,
|
| 283 |
+
bool is_vnni = true);
|
| 284 |
+
|
| 285 |
+
TORCH_API void brgemm(
|
| 286 |
+
int64_t M,
|
| 287 |
+
int64_t N,
|
| 288 |
+
int64_t K,
|
| 289 |
+
int64_t ld_a,
|
| 290 |
+
int64_t ld_b,
|
| 291 |
+
int64_t ld_c,
|
| 292 |
+
const bool add_C,
|
| 293 |
+
const signed char* A,
|
| 294 |
+
const signed char* B,
|
| 295 |
+
int32_t* C,
|
| 296 |
+
bool is_vnni = true);
|
| 297 |
+
|
| 298 |
+
// Release brgemm hardware context
|
| 299 |
+
TORCH_API void brgemm_release(bool is_vnni = true);
|
| 300 |
+
|
| 301 |
+
// Pack B matrix to get better performance if needed
|
| 302 |
+
TORCH_API void pack(
|
| 303 |
+
int64_t K,
|
| 304 |
+
int64_t N,
|
| 305 |
+
int64_t ld_in,
|
| 306 |
+
int64_t ld_out,
|
| 307 |
+
ScalarType dt_in,
|
| 308 |
+
ScalarType dt_out,
|
| 309 |
+
const void* in,
|
| 310 |
+
void* out);
|
| 311 |
+
|
| 312 |
+
// Whether pack is supported in the platform.
|
| 313 |
+
TORCH_API bool could_pack(ScalarType dt_in);
|
| 314 |
+
|
| 315 |
+
} // namespace at::native::cpublas
|
| 316 |
+
|
| 317 |
+
#else
|
| 318 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 319 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CPUFallback.h
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/ivalue.h>
|
| 5 |
+
#include <ATen/core/stack.h>
|
| 6 |
+
#include <ATen/core/boxing/KernelFunction.h>
|
| 7 |
+
#include <ATen/core/dispatch/Dispatcher.h>
|
| 8 |
+
#include <c10/util/Metaprogramming.h>
|
| 9 |
+
#include <torch/library.h>
|
| 10 |
+
|
| 11 |
+
namespace at::native {
|
| 12 |
+
|
| 13 |
+
// This function implements a boxed fallback to CPU.
|
| 14 |
+
// External backends can add their own custom logging on top if it to customize their own CPU fallbacks.
|
| 15 |
+
TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool error_on_views = false,
|
| 16 |
+
c10::DispatchKey cpu_dispatch_key = c10::DispatchKey::CPU);
|
| 17 |
+
|
| 18 |
+
// This is a helper function that backends can use to directly call their boxed CPU fallback
|
| 19 |
+
// TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands.
|
| 20 |
+
template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
|
| 21 |
+
struct _call_fallback_fn final {};
|
| 22 |
+
|
| 23 |
+
template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op, bool symint, class ReturnType, class... ParameterTypes>
|
| 24 |
+
struct _call_fallback_fn<fallback_fn, Op, symint, ReturnType(ParameterTypes...)> final {
|
| 25 |
+
static ReturnType call(typename c10::maybe_keep_symint<symint, ParameterTypes>::type... args) {
|
| 26 |
+
auto op = c10::Dispatcher::singleton()
|
| 27 |
+
// TODO: figure out how to make compiler happy without dynamic casts
|
| 28 |
+
.findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name)
|
| 29 |
+
//.findSchemaOrThrow("a", "b")
|
| 30 |
+
.typed<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>();
|
| 31 |
+
return c10::impl::BoxedKernelWrapper<ReturnType (typename c10::maybe_keep_symint<symint, ParameterTypes>::type...)>::call(
|
| 32 |
+
c10::BoxedKernel::makeFromFunction<fallback_fn>(),
|
| 33 |
+
op,
|
| 34 |
+
c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset.
|
| 35 |
+
// TODO: get std::forward<> to work
|
| 36 |
+
args...
|
| 37 |
+
);
|
| 38 |
+
}
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
|
| 42 |
+
using call_fallback_fn_symint = _call_fallback_fn<fallback_fn, Op, true, typename Op::schema>;
|
| 43 |
+
|
| 44 |
+
template<c10::KernelFunction::BoxedKernelFunction* fallback_fn, class Op>
|
| 45 |
+
using call_fallback_fn = _call_fallback_fn<fallback_fn, Op, false, typename Op::schema>;
|
| 46 |
+
|
| 47 |
+
} // namespace at::native
|
| 48 |
+
|
| 49 |
+
#else
|
| 50 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 51 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CanUse32BitIndexMath.h
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <c10/macros/Export.h>
|
| 4 |
+
#include <limits>
|
| 5 |
+
|
| 6 |
+
namespace at {
|
| 7 |
+
class TensorBase;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
namespace at::native {
|
| 11 |
+
|
| 12 |
+
TORCH_API bool canUse32BitIndexMath(const at::TensorBase &t, int64_t max_elem=std::numeric_limits<int32_t>::max());
|
| 13 |
+
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
#else
|
| 17 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 18 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <c10/util/irange.h>
|
| 6 |
+
|
| 7 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 8 |
+
#include <ATen/NativeFunctions.h>
|
| 9 |
+
#else
|
| 10 |
+
#include <ATen/ops/view_as_real_native.h>
|
| 11 |
+
#include <ATen/ops/view_as_complex_native.h>
|
| 12 |
+
|
| 13 |
+
#include <utility>
|
| 14 |
+
#endif
|
| 15 |
+
|
| 16 |
+
// WARNING: this header contains non-inline functions and should be only
|
| 17 |
+
// included from ONE cpp file
|
| 18 |
+
|
| 19 |
+
namespace at::native {
|
| 20 |
+
|
| 21 |
+
// View tensor with new dtype, storage offset, sizes and strides
|
| 22 |
+
inline Tensor view_tensor(
|
| 23 |
+
const Tensor &tensor, ScalarType dtype,
|
| 24 |
+
c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) {
|
| 25 |
+
Storage storage = tensor.storage();
|
| 26 |
+
auto key_set = tensor.key_set().remove(DispatchKey::Conjugate);
|
| 27 |
+
auto new_tensor = detail::make_tensor<TensorImpl>(
|
| 28 |
+
c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype));
|
| 29 |
+
auto * impl = new_tensor.unsafeGetTensorImpl();
|
| 30 |
+
impl->set_sizes_and_strides(sizes, strides, offset);
|
| 31 |
+
return new_tensor;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) {
|
| 35 |
+
SymDimVector res(oldstride.size() + 1);
|
| 36 |
+
for (const auto i : c10::irange(oldstride.size())) {
|
| 37 |
+
res[i] = oldstride[i] * 2;
|
| 38 |
+
}
|
| 39 |
+
res.back() = 1;
|
| 40 |
+
return res;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
inline Tensor _view_as_real_physical(const Tensor& self) {
|
| 44 |
+
TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors");
|
| 45 |
+
auto old_sizes = self.sym_sizes();
|
| 46 |
+
SymDimVector new_sizes(old_sizes.size() + 1);
|
| 47 |
+
std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
|
| 48 |
+
// last dimension will always have two elements containing the real and imag vals
|
| 49 |
+
new_sizes.back() = 2;
|
| 50 |
+
auto new_strides = computeStrideForViewAsReal(self.sym_strides());
|
| 51 |
+
auto new_storage_offset = self.sym_storage_offset() * 2;
|
| 52 |
+
const auto float_type = c10::toRealValueType(self.scalar_type());
|
| 53 |
+
auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides);
|
| 54 |
+
return real_tensor;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// expects as input a complex tensor and returns back a tensor
|
| 58 |
+
// with corresponding real dtype containing the complex values
|
| 59 |
+
// in the last two dimensions
|
| 60 |
+
Tensor view_as_real(const Tensor& self) {
|
| 61 |
+
TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original.");
|
| 62 |
+
return _view_as_real_physical(self);
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
inline SymDimVector computeStrideForViewAsComplex(SymIntArrayRef oldstride) {
|
| 66 |
+
const auto dim = oldstride.size();
|
| 67 |
+
TORCH_CHECK(dim > 0 && oldstride[dim - 1] == 1, "Tensor must have a last dimension with stride 1");
|
| 68 |
+
|
| 69 |
+
SymDimVector res(dim - 1);
|
| 70 |
+
for (const auto i : c10::irange(res.size())) {
|
| 71 |
+
TORCH_CHECK(oldstride[i] % 2 == 0, "Tensor must have a stride divisible by 2 for all but last dimension");
|
| 72 |
+
res[i] = oldstride[i] / 2;
|
| 73 |
+
}
|
| 74 |
+
return res;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// expects as input a float or double tensor with last dimension of size 2
|
| 78 |
+
// and returns back a tensor with corresponding complex dtype
|
| 79 |
+
Tensor view_as_complex(const Tensor& self) {
|
| 80 |
+
TORCH_CHECK(
|
| 81 |
+
self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf,
|
| 82 |
+
"view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type());
|
| 83 |
+
|
| 84 |
+
auto old_sizes = self.sym_sizes();
|
| 85 |
+
TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions");
|
| 86 |
+
TORCH_CHECK(old_sizes[old_sizes.size()-1] == 2, "Tensor must have a last dimension of size 2");
|
| 87 |
+
SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1);
|
| 88 |
+
|
| 89 |
+
const auto new_strides = computeStrideForViewAsComplex(self.sym_strides());
|
| 90 |
+
const auto complex_type = c10::toComplexType(self.scalar_type());
|
| 91 |
+
|
| 92 |
+
TORCH_CHECK(self.sym_storage_offset() % 2 == 0, "Tensor must have a storage_offset divisible by 2");
|
| 93 |
+
const auto new_storage_offset = self.sym_storage_offset() / 2;
|
| 94 |
+
|
| 95 |
+
return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides);
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
} // namespace at::native
|
| 99 |
+
|
| 100 |
+
#else
|
| 101 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 102 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessor.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/CompositeRandomAccessorCommon.h>
|
| 5 |
+
|
| 6 |
+
namespace at::native {
|
| 7 |
+
|
| 8 |
+
struct TupleInfoCPU {
|
| 9 |
+
template <typename ...Types>
|
| 10 |
+
using tuple = std::tuple<Types...>;
|
| 11 |
+
|
| 12 |
+
template <typename ...Types>
|
| 13 |
+
static constexpr auto tie(Types&... args) noexcept {
|
| 14 |
+
return std::tie(args...);
|
| 15 |
+
}
|
| 16 |
+
};
|
| 17 |
+
|
| 18 |
+
template <typename KeyAccessor, typename ValueAccessor>
|
| 19 |
+
using CompositeRandomAccessorCPU =
|
| 20 |
+
CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfoCPU>;
|
| 21 |
+
|
| 22 |
+
template <typename Values, typename References>
|
| 23 |
+
void swap(
|
| 24 |
+
references_holder<Values, References> rh1,
|
| 25 |
+
references_holder<Values, References> rh2
|
| 26 |
+
) {
|
| 27 |
+
return std::swap(rh1.data(), rh2.data());
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
template <int N, typename Values, typename References>
|
| 31 |
+
auto get(references_holder<Values, References> rh) -> decltype(std::get<N>(rh.data())) {
|
| 32 |
+
return std::get<N>(rh.data());
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
} // namespace at::native
|
| 36 |
+
|
| 37 |
+
#else
|
| 38 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 39 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#include <utility>
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
namespace at::native {
|
| 7 |
+
|
| 8 |
+
namespace {
|
| 9 |
+
|
| 10 |
+
// operator_brackets_proxy is used in
|
| 11 |
+
// CompositeRandomAccessor in place of operator[].
|
| 12 |
+
// For some iterators, references returned by operator[]
|
| 13 |
+
// could become invalid, operator_brackets_proxy tries to
|
| 14 |
+
// resolve that by making accessor[n] to be equivalent to
|
| 15 |
+
// *(accessor + n).
|
| 16 |
+
template <typename Accessor>
|
| 17 |
+
class operator_brackets_proxy {
|
| 18 |
+
using reference = typename std::iterator_traits<Accessor>::reference;
|
| 19 |
+
using value_type = typename std::iterator_traits<Accessor>::value_type;
|
| 20 |
+
|
| 21 |
+
public:
|
| 22 |
+
C10_HOST_DEVICE
|
| 23 |
+
operator_brackets_proxy(Accessor const& accessor)
|
| 24 |
+
: accessor(accessor)
|
| 25 |
+
{}
|
| 26 |
+
|
| 27 |
+
C10_HOST_DEVICE
|
| 28 |
+
operator reference() {
|
| 29 |
+
return *accessor;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
C10_HOST_DEVICE
|
| 33 |
+
reference operator*() {
|
| 34 |
+
return *accessor;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
C10_HOST_DEVICE
|
| 38 |
+
operator_brackets_proxy& operator=(value_type const& val) {
|
| 39 |
+
*accessor = val;
|
| 40 |
+
return *this;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
private:
|
| 44 |
+
Accessor accessor;
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// references_holder is used as a surrogate for the
|
| 50 |
+
// references type from std::iterator_traits in CompositeRandomAccessor.
|
| 51 |
+
// It is assumed in CompositeRandomAccessor that
|
| 52 |
+
// References = tuple<Types&...>,
|
| 53 |
+
// Values = tuple<Types...> by default,
|
| 54 |
+
// but they could be anything as long as References could be
|
| 55 |
+
// cast to Values.
|
| 56 |
+
// If you plan to use it with STL, for example, you will need to
|
| 57 |
+
// define 'swap` and `get`(aka std::get) methods.
|
| 58 |
+
template <typename Values, typename References>
|
| 59 |
+
class references_holder {
|
| 60 |
+
public:
|
| 61 |
+
using values = Values;
|
| 62 |
+
using references = References;
|
| 63 |
+
|
| 64 |
+
C10_HOST_DEVICE
|
| 65 |
+
references_holder(references refs)
|
| 66 |
+
: refs{std::move(refs)}
|
| 67 |
+
{}
|
| 68 |
+
|
| 69 |
+
C10_HOST_DEVICE
|
| 70 |
+
operator references() {
|
| 71 |
+
return refs;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
C10_HOST_DEVICE
|
| 75 |
+
operator values() {
|
| 76 |
+
return refs;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
C10_HOST_DEVICE
|
| 80 |
+
references_holder& operator=(values vals) {
|
| 81 |
+
refs = vals;
|
| 82 |
+
return *this;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
C10_HOST_DEVICE
|
| 86 |
+
references& data() {
|
| 87 |
+
return refs;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
protected:
|
| 91 |
+
references refs;
|
| 92 |
+
};
|
| 93 |
+
|
| 94 |
+
// CompositeRandomAccessor is essentially a simplified version of
|
| 95 |
+
// a random access iterator over two random access iterators.
|
| 96 |
+
// TupleInfo should contain a variadic type `tuple`, and a method `tie`,
|
| 97 |
+
// which constructs a tuple of references from a variadic list of arguments.
|
| 98 |
+
template <typename KeyAccessor, typename ValueAccessor, typename TupleInfo>
|
| 99 |
+
class CompositeRandomAccessor {
|
| 100 |
+
using self_type = CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfo>;
|
| 101 |
+
|
| 102 |
+
using key_accessor_value_type =
|
| 103 |
+
typename std::iterator_traits<KeyAccessor>::value_type;
|
| 104 |
+
using value_accessor_value_type =
|
| 105 |
+
typename std::iterator_traits<ValueAccessor>::value_type;
|
| 106 |
+
using key_accessor_reference_type =
|
| 107 |
+
typename std::iterator_traits<KeyAccessor>::reference;
|
| 108 |
+
using value_accessor_reference_type =
|
| 109 |
+
typename std::iterator_traits<ValueAccessor>::reference;
|
| 110 |
+
|
| 111 |
+
using composite_value_type = typename TupleInfo::template tuple<
|
| 112 |
+
key_accessor_value_type,
|
| 113 |
+
value_accessor_value_type>;
|
| 114 |
+
using composite_reference = typename TupleInfo::template tuple<
|
| 115 |
+
key_accessor_reference_type,
|
| 116 |
+
value_accessor_reference_type>;
|
| 117 |
+
|
| 118 |
+
public:
|
| 119 |
+
using value_type = composite_value_type;
|
| 120 |
+
using reference = references_holder<composite_value_type, composite_reference>;
|
| 121 |
+
// Note that CompositeRandomAccessor does not hold key and values
|
| 122 |
+
// in a specific datastructure, which means that a pointer to a (key, value)
|
| 123 |
+
// is not defined. Hence we just use a pointer type of the KeyAccessor.
|
| 124 |
+
using pointer = typename std::iterator_traits<KeyAccessor>::pointer;
|
| 125 |
+
using difference_type = typename std::iterator_traits<KeyAccessor>::difference_type;
|
| 126 |
+
using iterator_category = std::random_access_iterator_tag;
|
| 127 |
+
|
| 128 |
+
C10_HOST_DEVICE
|
| 129 |
+
CompositeRandomAccessor() = default;
|
| 130 |
+
|
| 131 |
+
C10_HOST_DEVICE
|
| 132 |
+
CompositeRandomAccessor(KeyAccessor keys, ValueAccessor values)
|
| 133 |
+
: keys(keys), values(values)
|
| 134 |
+
{}
|
| 135 |
+
|
| 136 |
+
// Pointer-like operations {
|
| 137 |
+
C10_HOST_DEVICE
|
| 138 |
+
reference operator*() const {
|
| 139 |
+
return TupleInfo::tie(*keys, *values);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
// operator->() is supposed to return a pointer type.
|
| 143 |
+
// Since CompositeRandomAccessor does not hold pointers to pairs,
|
| 144 |
+
// we just return a pointer to a key.
|
| 145 |
+
C10_HOST_DEVICE
|
| 146 |
+
auto* operator->() const {
|
| 147 |
+
return keys.operator->();
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
C10_HOST_DEVICE
|
| 151 |
+
reference operator[](difference_type idx) {
|
| 152 |
+
return operator_brackets_proxy<self_type>(
|
| 153 |
+
CompositeRandomAccessor(keys + idx, values + idx)
|
| 154 |
+
);
|
| 155 |
+
}
|
| 156 |
+
// }
|
| 157 |
+
|
| 158 |
+
// Prefix/postfix increment/decrement {
|
| 159 |
+
C10_HOST_DEVICE
|
| 160 |
+
CompositeRandomAccessor& operator++() {
|
| 161 |
+
++keys;
|
| 162 |
+
++values;
|
| 163 |
+
return *this;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
C10_HOST_DEVICE
|
| 167 |
+
CompositeRandomAccessor operator++(int) {
|
| 168 |
+
CompositeRandomAccessor copy(*this);
|
| 169 |
+
++*this;
|
| 170 |
+
return copy;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
C10_HOST_DEVICE
|
| 174 |
+
CompositeRandomAccessor& operator--() {
|
| 175 |
+
--keys;
|
| 176 |
+
--values;
|
| 177 |
+
return *this;
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
C10_HOST_DEVICE
|
| 181 |
+
CompositeRandomAccessor operator--(int) {
|
| 182 |
+
CompositeRandomAccessor copy(*this);
|
| 183 |
+
--*this;
|
| 184 |
+
return copy;
|
| 185 |
+
}
|
| 186 |
+
// }
|
| 187 |
+
|
| 188 |
+
// Arithmetic operations {
|
| 189 |
+
C10_HOST_DEVICE
|
| 190 |
+
CompositeRandomAccessor& operator+=(difference_type offset) {
|
| 191 |
+
keys += offset;
|
| 192 |
+
values += offset;
|
| 193 |
+
return *this;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
C10_HOST_DEVICE
|
| 197 |
+
CompositeRandomAccessor operator+(difference_type offset) const {
|
| 198 |
+
return CompositeRandomAccessor(keys + offset, values + offset);
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
C10_HOST_DEVICE
|
| 202 |
+
friend CompositeRandomAccessor operator+(
|
| 203 |
+
difference_type offset,
|
| 204 |
+
const CompositeRandomAccessor& accessor
|
| 205 |
+
) {
|
| 206 |
+
return accessor + offset;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
C10_HOST_DEVICE
|
| 210 |
+
CompositeRandomAccessor& operator-=(difference_type offset) {
|
| 211 |
+
keys -= offset;
|
| 212 |
+
values -= offset;
|
| 213 |
+
return *this;
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
C10_HOST_DEVICE
|
| 217 |
+
CompositeRandomAccessor operator-(difference_type offset) const {
|
| 218 |
+
return CompositeRandomAccessor(keys - offset, values - offset);
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
C10_HOST_DEVICE
|
| 222 |
+
difference_type operator-(const CompositeRandomAccessor& other) const {
|
| 223 |
+
return keys - other.keys;
|
| 224 |
+
}
|
| 225 |
+
// }
|
| 226 |
+
|
| 227 |
+
// Comparison operators {
|
| 228 |
+
C10_HOST_DEVICE
|
| 229 |
+
bool operator==(const CompositeRandomAccessor& other) const {
|
| 230 |
+
return keys == other.keys;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
C10_HOST_DEVICE
|
| 234 |
+
bool operator!=(const CompositeRandomAccessor& other) const {
|
| 235 |
+
return keys != other.keys;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
C10_HOST_DEVICE
|
| 239 |
+
bool operator<(const CompositeRandomAccessor& other) const {
|
| 240 |
+
return keys < other.keys;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
C10_HOST_DEVICE
|
| 244 |
+
bool operator<=(const CompositeRandomAccessor& other) const {
|
| 245 |
+
return keys <= other.keys;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
C10_HOST_DEVICE
|
| 249 |
+
bool operator>(const CompositeRandomAccessor& other) const {
|
| 250 |
+
return keys > other.keys;
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
C10_HOST_DEVICE
|
| 254 |
+
bool operator>=(const CompositeRandomAccessor& other) const {
|
| 255 |
+
return keys >= other.keys;
|
| 256 |
+
}
|
| 257 |
+
// }
|
| 258 |
+
|
| 259 |
+
protected:
|
| 260 |
+
KeyAccessor keys;
|
| 261 |
+
ValueAccessor values;
|
| 262 |
+
};
|
| 263 |
+
|
| 264 |
+
} // namespace at::native
|
| 265 |
+
|
| 266 |
+
#else
|
| 267 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 268 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ConvUtils.h
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <ATen/TensorUtils.h>
|
| 5 |
+
#include <ATen/detail/CUDAHooksInterface.h>
|
| 6 |
+
#include <ATen/native/DispatchStub.h>
|
| 7 |
+
#include <c10/util/env.h>
|
| 8 |
+
#include <c10/util/irange.h>
|
| 9 |
+
|
| 10 |
+
#include <utility>
|
| 11 |
+
|
| 12 |
+
namespace at::native {
|
| 13 |
+
|
| 14 |
+
using conv_depthwise2d_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
|
| 15 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 16 |
+
at::IntArrayRef, at::IntArrayRef, std::array<bool, 2>);
|
| 17 |
+
DECLARE_DISPATCH(conv_depthwise2d_backward_fn, conv_depthwise2d_backward_stub)
|
| 18 |
+
using conv_depthwise3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 19 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 20 |
+
at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
|
| 21 |
+
DECLARE_DISPATCH(conv_depthwise3d_backward_fn, conv_depthwise3d_backward_stub)
|
| 22 |
+
using cudnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
|
| 23 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 24 |
+
at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
|
| 25 |
+
DECLARE_DISPATCH(cudnn_convolution_backward_fn, cudnn_convolution_backward_stub)
|
| 26 |
+
using mps_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 27 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 28 |
+
at::IntArrayRef, int64_t, std::array<bool,3>);
|
| 29 |
+
DECLARE_DISPATCH(mps_convolution_backward_fn, mps_convolution_backward_stub)
|
| 30 |
+
using cudnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
|
| 31 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 32 |
+
at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
|
| 33 |
+
DECLARE_DISPATCH(cudnn_convolution_transpose_backward_fn, cudnn_convolution_transpose_backward_stub)
|
| 34 |
+
using miopen_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 35 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 36 |
+
at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
|
| 37 |
+
DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_convolution_backward_stub)
|
| 38 |
+
using miopen_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 39 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 40 |
+
at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
|
| 41 |
+
DECLARE_DISPATCH(miopen_convolution_transpose_backward_fn, miopen_convolution_transpose_backward_stub)
|
| 42 |
+
using miopen_depthwise_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 43 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 44 |
+
at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
|
| 45 |
+
DECLARE_DISPATCH(miopen_depthwise_convolution_backward_fn, miopen_depthwise_convolution_backward_stub)
|
| 46 |
+
using mkldnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 47 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 48 |
+
at::IntArrayRef, int64_t, std::array<bool,3>);
|
| 49 |
+
DECLARE_DISPATCH(mkldnn_convolution_backward_fn, mkldnn_convolution_backward_stub)
|
| 50 |
+
using mkldnn_convolution_transpose_fn = Tensor(*)(const Tensor&, const Tensor&, const std::optional<Tensor>&,
|
| 51 |
+
IntArrayRef, IntArrayRef, IntArrayRef, IntArrayRef, int64_t);
|
| 52 |
+
DECLARE_DISPATCH(mkldnn_convolution_transpose_fn, mkldnn_convolution_transpose_stub)
|
| 53 |
+
using mkldnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 54 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 55 |
+
at::IntArrayRef, at::IntArrayRef, int64_t, std::array<bool,3>);
|
| 56 |
+
DECLARE_DISPATCH(mkldnn_convolution_transpose_backward_fn, mkldnn_convolution_transpose_backward_stub)
|
| 57 |
+
using slow_conv_dilated2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 58 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 59 |
+
at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
|
| 60 |
+
DECLARE_DISPATCH(slow_conv_dilated2d_backward_fn, slow_conv_dilated2d_backward_stub)
|
| 61 |
+
using slow_conv_dilated3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 62 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 63 |
+
at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
|
| 64 |
+
DECLARE_DISPATCH(slow_conv_dilated3d_backward_fn, slow_conv_dilated3d_backward_stub)
|
| 65 |
+
using slow_conv_transpose2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 66 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 67 |
+
at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
|
| 68 |
+
DECLARE_DISPATCH(slow_conv_transpose2d_backward_fn, slow_conv_transpose2d_backward_stub)
|
| 69 |
+
using slow_conv_transpose3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
|
| 70 |
+
const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
|
| 71 |
+
at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
|
| 72 |
+
DECLARE_DISPATCH(slow_conv_transpose3d_backward_fn, slow_conv_transpose3d_backward_stub)
|
| 73 |
+
|
| 74 |
+
namespace {
|
| 75 |
+
bool is_cudnnv8_heuristic_mode_b() {
|
| 76 |
+
static const bool is_cudnnv8_heuristic_mode_b = c10::utils::check_env("TORCH_CUDNN_USE_HEURISTIC_MODE_B") == true;
|
| 77 |
+
return is_cudnnv8_heuristic_mode_b;
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
inline bool cudnnv8_enabled_check_debug() {
|
| 82 |
+
static bool cudnnv8_flag = c10::utils::check_env("TORCH_CUDNN_V8_API_DISABLED") != true;
|
| 83 |
+
static bool cudnnv8_debug = c10::utils::check_env("TORCH_CUDNN_V8_API_DEBUG") == true;
|
| 84 |
+
static uint8_t cudnnv8_debugcount = 0;
|
| 85 |
+
if (cudnnv8_debug == 1 && cudnnv8_debugcount < 10) {
|
| 86 |
+
TORCH_WARN("TORCH_CUDNN_V8_DEBUG ON, V8 ON: ", cudnnv8_flag, " TORCH_CUDNN_USE_HEURISTIC_MODE B: ", is_cudnnv8_heuristic_mode_b());
|
| 87 |
+
cudnnv8_debugcount++;
|
| 88 |
+
}
|
| 89 |
+
return cudnnv8_flag == 1;
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
inline bool cudnnv8_use_heur_mode_b() {
|
| 93 |
+
return is_cudnnv8_heuristic_mode_b();
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// Keep in sync with py::enum_ in Module.cpp
|
| 97 |
+
enum class ConvBackend {
|
| 98 |
+
CudaDepthwise2d,
|
| 99 |
+
CudaDepthwise3d,
|
| 100 |
+
Cudnn,
|
| 101 |
+
CudnnTranspose,
|
| 102 |
+
Empty,
|
| 103 |
+
Miopen,
|
| 104 |
+
MiopenDepthwise,
|
| 105 |
+
MiopenTranspose,
|
| 106 |
+
Mkldnn,
|
| 107 |
+
MkldnnTranspose,
|
| 108 |
+
MkldnnEmpty,
|
| 109 |
+
NnpackSpatial,
|
| 110 |
+
Overrideable,
|
| 111 |
+
Slow2d,
|
| 112 |
+
Slow3d,
|
| 113 |
+
SlowDilated2d,
|
| 114 |
+
SlowDilated3d,
|
| 115 |
+
SlowTranspose2d,
|
| 116 |
+
SlowTranspose3d,
|
| 117 |
+
Winograd3x3Depthwise,
|
| 118 |
+
Xnnpack2d,
|
| 119 |
+
Mps,
|
| 120 |
+
MpsTranspose,
|
| 121 |
+
};
|
| 122 |
+
|
| 123 |
+
// Overload for selecting the convolution backend from the full set of convolution inputs.
|
| 124 |
+
// This overload is exposed to python for testing, etc.
|
| 125 |
+
TORCH_API ConvBackend select_conv_backend(
|
| 126 |
+
const Tensor& input, const Tensor& weight, const std::optional<Tensor>& bias_opt,
|
| 127 |
+
SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation,
|
| 128 |
+
bool transposed, SymIntArrayRef output_padding, c10::SymInt groups, const at::OptionalSymIntArrayRef bias_sizes_opt);
|
| 129 |
+
|
| 130 |
+
TORCH_API at::MemoryFormat _determine_backend_memory_format(const Tensor& input,
|
| 131 |
+
const Tensor& weight,
|
| 132 |
+
const ConvBackend backend);
|
| 133 |
+
|
| 134 |
+
// ---------------------------------------------------------------------
|
| 135 |
+
//
|
| 136 |
+
// Math
|
| 137 |
+
//
|
| 138 |
+
// ---------------------------------------------------------------------
|
| 139 |
+
|
| 140 |
+
constexpr int input_batch_size_dim = 0; // also grad_input
|
| 141 |
+
constexpr int input_channels_dim = 1;
|
| 142 |
+
constexpr int output_batch_size_dim = 0; // also grad_output
|
| 143 |
+
constexpr int output_channels_dim = 1;
|
| 144 |
+
constexpr int weight_output_channels_dim = 0;
|
| 145 |
+
constexpr int weight_input_channels_dim = 1;
|
| 146 |
+
|
| 147 |
+
// Often written as 2 + max_dim (extra dims for batch size and channels)
|
| 148 |
+
constexpr int max_dim = 3;
|
| 149 |
+
|
| 150 |
+
// ---------------------------------------------------------------------
|
| 151 |
+
//
|
| 152 |
+
// Checking
|
| 153 |
+
//
|
| 154 |
+
// ---------------------------------------------------------------------
|
| 155 |
+
|
| 156 |
+
// Used on pad, stride and dilation
|
| 157 |
+
static void check_args(CheckedFrom c, IntArrayRef args, size_t expected_size, const char* arg_name)
|
| 158 |
+
{
|
| 159 |
+
TORCH_CHECK(args.size() <= expected_size,
|
| 160 |
+
"Too many ", arg_name, " values (", args.size(), ") supplied, expecting ",
|
| 161 |
+
expected_size, " (while checking arguments for ", c, ")");
|
| 162 |
+
TORCH_CHECK(args.size() >= expected_size,
|
| 163 |
+
"Not enough ", arg_name, " values (", args.size(), ") supplied, expecting ",
|
| 164 |
+
expected_size, " (while checking arguments for ", c, ")");
|
| 165 |
+
|
| 166 |
+
auto num_negative_values = std::count_if(args.begin(), args.end(), [](int x){return x < 0;});
|
| 167 |
+
if (num_negative_values > 0){
|
| 168 |
+
std::stringstream ss;
|
| 169 |
+
ss << arg_name << " should be greater than zero but got (";
|
| 170 |
+
std::copy(args.begin(), args.end() - 1, std::ostream_iterator<int>(ss,", "));
|
| 171 |
+
ss << args.back() << ")" << " (while checking arguments for " << c << ')';
|
| 172 |
+
TORCH_CHECK(false, ss.str());
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
// NOTE [ Convolution checks ]
|
| 178 |
+
//
|
| 179 |
+
// NB: For many call sites, it is not strictly necessary to check all of
|
| 180 |
+
// these relationships (for example, for forward convolution, we compute
|
| 181 |
+
// the size of output ourselves, so we don't actually need to check
|
| 182 |
+
// output. However, writing a single function that does everything
|
| 183 |
+
// means we get to reuse it for both forwards and all backwards
|
| 184 |
+
// variants, even when the set of "real" inputs varies. The magic of
|
| 185 |
+
// relational computing!
|
| 186 |
+
//
|
| 187 |
+
// (There is one downside, which is that it is slightly harder to write
|
| 188 |
+
// error messages which are able to distinguish between real inputs
|
| 189 |
+
// (which the user can change) and computed inputs (which the user can
|
| 190 |
+
// only indirectly affect). It would be an interesting exercise to
|
| 191 |
+
// come up with a general framework to handle such situations.)
|
| 192 |
+
inline void convolution_shape_check(
|
| 193 |
+
CheckedFrom c,
|
| 194 |
+
const TensorGeometryArg& input, const TensorGeometryArg& weight, const TensorGeometryArg& output,
|
| 195 |
+
IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups)
|
| 196 |
+
{
|
| 197 |
+
check_args(c, padding, input->dim() - 2, "padding");
|
| 198 |
+
check_args(c, stride, padding.size(), "stride");
|
| 199 |
+
check_args(c, dilation, padding.size(), "dilation");
|
| 200 |
+
|
| 201 |
+
// Input
|
| 202 |
+
checkDimRange(c, input, 3, 6 /* exclusive */);
|
| 203 |
+
checkSize_symint(c, input, input_channels_dim, weight->size(1) * groups);
|
| 204 |
+
|
| 205 |
+
// Weight
|
| 206 |
+
checkSameDim(c, input, weight);
|
| 207 |
+
|
| 208 |
+
// TODO: check that output->size() matches output_sizes
|
| 209 |
+
// TODO: check that weight matches output->sizes()
|
| 210 |
+
checkSameDim(c, input, output);
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
// NB: conv_output_size and conv_input_size are not bijections,
|
| 214 |
+
// as conv_output_size loses information; this is why conv_input_size
|
| 215 |
+
// takes an extra output_padding argument to resolve the ambiguity.
|
| 216 |
+
|
| 217 |
+
template <typename T>
|
| 218 |
+
inline std::vector<T> _conv_output_size(
|
| 219 |
+
ArrayRef<T> input_size, ArrayRef<T> weight_size,
|
| 220 |
+
ArrayRef<T> padding, ArrayRef<T> stride, ArrayRef<T> dilation = ArrayRef<T>()
|
| 221 |
+
) {
|
| 222 |
+
// ASSERT(input_size.size() > 2)
|
| 223 |
+
// ASSERT(input_size.size() == weight_size.size())
|
| 224 |
+
bool has_dilation = !dilation.empty();
|
| 225 |
+
auto dim = input_size.size();
|
| 226 |
+
std::vector<T> output_size(dim);
|
| 227 |
+
output_size[0] = input_size[input_batch_size_dim];
|
| 228 |
+
output_size[1] = weight_size[weight_output_channels_dim];
|
| 229 |
+
for (const auto d : c10::irange(2, dim)) {
|
| 230 |
+
auto dilation_ = has_dilation ? dilation[d - 2] : 1;
|
| 231 |
+
auto kernel = dilation_ * (weight_size[d] - 1) + 1;
|
| 232 |
+
output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1;
|
| 233 |
+
}
|
| 234 |
+
return output_size;
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
inline std::vector<int64_t> conv_output_size(
|
| 238 |
+
IntArrayRef input_size, IntArrayRef weight_size,
|
| 239 |
+
IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
|
| 240 |
+
) {
|
| 241 |
+
return _conv_output_size(input_size, weight_size, padding, stride, dilation);
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
inline std::vector<c10::SymInt> conv_output_size(
|
| 245 |
+
SymIntArrayRef input_size, SymIntArrayRef weight_size,
|
| 246 |
+
SymIntArrayRef padding, SymIntArrayRef stride, SymIntArrayRef dilation = SymIntArrayRef()
|
| 247 |
+
) {
|
| 248 |
+
return _conv_output_size(input_size, weight_size, padding, stride, dilation);
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
template <typename T>
|
| 252 |
+
std::vector<T> _conv_input_size(
|
| 253 |
+
ArrayRef<T> output_size, ArrayRef<T> weight_size,
|
| 254 |
+
ArrayRef<T> padding, ArrayRef<T> output_padding, ArrayRef<T> stride, ArrayRef<T> dilation, T groups
|
| 255 |
+
) {
|
| 256 |
+
// ASSERT(output_size.size() > 2)
|
| 257 |
+
// ASSERT(output_size.size() == weight_size.size())
|
| 258 |
+
auto dim = output_size.size();
|
| 259 |
+
std::vector<T> input_size(dim);
|
| 260 |
+
input_size[0] = output_size[output_batch_size_dim];
|
| 261 |
+
input_size[1] = weight_size[weight_input_channels_dim] * groups;
|
| 262 |
+
for (const auto d : c10::irange(2, dim)) {
|
| 263 |
+
auto kernel = (weight_size[d] - 1) * dilation[d - 2] + 1;
|
| 264 |
+
input_size[d] = (output_size[d] - 1) * stride[d - 2] - (padding[d - 2] * 2) +
|
| 265 |
+
kernel + output_padding[d - 2];
|
| 266 |
+
}
|
| 267 |
+
return input_size;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
inline std::vector<c10::SymInt> conv_input_size(
|
| 271 |
+
SymIntArrayRef output_size, SymIntArrayRef weight_size,
|
| 272 |
+
SymIntArrayRef padding, SymIntArrayRef output_padding, SymIntArrayRef stride, SymIntArrayRef dilation, c10::SymInt groups
|
| 273 |
+
) {
|
| 274 |
+
return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, std::move(groups));
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
inline std::vector<int64_t> conv_input_size(
|
| 278 |
+
IntArrayRef output_size, IntArrayRef weight_size,
|
| 279 |
+
IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
|
| 280 |
+
) {
|
| 281 |
+
return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
template <typename T>
|
| 285 |
+
std::vector<T> _conv_weight_size(
|
| 286 |
+
ArrayRef<T> input_size, ArrayRef<T> output_size,
|
| 287 |
+
ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
|
| 288 |
+
) {
|
| 289 |
+
auto dim = input_size.size();
|
| 290 |
+
std::vector<T> weight_size(dim);
|
| 291 |
+
weight_size[0] = output_size[1];
|
| 292 |
+
weight_size[1] = input_size[1] / groups;
|
| 293 |
+
for (const auto d : c10::irange(2, dim)) {
|
| 294 |
+
auto kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2]
|
| 295 |
+
+ padding[d - 2] * 2 - output_padding[d - 2];
|
| 296 |
+
weight_size[d] = (kernel - 1) / dilation[d - 2] + 1;
|
| 297 |
+
}
|
| 298 |
+
return weight_size;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
inline std::vector<c10::SymInt> conv_weight_size(
|
| 302 |
+
SymIntArrayRef input_size, SymIntArrayRef output_size,
|
| 303 |
+
SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
|
| 304 |
+
) {
|
| 305 |
+
return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
inline std::vector<int64_t> conv_weight_size(
|
| 309 |
+
IntArrayRef input_size, IntArrayRef output_size,
|
| 310 |
+
IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
|
| 311 |
+
) {
|
| 312 |
+
return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
inline Tensor reshape_bias(int64_t dim, const Tensor& bias) {
|
| 316 |
+
std::vector<int64_t> shape(dim, 1);
|
| 317 |
+
shape[1] = -1;
|
| 318 |
+
return bias.reshape(shape);
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
inline at::MemoryFormat cudnn_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) {
|
| 322 |
+
// disable NHWC for float64 input.
|
| 323 |
+
if (!at::detail::getCUDAHooks().compiledWithCuDNN() ||
|
| 324 |
+
input.scalar_type() == at::kDouble ||
|
| 325 |
+
weight.scalar_type() == at::kDouble) {
|
| 326 |
+
return at::MemoryFormat::Contiguous;
|
| 327 |
+
}
|
| 328 |
+
long cudnn_version = at::detail::getCUDAHooks().versionCuDNN();
|
| 329 |
+
auto input_memory_format = input.suggest_memory_format();
|
| 330 |
+
auto weight_memory_format = weight.suggest_memory_format();
|
| 331 |
+
auto weight_ndim = weight.ndimension();
|
| 332 |
+
|
| 333 |
+
bool can_use_cudnn_channels_last_2d = (cudnn_version >= 7603) && (weight_ndim == 4) && (
|
| 334 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast) ||
|
| 335 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast)
|
| 336 |
+
);
|
| 337 |
+
if (can_use_cudnn_channels_last_2d) {
|
| 338 |
+
return at::MemoryFormat::ChannelsLast;
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
bool can_use_cudnn_channels_last_3d = (cudnn_version >= 8005) && (weight_ndim == 5) && (
|
| 342 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
|
| 343 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast3d)
|
| 344 |
+
);
|
| 345 |
+
if (can_use_cudnn_channels_last_3d) {
|
| 346 |
+
return at::MemoryFormat::ChannelsLast3d;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
return at::MemoryFormat::Contiguous;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
// controls whether emptyCache will be called following cudnn conv benchmarking
|
| 353 |
+
TORCH_API void _cudnn_set_conv_benchmark_empty_cache(bool enable);
|
| 354 |
+
TORCH_API bool _cudnn_get_conv_benchmark_empty_cache();
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
inline at::MemoryFormat miopen_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) {
|
| 358 |
+
// disable NHWC for float64 input.
|
| 359 |
+
if (!at::detail::getCUDAHooks().compiledWithMIOpen() ||
|
| 360 |
+
input.scalar_type() == at::kDouble ||
|
| 361 |
+
weight.scalar_type() == at::kDouble) {
|
| 362 |
+
return at::MemoryFormat::Contiguous;
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
// TODO: Remove PYTORCH_MIOPEN_SUGGEST_NHWC once ROCm officially supports NHWC in MIOpen
|
| 366 |
+
// See https://github.com/pytorch/pytorch/issues/64427.
|
| 367 |
+
// non static variable is used to be able to change environment variable in runtime for testing
|
| 368 |
+
// enabled by default for ROCm >= 7.0.0 with miopen 3.5
|
| 369 |
+
int miopen_version = detail::getCUDAHooks().compiledWithMIOpen() ? detail::getCUDAHooks().versionMIOpen() : 0;
|
| 370 |
+
bool is_miopen_3_5 = miopen_version >= 30500; // ROCm 7.0
|
| 371 |
+
bool suggest_nhwc = c10::utils::check_env("PYTORCH_MIOPEN_SUGGEST_NHWC").value_or(is_miopen_3_5);
|
| 372 |
+
|
| 373 |
+
auto input_memory_format = input.suggest_memory_format();
|
| 374 |
+
auto weight_memory_format = weight.suggest_memory_format();
|
| 375 |
+
auto weight_ndim = weight.ndimension();
|
| 376 |
+
|
| 377 |
+
bool can_use_miopen_channels_last_2d = suggest_nhwc && (weight_ndim == 4) && (
|
| 378 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast) ||
|
| 379 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast)
|
| 380 |
+
);
|
| 381 |
+
if (can_use_miopen_channels_last_2d) {
|
| 382 |
+
return at::MemoryFormat::ChannelsLast;
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
bool can_use_miopen_channels_last_3d = suggest_nhwc && (weight_ndim == 5) && (
|
| 386 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
|
| 387 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast3d)
|
| 388 |
+
);
|
| 389 |
+
if (can_use_miopen_channels_last_3d) {
|
| 390 |
+
return at::MemoryFormat::ChannelsLast3d;
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
return at::MemoryFormat::Contiguous;
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// deprecated, but to remove would be BC-breaking
|
| 397 |
+
inline bool miopen_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
|
| 398 |
+
return miopen_conv_suggest_memory_format(input, weight) != at::MemoryFormat::Contiguous;
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
inline bool mkldnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
|
| 402 |
+
|
| 403 |
+
// disable NHWC for float64 input.
|
| 404 |
+
if (input.scalar_type() == at::kDouble ||
|
| 405 |
+
weight.scalar_type() == at::kDouble) {
|
| 406 |
+
return false;
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
// disable NHWC for MkldnnCPU tensor.
|
| 410 |
+
if (input.is_mkldnn() || weight.is_mkldnn()) {
|
| 411 |
+
return false;
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
auto input_memory_format = input.suggest_memory_format();
|
| 415 |
+
auto weight_memory_format = weight.suggest_memory_format();
|
| 416 |
+
|
| 417 |
+
bool can_use_mkldnn_channels_last_2d =
|
| 418 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast) ||
|
| 419 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast);
|
| 420 |
+
|
| 421 |
+
bool can_use_mkldnn_channels_last_3d =
|
| 422 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
|
| 423 |
+
(weight_memory_format == at::MemoryFormat::ChannelsLast3d);
|
| 424 |
+
|
| 425 |
+
return can_use_mkldnn_channels_last_2d || can_use_mkldnn_channels_last_3d;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
inline bool thnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
|
| 429 |
+
|
| 430 |
+
auto input_memory_format = input.suggest_memory_format();
|
| 431 |
+
auto weight_memory_format = weight.suggest_memory_format();
|
| 432 |
+
|
| 433 |
+
bool can_use_thnn_channels_last_2d = input.device().is_cpu() && (
|
| 434 |
+
(input_memory_format == at::MemoryFormat::ChannelsLast) || (
|
| 435 |
+
weight_memory_format == at::MemoryFormat::ChannelsLast));
|
| 436 |
+
|
| 437 |
+
return can_use_thnn_channels_last_2d;
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
inline bool xpu_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
|
| 441 |
+
|
| 442 |
+
// check layout only for xpu tensor.
|
| 443 |
+
if (!input.is_xpu() || !weight.is_xpu()) {
|
| 444 |
+
return false;
|
| 445 |
+
}
|
| 446 |
+
if (!input.defined() || input.is_sparse()) {
|
| 447 |
+
// suggest channels_first
|
| 448 |
+
return false;
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
auto is_channel_last = [](const at::Tensor& t) {
|
| 452 |
+
auto fmt = t.suggest_memory_format();
|
| 453 |
+
return fmt == at::MemoryFormat::ChannelsLast || fmt == at::MemoryFormat::ChannelsLast3d;
|
| 454 |
+
};
|
| 455 |
+
return is_channel_last(input) || is_channel_last(weight);
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
inline bool mps_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
|
| 459 |
+
|
| 460 |
+
// check layout only for mps tensor.
|
| 461 |
+
if (!input.is_mps() || !weight.is_mps()) {
|
| 462 |
+
return false;
|
| 463 |
+
}
|
| 464 |
+
if (!input.defined() || input.is_sparse()) {
|
| 465 |
+
// suggest channels_first
|
| 466 |
+
return false;
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
auto is_channel_last = [](const at::Tensor& t) {
|
| 470 |
+
auto fmt = t.suggest_memory_format();
|
| 471 |
+
return fmt == at::MemoryFormat::ChannelsLast || fmt == at::MemoryFormat::ChannelsLast3d;
|
| 472 |
+
};
|
| 473 |
+
return is_channel_last(input) || is_channel_last(weight);
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
} // namespace at::native
|
| 477 |
+
|
| 478 |
+
#else
|
| 479 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 480 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ConvolutionMM3d.h
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#include <ATen/core/Tensor.h>
|
| 3 |
+
|
| 4 |
+
namespace at::native {
|
| 5 |
+
|
| 6 |
+
std::tuple<Tensor, Tensor, Tensor> slow_conv3d_backward_cpu(
|
| 7 |
+
const Tensor& grad_output,
|
| 8 |
+
const Tensor& self,
|
| 9 |
+
const Tensor& weight,
|
| 10 |
+
IntArrayRef kernel_size,
|
| 11 |
+
IntArrayRef stride,
|
| 12 |
+
IntArrayRef padding,
|
| 13 |
+
std::array<bool, 3> output_mask);
|
| 14 |
+
|
| 15 |
+
} // namespace at::native
|
| 16 |
+
|
| 17 |
+
#else
|
| 18 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 19 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Copy.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
|
| 6 |
+
namespace at {
|
| 7 |
+
|
| 8 |
+
class Tensor;
|
| 9 |
+
struct TensorIterator;
|
| 10 |
+
class TensorBase;
|
| 11 |
+
|
| 12 |
+
namespace native {
|
| 13 |
+
|
| 14 |
+
using copy_fn = void (*)(TensorIterator&, bool non_blocking);
|
| 15 |
+
|
| 16 |
+
DECLARE_DISPATCH(copy_fn, copy_stub)
|
| 17 |
+
|
| 18 |
+
TORCH_API void copy_ignoring_overlaps(const TensorBase &dst, const TensorBase &src);
|
| 19 |
+
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
| 22 |
+
|
| 23 |
+
#else
|
| 24 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 25 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
|
| 6 |
+
namespace at {
|
| 7 |
+
class Tensor;
|
| 8 |
+
|
| 9 |
+
namespace native {
|
| 10 |
+
|
| 11 |
+
using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d);
|
| 12 |
+
|
| 13 |
+
DECLARE_DISPATCH(cross_fn, cross_stub)
|
| 14 |
+
|
| 15 |
+
}} // namespace at::native
|
| 16 |
+
|
| 17 |
+
#else
|
| 18 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 19 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <vector>
|
| 6 |
+
|
| 7 |
+
#include <ATen/div_rtn.h>
|
| 8 |
+
#include <ATen/core/Tensor.h>
|
| 9 |
+
#include <c10/util/irange.h>
|
| 10 |
+
|
| 11 |
+
#define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \
|
| 12 |
+
TORCH_CHECK( \
|
| 13 |
+
T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \
|
| 14 |
+
"Need " #T " of dimension ", \
|
| 15 |
+
DIM, \
|
| 16 |
+
" and " #T ".size[", \
|
| 17 |
+
DIM_SIZE, \
|
| 18 |
+
"] == ", \
|
| 19 |
+
SIZE, \
|
| 20 |
+
" but got input to be of shape ", \
|
| 21 |
+
T.sizes())
|
| 22 |
+
|
| 23 |
+
namespace at::native::internal {
|
| 24 |
+
namespace {
|
| 25 |
+
inline bool all_positive(IntArrayRef& arr) {
|
| 26 |
+
return std::all_of(
|
| 27 |
+
arr.begin(), arr.end(), [](int64_t item) { return item > 0; });
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
inline bool all_nonnegative(std::vector<int64_t>& arr) {
|
| 31 |
+
return std::all_of(
|
| 32 |
+
arr.begin(), arr.end(), [](int64_t item) { return item >= 0; });
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
} // namespace
|
| 36 |
+
|
| 37 |
+
// calculate the rear part of output tensor sizes
|
| 38 |
+
template <int64_t dim>
|
| 39 |
+
std::vector<int64_t> get_output_size(
|
| 40 |
+
const Tensor& input,
|
| 41 |
+
IntArrayRef kernel_size,
|
| 42 |
+
IntArrayRef stride_size,
|
| 43 |
+
IntArrayRef pad_size,
|
| 44 |
+
IntArrayRef dilation_size) {
|
| 45 |
+
std::vector<int64_t> sizes;
|
| 46 |
+
for (const auto index : c10::irange(dim)) {
|
| 47 |
+
sizes.push_back(
|
| 48 |
+
div_rtn<int64_t>(
|
| 49 |
+
input.size(index + input.dim() - dim) + 2 * pad_size[index] -
|
| 50 |
+
(dilation_size[index] * (kernel_size[index] - 1) + 1),
|
| 51 |
+
stride_size[index]) +
|
| 52 |
+
1);
|
| 53 |
+
}
|
| 54 |
+
return sizes;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// calculate the sizes of output tensor
|
| 58 |
+
template <int64_t dim>
|
| 59 |
+
std::vector<int64_t> get_output_size(
|
| 60 |
+
const Tensor& input,
|
| 61 |
+
const Tensor& weight,
|
| 62 |
+
IntArrayRef kernel_size,
|
| 63 |
+
IntArrayRef stride_size,
|
| 64 |
+
IntArrayRef pad_size,
|
| 65 |
+
IntArrayRef dilation_size) {
|
| 66 |
+
auto output_size = get_output_size<dim>(
|
| 67 |
+
input, kernel_size, stride_size, pad_size, dilation_size);
|
| 68 |
+
output_size.insert(output_size.begin(), weight.size(0));
|
| 69 |
+
if (input.dim() == dim + 2) {
|
| 70 |
+
output_size.insert(output_size.begin(), input.size(0));
|
| 71 |
+
}
|
| 72 |
+
return output_size;
|
| 73 |
+
}
|
| 74 |
+
/*
|
| 75 |
+
slow_conv_dilated_shape_check - check user-input to dilated convolution
|
| 76 |
+
forward and backward functions.
|
| 77 |
+
*/
|
| 78 |
+
template <int64_t dim>
|
| 79 |
+
void slow_conv_dilated_shape_check(
|
| 80 |
+
const Tensor& input,
|
| 81 |
+
const Tensor& weight,
|
| 82 |
+
const Tensor& bias,
|
| 83 |
+
const Tensor& grad_output,
|
| 84 |
+
IntArrayRef kernel_size,
|
| 85 |
+
IntArrayRef stride_size,
|
| 86 |
+
IntArrayRef pad_size,
|
| 87 |
+
IntArrayRef dilation_size) {
|
| 88 |
+
/*
|
| 89 |
+
When the following tensors are defined:
|
| 90 |
+
|
| 91 |
+
bias, grad_weight, grad_output
|
| 92 |
+
|
| 93 |
+
then these are assumed to be contiguous without checking
|
| 94 |
+
because of these tensors are made contiguous by calling
|
| 95 |
+
.contiguous() method or by resizing of zero-sized tensors in
|
| 96 |
+
forward/backward functions.
|
| 97 |
+
|
| 98 |
+
When grad_weight is defined then it is assumed without
|
| 99 |
+
checking to have the same shape as weight, see backward
|
| 100 |
+
functions.
|
| 101 |
+
*/
|
| 102 |
+
// Check size arguments
|
| 103 |
+
TORCH_CHECK(
|
| 104 |
+
kernel_size.size() == dim,
|
| 105 |
+
"kernel sizes length should be ",
|
| 106 |
+
dim,
|
| 107 |
+
", but got ",
|
| 108 |
+
kernel_size.size());
|
| 109 |
+
TORCH_CHECK(
|
| 110 |
+
stride_size.size() == dim,
|
| 111 |
+
"strides length should be ",
|
| 112 |
+
dim,
|
| 113 |
+
", but got ",
|
| 114 |
+
stride_size.size());
|
| 115 |
+
TORCH_CHECK(
|
| 116 |
+
dilation_size.size() == dim,
|
| 117 |
+
"dilations length should be ",
|
| 118 |
+
dim,
|
| 119 |
+
", but got ",
|
| 120 |
+
dilation_size.size());
|
| 121 |
+
TORCH_CHECK(
|
| 122 |
+
pad_size.size() == dim,
|
| 123 |
+
"pads length should be ",
|
| 124 |
+
dim,
|
| 125 |
+
", but got ",
|
| 126 |
+
pad_size.size());
|
| 127 |
+
|
| 128 |
+
TORCH_CHECK(
|
| 129 |
+
all_positive(kernel_size),
|
| 130 |
+
"kernel size should be greater than zero, but got ",
|
| 131 |
+
kernel_size);
|
| 132 |
+
TORCH_CHECK(
|
| 133 |
+
all_positive(stride_size),
|
| 134 |
+
"stride should be greater than zero, but got ",
|
| 135 |
+
stride_size);
|
| 136 |
+
TORCH_CHECK(
|
| 137 |
+
all_positive(dilation_size),
|
| 138 |
+
"dilation should be greater than zero, but got ",
|
| 139 |
+
dilation_size);
|
| 140 |
+
|
| 141 |
+
// check input
|
| 142 |
+
TORCH_CHECK(input.defined(), "input must be defined");
|
| 143 |
+
bool is_batch = input.dim() == dim + 2;
|
| 144 |
+
int64_t n = (is_batch ? 2 : 1);
|
| 145 |
+
int64_t ndim = n + dim;
|
| 146 |
+
if (!is_batch) {
|
| 147 |
+
// input dim has to be dim + 1 if not batched
|
| 148 |
+
TORCH_CHECK(
|
| 149 |
+
input.dim() == dim + 1,
|
| 150 |
+
"input must be 4D or 5D tensor but got ",
|
| 151 |
+
input.dim(),
|
| 152 |
+
"D tensor");
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
// check output sizes
|
| 156 |
+
auto output_size = get_output_size<dim>(
|
| 157 |
+
input, kernel_size, stride_size, pad_size, dilation_size);
|
| 158 |
+
|
| 159 |
+
TORCH_CHECK(
|
| 160 |
+
all_nonnegative(output_size),
|
| 161 |
+
"calculated output size ",
|
| 162 |
+
output_size,
|
| 163 |
+
" is too small (all sizes must be non-negative)");
|
| 164 |
+
|
| 165 |
+
// check weight
|
| 166 |
+
TORCH_CHECK(weight.defined(), "weight must be defined");
|
| 167 |
+
TORCH_CHECK(
|
| 168 |
+
weight.dim() == dim + 2,
|
| 169 |
+
"weight must be ",
|
| 170 |
+
dim + 2,
|
| 171 |
+
"D tensor but got ",
|
| 172 |
+
weight.dim(),
|
| 173 |
+
"D tensor dim=",
|
| 174 |
+
dim);
|
| 175 |
+
TORCH_CHECK(
|
| 176 |
+
weight.sizes().slice(2) == kernel_size,
|
| 177 |
+
"weight[2:] shape ",
|
| 178 |
+
weight.sizes().slice(2),
|
| 179 |
+
" must be equal to kernel_size ",
|
| 180 |
+
kernel_size);
|
| 181 |
+
|
| 182 |
+
TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1));
|
| 183 |
+
|
| 184 |
+
// check bias when present
|
| 185 |
+
if (bias.defined()) {
|
| 186 |
+
TORCH_CHECK(
|
| 187 |
+
bias.dim() == 1,
|
| 188 |
+
"bias must be 1D tensor but got ",
|
| 189 |
+
bias.dim(),
|
| 190 |
+
"D tensor");
|
| 191 |
+
TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0));
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
// check grad_output when present
|
| 195 |
+
if (grad_output.defined()) {
|
| 196 |
+
TORCH_CHECK(
|
| 197 |
+
grad_output.dim() == ndim,
|
| 198 |
+
"grad_output must be ",
|
| 199 |
+
ndim,
|
| 200 |
+
"D tensor but got ",
|
| 201 |
+
grad_output.dim(),
|
| 202 |
+
"D tensor");
|
| 203 |
+
if (is_batch) {
|
| 204 |
+
TORCH_CHECK(
|
| 205 |
+
grad_output.size(0) == input.size(0),
|
| 206 |
+
"grad_output.size(0)=",
|
| 207 |
+
grad_output.size(0),
|
| 208 |
+
" must be input.size(0)=",
|
| 209 |
+
input.size(0));
|
| 210 |
+
}
|
| 211 |
+
TORCH_CHECK(
|
| 212 |
+
grad_output.size(n - 1) == weight.size(0),
|
| 213 |
+
"grad_output.size(",
|
| 214 |
+
n - 1,
|
| 215 |
+
")=",
|
| 216 |
+
grad_output.size(n - 1),
|
| 217 |
+
" must be weight.size(0)=",
|
| 218 |
+
weight.size(0));
|
| 219 |
+
TORCH_CHECK(
|
| 220 |
+
grad_output.sizes().slice(n) == output_size,
|
| 221 |
+
"grad_output[",
|
| 222 |
+
n,
|
| 223 |
+
":] shape",
|
| 224 |
+
grad_output.sizes().slice(n),
|
| 225 |
+
" must be equal to output size ",
|
| 226 |
+
output_size);
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
} // namespace at::native::internal
|
| 231 |
+
|
| 232 |
+
#else
|
| 233 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 234 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <c10/core/DeviceType.h>
|
| 5 |
+
#include <c10/macros/Macros.h>
|
| 6 |
+
|
| 7 |
+
#include <atomic>
|
| 8 |
+
#include <utility>
|
| 9 |
+
#include <variant>
|
| 10 |
+
|
| 11 |
+
// Implements instruction set specific function dispatch.
|
| 12 |
+
//
|
| 13 |
+
// Kernels that may make use of specialized instruction sets (e.g. AVX2) are
|
| 14 |
+
// compiled multiple times with different compiler flags (e.g. -mavx2). A
|
| 15 |
+
// DispatchStub contains a table of function pointers for a kernel. At runtime,
|
| 16 |
+
// the fastest available kernel is chosen based on the features reported by
|
| 17 |
+
// cpuinfo.
|
| 18 |
+
//
|
| 19 |
+
// Example:
|
| 20 |
+
//
|
| 21 |
+
// In native/MyKernel.h:
|
| 22 |
+
// using fn_type = void(*)(const Tensor& x);
|
| 23 |
+
// DECLARE_DISPATCH(fn_type, stub)
|
| 24 |
+
//
|
| 25 |
+
// In native/MyKernel.cpp
|
| 26 |
+
// DEFINE_DISPATCH(stub);
|
| 27 |
+
//
|
| 28 |
+
// In native/cpu/MyKernel.cpp:
|
| 29 |
+
// namespace {
|
| 30 |
+
// // use anonymous namespace so that different cpu versions won't conflict
|
| 31 |
+
// void kernel(const Tensor& x) { ... }
|
| 32 |
+
// }
|
| 33 |
+
// REGISTER_DISPATCH(stub, &kernel);
|
| 34 |
+
//
|
| 35 |
+
// To call:
|
| 36 |
+
// stub(kCPU, tensor);
|
| 37 |
+
//
|
| 38 |
+
// TODO: CPU instruction set selection should be folded into whatever
|
| 39 |
+
// the main dispatch mechanism is.
|
| 40 |
+
//
|
| 41 |
+
// Supported device types for registration:
|
| 42 |
+
// - CPU: Central Processing Unit
|
| 43 |
+
// - CUDA: NVIDIA GPUs
|
| 44 |
+
// - HIP: AMD GPUs
|
| 45 |
+
// - MPS: Apple Silicon GPUs (Metal Performance Shaders)
|
| 46 |
+
// - MTIA: Meta Training and Inference Devices
|
| 47 |
+
// - XPU: Intel GPUs
|
| 48 |
+
// - HPU: Reserved for HPU (Intel Gaudi) device types
|
| 49 |
+
// - PrivateUse1: Reserved for private/custom device types
|
| 50 |
+
//
|
| 51 |
+
// If you want to update the list of supported devices, add a new dispatch_ptr
|
| 52 |
+
// member in DispatchStubImpl.h and update the get_call_ptr switch.
|
| 53 |
+
// As well you will need to update the inlined list in 'is_device_supported`
|
| 54 |
+
//
|
| 55 |
+
//
|
| 56 |
+
// ignore warnings about DispatchStub::DEFAULT, AVX, AVX2 defined elsewhere
|
| 57 |
+
C10_CLANG_DIAGNOSTIC_PUSH()
|
| 58 |
+
C10_CLANG_DIAGNOSTIC_IGNORE("-Wundefined-var-template")
|
| 59 |
+
|
| 60 |
+
namespace at::native {
|
| 61 |
+
|
| 62 |
+
enum class CPUCapability {
|
| 63 |
+
DEFAULT = 0,
|
| 64 |
+
#if defined(HAVE_VSX_CPU_DEFINITION)
|
| 65 |
+
VSX = 1,
|
| 66 |
+
#elif defined(HAVE_ZVECTOR_CPU_DEFINITION)
|
| 67 |
+
ZVECTOR = 1,
|
| 68 |
+
#elif defined(HAVE_SVE256_CPU_DEFINITION) && defined(HAVE_ARM_BF16_CPU_DEFINITION)
|
| 69 |
+
SVE256 = 1,
|
| 70 |
+
#else
|
| 71 |
+
AVX2 = 1,
|
| 72 |
+
AVX512 = 2,
|
| 73 |
+
#endif
|
| 74 |
+
NUM_OPTIONS
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
// Enum for error types
|
| 78 |
+
enum class ErrorType {
|
| 79 |
+
MissingDeviceKernel,
|
| 80 |
+
DeviceNotSupported
|
| 81 |
+
};
|
| 82 |
+
|
| 83 |
+
// Alias for the return type using std::variant
|
| 84 |
+
using DispatchResult = std::variant<void*, ErrorType>;
|
| 85 |
+
|
| 86 |
+
CPUCapability get_cpu_capability();
|
| 87 |
+
|
| 88 |
+
template <typename FnPtr, typename T>
|
| 89 |
+
struct DispatchStub;
|
| 90 |
+
|
| 91 |
+
/**
|
| 92 |
+
* The sole purpose of this class is to outline methods that don't need to be
|
| 93 |
+
* specialized or otherwise inlined and duplicated (by the compiler due to
|
| 94 |
+
* template expansion), since it causes size bloat if there are a significant
|
| 95 |
+
* number of specialization of the DispatchStub<> class.
|
| 96 |
+
*/
|
| 97 |
+
struct TORCH_API DispatchStubImpl {
|
| 98 |
+
|
| 99 |
+
// The DispatchStubImpl::try_get_call_ptr() method is used to get the call
|
| 100 |
+
// pointer for a given device type. If the call pointer is not found,
|
| 101 |
+
// DispatchStubImpl::try_get_call_ptr() returns an ErrorType.
|
| 102 |
+
// The main difference between try_get_call_ptr() and get_call_ptr() is that
|
| 103 |
+
// try_get_call_ptr() will return the ErrorType and not raise an exception.
|
| 104 |
+
DispatchResult try_get_call_ptr(
|
| 105 |
+
c10::DeviceType device_type
|
| 106 |
+
, void *DEFAULT
|
| 107 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 108 |
+
, void *AVX512
|
| 109 |
+
#endif
|
| 110 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 111 |
+
, void *AVX2
|
| 112 |
+
#endif
|
| 113 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 114 |
+
, void *VSX
|
| 115 |
+
#endif
|
| 116 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 117 |
+
, void *ZVECTOR
|
| 118 |
+
#endif
|
| 119 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 120 |
+
, void *SVE256
|
| 121 |
+
#endif
|
| 122 |
+
);
|
| 123 |
+
|
| 124 |
+
// Analogous to try_get_call_ptr(), but it will return the ErrorType and not
|
| 125 |
+
// raise an exception.
|
| 126 |
+
DispatchResult try_choose_cpu_impl(
|
| 127 |
+
void *DEFAULT
|
| 128 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 129 |
+
, void *AVX512
|
| 130 |
+
#endif
|
| 131 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 132 |
+
, void *AVX2
|
| 133 |
+
#endif
|
| 134 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 135 |
+
, void *VSX
|
| 136 |
+
#endif
|
| 137 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 138 |
+
, void *ZVECTOR
|
| 139 |
+
#endif
|
| 140 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 141 |
+
, void *SVE256
|
| 142 |
+
#endif
|
| 143 |
+
);
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
void* get_call_ptr(
|
| 147 |
+
c10::DeviceType device_type
|
| 148 |
+
, void *DEFAULT
|
| 149 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 150 |
+
, void *AVX512
|
| 151 |
+
#endif
|
| 152 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 153 |
+
, void *AVX2
|
| 154 |
+
#endif
|
| 155 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 156 |
+
, void *VSX
|
| 157 |
+
#endif
|
| 158 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 159 |
+
, void *ZVECTOR
|
| 160 |
+
#endif
|
| 161 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 162 |
+
, void *SVE256
|
| 163 |
+
#endif
|
| 164 |
+
);
|
| 165 |
+
|
| 166 |
+
/**
|
| 167 |
+
* The CPU Dispatch actual method is chosen in decreasing order of preference by
|
| 168 |
+
* DispatchStubImpl::choose_cpu_impl() in case none is found by
|
| 169 |
+
* DispatchStubImpl::get_call_ptr() in cpu_dispatch_ptr.
|
| 170 |
+
*/
|
| 171 |
+
void* choose_cpu_impl(
|
| 172 |
+
void *DEFAULT
|
| 173 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 174 |
+
, void *AVX512
|
| 175 |
+
#endif
|
| 176 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 177 |
+
, void *AVX2
|
| 178 |
+
#endif
|
| 179 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 180 |
+
, void *VSX
|
| 181 |
+
#endif
|
| 182 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 183 |
+
, void *ZVECTOR
|
| 184 |
+
#endif
|
| 185 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 186 |
+
, void *SVE256
|
| 187 |
+
#endif
|
| 188 |
+
);
|
| 189 |
+
|
| 190 |
+
// Fixing dispatch error in Windows debug builds.
|
| 191 |
+
// See https://github.com/pytorch/pytorch/issues/22681 for more details.
|
| 192 |
+
#if defined(_MSC_VER) && defined(_DEBUG)
|
| 193 |
+
std::atomic<void*> cpu_dispatch_ptr;
|
| 194 |
+
void* cuda_dispatch_ptr;
|
| 195 |
+
void* hip_dispatch_ptr;
|
| 196 |
+
void* mps_dispatch_ptr;
|
| 197 |
+
void* mtia_dispatch_ptr;
|
| 198 |
+
#if defined(USE_XPU)
|
| 199 |
+
void* xpu_dispatch_ptr;
|
| 200 |
+
#endif
|
| 201 |
+
void* hpu_dispatch_ptr;
|
| 202 |
+
void* privateuse1_dispatch_ptr;
|
| 203 |
+
#else
|
| 204 |
+
std::atomic<void*> cpu_dispatch_ptr{nullptr};
|
| 205 |
+
void* cuda_dispatch_ptr = nullptr;
|
| 206 |
+
void* hip_dispatch_ptr = nullptr;
|
| 207 |
+
void* mps_dispatch_ptr = nullptr;
|
| 208 |
+
void* mtia_dispatch_ptr = nullptr;
|
| 209 |
+
#if defined(USE_XPU)
|
| 210 |
+
void* xpu_dispatch_ptr = nullptr;
|
| 211 |
+
#endif
|
| 212 |
+
void* hpu_dispatch_ptr = nullptr;
|
| 213 |
+
void* privateuse1_dispatch_ptr = nullptr;
|
| 214 |
+
#endif
|
| 215 |
+
};
|
| 216 |
+
|
| 217 |
+
template <typename rT, typename T, typename... Args>
|
| 218 |
+
struct DispatchStub<rT (*)(Args...), T> {
|
| 219 |
+
using FnPtr = rT (*) (Args...);
|
| 220 |
+
|
| 221 |
+
DispatchStub() = default;
|
| 222 |
+
DispatchStub(const DispatchStub&) = delete;
|
| 223 |
+
DispatchStub& operator=(const DispatchStub&) = delete;
|
| 224 |
+
|
| 225 |
+
private:
|
| 226 |
+
FnPtr get_call_ptr(const c10::DeviceType device_type) {
|
| 227 |
+
return reinterpret_cast<FnPtr>(
|
| 228 |
+
impl.get_call_ptr(device_type
|
| 229 |
+
, reinterpret_cast<void*>(DEFAULT)
|
| 230 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 231 |
+
, reinterpret_cast<void*>(AVX512)
|
| 232 |
+
#endif
|
| 233 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 234 |
+
, reinterpret_cast<void*>(AVX2)
|
| 235 |
+
#endif
|
| 236 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 237 |
+
, reinterpret_cast<void*>(VSX)
|
| 238 |
+
#endif
|
| 239 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 240 |
+
, reinterpret_cast<void*>(ZVECTOR)
|
| 241 |
+
#endif
|
| 242 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 243 |
+
, reinterpret_cast<void*>(SVE256)
|
| 244 |
+
#endif
|
| 245 |
+
)
|
| 246 |
+
);
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
public:
|
| 250 |
+
template <typename... ArgTypes>
|
| 251 |
+
rT operator()(c10::DeviceType device_type, ArgTypes&&... args) {
|
| 252 |
+
FnPtr call_ptr = get_call_ptr(device_type);
|
| 253 |
+
return (*call_ptr)(std::forward<ArgTypes>(args)...);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
void set_cuda_dispatch_ptr(FnPtr fn_ptr) {
|
| 257 |
+
impl.cuda_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
#if defined(USE_XPU)
|
| 261 |
+
void set_xpu_dispatch_ptr(FnPtr fn_ptr){
|
| 262 |
+
impl.xpu_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 263 |
+
}
|
| 264 |
+
#endif
|
| 265 |
+
|
| 266 |
+
void set_hpu_dispatch_ptr(FnPtr fn_ptr) {
|
| 267 |
+
impl.hpu_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
void set_hip_dispatch_ptr(FnPtr fn_ptr) {
|
| 271 |
+
impl.hip_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
void set_mps_dispatch_ptr(FnPtr fn_ptr) {
|
| 275 |
+
impl.mps_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
void set_mtia_dispatch_ptr(FnPtr fn_ptr) {
|
| 279 |
+
impl.mtia_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
void set_privateuse1_dispatch_ptr(FnPtr fn_ptr) {
|
| 283 |
+
impl.privateuse1_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
// Returns true if the dispatcher has a kernel registered for this device
|
| 287 |
+
// type.
|
| 288 |
+
bool is_device_supported(const c10::DeviceType device_type) {
|
| 289 |
+
auto result = impl.try_get_call_ptr(device_type
|
| 290 |
+
, reinterpret_cast<void*>(DEFAULT)
|
| 291 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 292 |
+
, reinterpret_cast<void*>(AVX512)
|
| 293 |
+
#endif
|
| 294 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 295 |
+
, reinterpret_cast<void*>(AVX2)
|
| 296 |
+
#endif
|
| 297 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 298 |
+
, reinterpret_cast<void*>(VSX)
|
| 299 |
+
#endif
|
| 300 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 301 |
+
, reinterpret_cast<void*>(ZVECTOR)
|
| 302 |
+
#endif
|
| 303 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 304 |
+
, reinterpret_cast<void*>(SVE256)
|
| 305 |
+
#endif
|
| 306 |
+
);
|
| 307 |
+
if (std::holds_alternative<ErrorType>(result)){
|
| 308 |
+
return false;
|
| 309 |
+
}
|
| 310 |
+
return true;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
static TORCH_API FnPtr DEFAULT;
|
| 314 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 315 |
+
static TORCH_API FnPtr AVX512;
|
| 316 |
+
#endif
|
| 317 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 318 |
+
static TORCH_API FnPtr AVX2;
|
| 319 |
+
#endif
|
| 320 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 321 |
+
static TORCH_API FnPtr VSX;
|
| 322 |
+
#endif
|
| 323 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 324 |
+
static TORCH_API FnPtr ZVECTOR;
|
| 325 |
+
#endif
|
| 326 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 327 |
+
static TORCH_API FnPtr SVE256;
|
| 328 |
+
#endif
|
| 329 |
+
private:
|
| 330 |
+
DispatchStubImpl impl;
|
| 331 |
+
};
|
| 332 |
+
|
| 333 |
+
namespace {
|
| 334 |
+
template <typename DispatchStub>
|
| 335 |
+
struct RegisterCUDADispatch {
|
| 336 |
+
RegisterCUDADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
|
| 337 |
+
stub.set_cuda_dispatch_ptr(value);
|
| 338 |
+
}
|
| 339 |
+
};
|
| 340 |
+
|
| 341 |
+
template <typename DispatchStub>
|
| 342 |
+
struct RegisterXPUDispatch {
|
| 343 |
+
RegisterXPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){
|
| 344 |
+
stub.set_xpu_dispatch_ptr(value);
|
| 345 |
+
}
|
| 346 |
+
};
|
| 347 |
+
|
| 348 |
+
template <typename DispatchStub>
|
| 349 |
+
struct RegisterHPUDispatch {
|
| 350 |
+
RegisterHPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){
|
| 351 |
+
stub.set_hpu_dispatch_ptr(value);
|
| 352 |
+
}
|
| 353 |
+
};
|
| 354 |
+
|
| 355 |
+
template <typename DispatchStub>
|
| 356 |
+
struct RegisterMPSDispatch {
|
| 357 |
+
RegisterMPSDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
|
| 358 |
+
stub.set_mps_dispatch_ptr(value);
|
| 359 |
+
}
|
| 360 |
+
};
|
| 361 |
+
|
| 362 |
+
template <typename DispatchStub>
|
| 363 |
+
struct RegisterHIPDispatch {
|
| 364 |
+
RegisterHIPDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
|
| 365 |
+
// TODO: make this point at hip_dispatch_ptr
|
| 366 |
+
stub.set_cuda_dispatch_ptr(value);
|
| 367 |
+
}
|
| 368 |
+
};
|
| 369 |
+
|
| 370 |
+
template <typename DispatchStub>
|
| 371 |
+
struct RegisterMTIADispatch {
|
| 372 |
+
RegisterMTIADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
|
| 373 |
+
stub.set_mtia_dispatch_ptr(value);
|
| 374 |
+
}
|
| 375 |
+
};
|
| 376 |
+
|
| 377 |
+
template <typename DispatchStub>
|
| 378 |
+
struct RegisterPRIVATEUSE1Dispatch {
|
| 379 |
+
RegisterPRIVATEUSE1Dispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
|
| 380 |
+
stub.set_privateuse1_dispatch_ptr(value);
|
| 381 |
+
}
|
| 382 |
+
};
|
| 383 |
+
|
| 384 |
+
} // anonymous namespace
|
| 385 |
+
// Compiler will complain if you put things like std::tuple<Tensor, Tensor> in
|
| 386 |
+
// the `fn` argument of DECLARE_DISPATCH. Some possible workarounds, e.g.,
|
| 387 |
+
// adding parentheses and using helper struct to get rid of the parentheses, do
|
| 388 |
+
// not work with MSVC. So do a `using`-declaration if you need to pass in such
|
| 389 |
+
// `fn`, e.g., grid_sampler_2d_backward_cpu_kernel in GridSampleKernel.h.
|
| 390 |
+
#define DECLARE_DISPATCH(fn, name) \
|
| 391 |
+
struct name##_DECLARE_DISPATCH_type : DispatchStub<fn, name##_DECLARE_DISPATCH_type> { \
|
| 392 |
+
name##_DECLARE_DISPATCH_type() = default; \
|
| 393 |
+
name##_DECLARE_DISPATCH_type(const name##_DECLARE_DISPATCH_type&) = delete; \
|
| 394 |
+
name##_DECLARE_DISPATCH_type& operator=(const name##_DECLARE_DISPATCH_type&) = delete; \
|
| 395 |
+
name##_DECLARE_DISPATCH_type(name##_DECLARE_DISPATCH_type&&) = delete; \
|
| 396 |
+
name##_DECLARE_DISPATCH_type& operator=(name##_DECLARE_DISPATCH_type&&) = delete; \
|
| 397 |
+
~name##_DECLARE_DISPATCH_type() = default; \
|
| 398 |
+
}; \
|
| 399 |
+
extern TORCH_API struct name##_DECLARE_DISPATCH_type name;
|
| 400 |
+
|
| 401 |
+
#define DEFINE_DISPATCH(name) struct name##_DECLARE_DISPATCH_type name
|
| 402 |
+
|
| 403 |
+
#define REGISTER_ARCH_DISPATCH(name, arch, fn) \
|
| 404 |
+
template <> name##_DECLARE_DISPATCH_type::FnPtr TORCH_API DispatchStub<name##_DECLARE_DISPATCH_type::FnPtr, struct name##_DECLARE_DISPATCH_type>::arch = fn;
|
| 405 |
+
|
| 406 |
+
#ifdef HAVE_AVX512_CPU_DEFINITION
|
| 407 |
+
#define REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX512, fn)
|
| 408 |
+
#else
|
| 409 |
+
#define REGISTER_AVX512_DISPATCH(name, fn)
|
| 410 |
+
#endif
|
| 411 |
+
|
| 412 |
+
#ifdef HAVE_AVX2_CPU_DEFINITION
|
| 413 |
+
#define REGISTER_AVX2_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX2, fn)
|
| 414 |
+
#else
|
| 415 |
+
#define REGISTER_AVX2_DISPATCH(name, fn)
|
| 416 |
+
#endif
|
| 417 |
+
|
| 418 |
+
#ifdef HAVE_VSX_CPU_DEFINITION
|
| 419 |
+
#define REGISTER_VSX_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, VSX, fn)
|
| 420 |
+
#else
|
| 421 |
+
#define REGISTER_VSX_DISPATCH(name, fn)
|
| 422 |
+
#endif
|
| 423 |
+
|
| 424 |
+
#ifdef HAVE_ZVECTOR_CPU_DEFINITION
|
| 425 |
+
#define REGISTER_ZVECTOR_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, ZVECTOR, fn)
|
| 426 |
+
#else
|
| 427 |
+
#define REGISTER_ZVECTOR_DISPATCH(name, fn)
|
| 428 |
+
#endif
|
| 429 |
+
|
| 430 |
+
#ifdef HAVE_SVE256_CPU_DEFINITION
|
| 431 |
+
#define REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, SVE256, fn)
|
| 432 |
+
#else
|
| 433 |
+
#define REGISTER_SVE256_DISPATCH(name, fn)
|
| 434 |
+
#endif
|
| 435 |
+
|
| 436 |
+
// Macro to register the same kernel for all CPU arch types. This is useful
|
| 437 |
+
// if a kernel does not benefit from being recompiled across different arch types.
|
| 438 |
+
#define REGISTER_ALL_CPU_DISPATCH(name, fn) \
|
| 439 |
+
REGISTER_ARCH_DISPATCH(name, DEFAULT, fn) \
|
| 440 |
+
REGISTER_AVX512_DISPATCH(name, fn) \
|
| 441 |
+
REGISTER_AVX2_DISPATCH(name, fn) \
|
| 442 |
+
REGISTER_VSX_DISPATCH(name, fn) \
|
| 443 |
+
REGISTER_ZVECTOR_DISPATCH(name, fn) \
|
| 444 |
+
REGISTER_SVE256_DISPATCH(name, fn)
|
| 445 |
+
|
| 446 |
+
#define REGISTER_NO_CPU_DISPATCH(name) \
|
| 447 |
+
REGISTER_ALL_CPU_DISPATCH(name, nullptr)
|
| 448 |
+
|
| 449 |
+
#define REGISTER_CUDA_DISPATCH(name, fn) \
|
| 450 |
+
static RegisterCUDADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 451 |
+
|
| 452 |
+
#define REGISTER_XPU_DISPATCH(name, fn) \
|
| 453 |
+
static RegisterXPUDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 454 |
+
|
| 455 |
+
#define REGISTER_HPU_DISPATCH(name, fn) \
|
| 456 |
+
static RegisterHPUDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 457 |
+
|
| 458 |
+
#define REGISTER_HIP_DISPATCH(name, fn) \
|
| 459 |
+
static RegisterHIPDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 460 |
+
|
| 461 |
+
#define REGISTER_MPS_DISPATCH(name, fn) \
|
| 462 |
+
static RegisterMPSDispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 463 |
+
|
| 464 |
+
#define REGISTER_MTIA_DISPATCH(name, fn) \
|
| 465 |
+
static RegisterMTIADispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 466 |
+
|
| 467 |
+
#define REGISTER_PRIVATEUSE1_DISPATCH(name, fn) \
|
| 468 |
+
static RegisterPRIVATEUSE1Dispatch<struct name##_DECLARE_DISPATCH_type> name ## __register(name, fn);
|
| 469 |
+
|
| 470 |
+
// NB: This macro must be used in an actual 'cu' file; if you try using
|
| 471 |
+
// it from a 'cpp' file it will not work!
|
| 472 |
+
#if defined(__CUDACC__)
|
| 473 |
+
#define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
|
| 474 |
+
#elif defined(__HIPCC__)
|
| 475 |
+
// TODO: cut this over to HIP dispatch once we stop pretending that CUDA
|
| 476 |
+
// is HIP in the PyTorch HIPify build.
|
| 477 |
+
#define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
|
| 478 |
+
// #define REGISTER_DISPATCH(name, fn) REGISTER_HIP_DISPATCH(name, fn)
|
| 479 |
+
#elif defined(__OBJC__) && defined(USE_MPS)
|
| 480 |
+
// NB: this macro must be used from a 'mm' file in order to dispatch a MPS kernel
|
| 481 |
+
#define REGISTER_DISPATCH(name, fn) REGISTER_MPS_DISPATCH(name, fn)
|
| 482 |
+
#elif defined(CPU_CAPABILITY)
|
| 483 |
+
// REGISTER_DISPATCH now dispatches an AVX512 kernel to nullptr but registers other dispatches.
|
| 484 |
+
// ALSO_REGISTER_AVX512_DISPATCH should be used for ensuring AVX512 dispatch, among others.
|
| 485 |
+
// ALSO_REGISTER_SVE256_DISPATCH should be used for ensuring SVE256 dispatch, among others.
|
| 486 |
+
#ifdef CPU_CAPABILITY_AVX512
|
| 487 |
+
#define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, ((void*)(fn) ? nullptr : nullptr))
|
| 488 |
+
#else
|
| 489 |
+
#define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
|
| 490 |
+
#endif
|
| 491 |
+
#define ALSO_REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
|
| 492 |
+
#define ALSO_REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
|
| 493 |
+
#endif
|
| 494 |
+
} // namespace at::native
|
| 495 |
+
|
| 496 |
+
C10_CLANG_DIAGNOSTIC_POP()
|
| 497 |
+
|
| 498 |
+
#else
|
| 499 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 500 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Distance.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
|
| 6 |
+
namespace at {
|
| 7 |
+
class Tensor;
|
| 8 |
+
|
| 9 |
+
namespace native {
|
| 10 |
+
|
| 11 |
+
using pdist_forward_fn = void(*)(Tensor&, const Tensor&, const double p);
|
| 12 |
+
using pdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
|
| 13 |
+
using cdist_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p);
|
| 14 |
+
using cdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&);
|
| 15 |
+
|
| 16 |
+
DECLARE_DISPATCH(pdist_forward_fn, pdist_forward_stub)
|
| 17 |
+
DECLARE_DISPATCH(pdist_backward_fn, pdist_backward_stub)
|
| 18 |
+
DECLARE_DISPATCH(cdist_fn, cdist_stub)
|
| 19 |
+
DECLARE_DISPATCH(cdist_backward_fn, cdist_backward_stub)
|
| 20 |
+
|
| 21 |
+
}} // namespace at::native
|
| 22 |
+
|
| 23 |
+
#else
|
| 24 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 25 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <ATen/Dispatch.h>
|
| 6 |
+
#include <ATen/Dispatch_v2.h>
|
| 7 |
+
#include <ATen/Generator.h>
|
| 8 |
+
#include <ATen/ExpandUtils.h>
|
| 9 |
+
#include <ATen/Tensor.h>
|
| 10 |
+
#include <ATen/MemoryOverlap.h>
|
| 11 |
+
#include <ATen/NamedTensorUtils.h>
|
| 12 |
+
#include <ATen/native/Resize.h>
|
| 13 |
+
#include <ATen/native/TensorIterator.h>
|
| 14 |
+
#include <cmath>
|
| 15 |
+
#include <limits>
|
| 16 |
+
#include <optional>
|
| 17 |
+
|
| 18 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 19 |
+
#include <ATen/Functions.h>
|
| 20 |
+
#else
|
| 21 |
+
#include <ATen/ops/empty_like.h>
|
| 22 |
+
#include <ATen/ops/empty.h>
|
| 23 |
+
#include <ATen/ops/full.h>
|
| 24 |
+
#include <ATen/ops/view_as_real.h>
|
| 25 |
+
#endif
|
| 26 |
+
|
| 27 |
+
namespace at::native::templates {
|
| 28 |
+
|
| 29 |
+
// ==================================================== Random ========================================================
|
| 30 |
+
|
| 31 |
+
// The purpose of `update_from` and `update_to` is to find the closest valid int64_t number that can be used as actual `from`.
|
| 32 |
+
// The current implementation of `random_` uses uint64_t arithmetic and casts the result to the target dtype(scalar_t).
|
| 33 |
+
// This casting can result in generating numbers that happen to be greater or equal to `to` value. For instance:
|
| 34 |
+
//
|
| 35 |
+
// auto actual = torch::empty({3, 3}, torch::half);
|
| 36 |
+
// actual.random_(0, 65504);
|
| 37 |
+
//
|
| 38 |
+
// If random's uint64_t arithmetic produces 65503 as a random value after casting to torch::half it becomes 65504
|
| 39 |
+
// and violates the requirement that random value must be less than `to`. To resolve this issue `update_from` and `update_to`
|
| 40 |
+
// moves `from` to the right and `to` to the left to the next closest value that won't go outside [from, to) after casting to
|
| 41 |
+
// the target dtype. For `to` = 65504 it moves left for (1 << (log2(to) - 11 + 1)) = 32 and becomes 65472, which is previous
|
| 42 |
+
// available number for torch::half dtype.
|
| 43 |
+
template<typename scalar_t>
|
| 44 |
+
int64_t update_from(int64_t from) {
|
| 45 |
+
static_assert(
|
| 46 |
+
std::is_floating_point_v<scalar_t> ||
|
| 47 |
+
std::is_same_v<scalar_t, at::Half> ||
|
| 48 |
+
std::is_same_v<scalar_t, at::BFloat16>, "scalar_t must be floating-point type");
|
| 49 |
+
const auto from_plus_1 = static_cast<int64_t>(static_cast<scalar_t>(from + 1));
|
| 50 |
+
if (from_plus_1 < from) {
|
| 51 |
+
int64_t from_ = std::abs(from + 1);
|
| 52 |
+
int n = 0;
|
| 53 |
+
while (from_ >>= 1) ++n;
|
| 54 |
+
// NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
|
| 55 |
+
from = from_plus_1 + (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
|
| 56 |
+
}
|
| 57 |
+
return from;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
template<typename scalar_t>
|
| 61 |
+
int64_t update_to(int64_t to) {
|
| 62 |
+
static_assert(
|
| 63 |
+
std::is_floating_point_v<scalar_t> ||
|
| 64 |
+
std::is_same_v<scalar_t, at::Half> ||
|
| 65 |
+
std::is_same_v<scalar_t, at::BFloat16>, "scalar_t must be floating-point type");
|
| 66 |
+
const auto to_minus_1 = static_cast<int64_t>(static_cast<scalar_t>(to - 1));
|
| 67 |
+
if (to_minus_1 >= to) {
|
| 68 |
+
int64_t to_ = std::abs(to - 1);
|
| 69 |
+
int n = 0;
|
| 70 |
+
while (to_ >>= 1) ++n;
|
| 71 |
+
// NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
|
| 72 |
+
to = to_minus_1 - (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
|
| 73 |
+
}
|
| 74 |
+
return to;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// Return earlier for not invoking kernel.
|
| 78 |
+
// See https://github.com/pytorch/pytorch/issues/103418 for more details
|
| 79 |
+
#define CHECK_EMPTY_AND_RETURN(tensor) \
|
| 80 |
+
if (tensor.numel() == 0) { \
|
| 81 |
+
return tensor; \
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
template<template<typename> class random_kernel, typename RNG>
|
| 85 |
+
at::Tensor& random_impl(at::Tensor& self, std::optional<Generator> generator) {
|
| 86 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 87 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 88 |
+
random_kernel<RNG>()(iter, generator);
|
| 89 |
+
return self;
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
#define CHECK_OUT_OF_BOUNDS(var, name, min, max, dtype) \
|
| 93 |
+
TORCH_CHECK(var >= min && var <= max, name , " is out of bounds for ", dtype); \
|
| 94 |
+
|
| 95 |
+
#define WARN_OUT_OF_BOUNDS(var, name, digits, dtype) \
|
| 96 |
+
if (var < -(1LL << digits) || var > (1LL << digits)) { \
|
| 97 |
+
TORCH_WARN(name , " is out of bounds [-(2^", digits, "), 2^", digits, "]. ", \
|
| 98 |
+
"Due to precision limitations ", dtype, " can support discrete uniform distribution only within this range. ", \
|
| 99 |
+
"This warning will become an error in version 1.7 release, please fix the code in advance"); \
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
inline void check_from_to_in_range(int64_t from, int64_t to_inc, caffe2::TypeMeta dtype) {
|
| 103 |
+
const auto scalar_type = typeMetaToScalarType(dtype);
|
| 104 |
+
if (isFloatingType(scalar_type)) {
|
| 105 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, scalar_type, "check_random_fp_bounds", [&] {
|
| 106 |
+
const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
|
| 107 |
+
const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
|
| 108 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 109 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
|
| 110 |
+
|
| 111 |
+
constexpr auto digits = std::numeric_limits<scalar_t>::digits;
|
| 112 |
+
WARN_OUT_OF_BOUNDS(from, "from", digits, dtype);
|
| 113 |
+
WARN_OUT_OF_BOUNDS(to_inc, "to - 1", digits, dtype);
|
| 114 |
+
});
|
| 115 |
+
} else if (scalar_type == kUInt64) {
|
| 116 |
+
// When you do a comparison between int64_t and uint64_t, the usual
|
| 117 |
+
// arithmetic conversions say that the int64_t value is promoted to
|
| 118 |
+
// unsigned. But this conversion wraps around: if I had -1 as my int64_t,
|
| 119 |
+
// then it will promote to 0xFFFFFFFFFFFFFFFF in uint64_t. This is never
|
| 120 |
+
// the right thing to do.
|
| 121 |
+
CHECK_OUT_OF_BOUNDS(from, "from", 0, INT64_MAX, dtype);
|
| 122 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", 0, INT64_MAX, dtype);
|
| 123 |
+
} else if (isIntegralType(scalar_type, /*includeBool=*/true)) {
|
| 124 |
+
AT_DISPATCH_V2(scalar_type, "check_random_integral_bounds", AT_WRAP([&]() {
|
| 125 |
+
const auto min = static_cast<int64_t>(std::numeric_limits<scalar_t>::lowest());
|
| 126 |
+
const auto max = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
|
| 127 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 128 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
|
| 129 |
+
}), AT_EXPAND(AT_INTEGRAL_TYPES), kUInt16, kUInt32, kBool);
|
| 130 |
+
} else {
|
| 131 |
+
TORCH_CHECK(false, "check_random_bounds handles only integral, floating-point and boolean types");
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
template<template<typename> class random_from_to_kernel, typename RNG>
|
| 136 |
+
at::Tensor& random_from_to_impl(at::Tensor& self, int64_t from, std::optional<int64_t> to_opt, std::optional<Generator> generator) {
|
| 137 |
+
uint64_t range = 0;
|
| 138 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 139 |
+
if (to_opt.has_value()) {
|
| 140 |
+
// [from, to)
|
| 141 |
+
int64_t to = *to_opt;
|
| 142 |
+
TORCH_CHECK(from < to, "random_ expects 'from' to be less than 'to', but got from=", from, " >= to=", to);
|
| 143 |
+
if (isFloatingType(iter.dtype())) {
|
| 144 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_update_from_to", [&] {
|
| 145 |
+
from = update_from<scalar_t>(from);
|
| 146 |
+
to = update_to<scalar_t>(to);
|
| 147 |
+
TORCH_CHECK(from < to, "random_ expects 'from' casted to dtype to be less than 'to' casted to dtype, but got from=", from, " >= to=", to);
|
| 148 |
+
});
|
| 149 |
+
}
|
| 150 |
+
check_from_to_in_range(from, to - 1, self.dtype());
|
| 151 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 152 |
+
range = static_cast<uint64_t>(to) - static_cast<uint64_t>(from);
|
| 153 |
+
random_from_to_kernel<RNG>()(iter, range, from, generator);
|
| 154 |
+
} else if (from != std::numeric_limits<int64_t>::lowest()) {
|
| 155 |
+
// [from, std::numeric_limits<int64_t>::max()]
|
| 156 |
+
int64_t to_inc = 0;
|
| 157 |
+
if (isFloatingType(iter.dtype())) {
|
| 158 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_from_to_range_calc", [&] {
|
| 159 |
+
constexpr int64_t scalar_t_max = static_cast<int64_t>(1) << std::numeric_limits<scalar_t>::digits;
|
| 160 |
+
to_inc = scalar_t_max > std::numeric_limits<int64_t>::max() ? std::numeric_limits<int64_t>::max() : static_cast<int64_t>(scalar_t_max);
|
| 161 |
+
from = update_from<scalar_t>(from);
|
| 162 |
+
TORCH_CHECK(from < to_inc, "random_ expects 'from' casted to dtype to be less than or equal to 'to_inc' casted to dtype, but got from=", from, " > to_inc=", to_inc);
|
| 163 |
+
});
|
| 164 |
+
} else if (isIntegralType(iter.dtype(), /*includeBool=*/true)) {
|
| 165 |
+
AT_DISPATCH_V2(self.scalar_type(), "random_from_to_range_calc", AT_WRAP([&] {
|
| 166 |
+
if constexpr (std::is_same_v<scalar_t, bool>) {
|
| 167 |
+
to_inc = static_cast<int64_t>(true);
|
| 168 |
+
} else {
|
| 169 |
+
to_inc = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
|
| 170 |
+
}
|
| 171 |
+
}), AT_EXPAND(AT_INTEGRAL_TYPES_V2), kBool);
|
| 172 |
+
} else {
|
| 173 |
+
TORCH_CHECK(false, "random_from_to_impl handles only integral, floating-point and boolean types");
|
| 174 |
+
}
|
| 175 |
+
check_from_to_in_range(from, to_inc, self.dtype());
|
| 176 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 177 |
+
range = static_cast<uint64_t>(to_inc) - static_cast<uint64_t>(from) + 1;
|
| 178 |
+
random_from_to_kernel<RNG>()(iter, range, from, generator);
|
| 179 |
+
} else {
|
| 180 |
+
// [std::numeric_limits<int64_t>::lowest(), std::numeric_limits<int64_t>::max()]
|
| 181 |
+
// range = 2^64
|
| 182 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 183 |
+
random_from_to_kernel<RNG>()(iter, generator);
|
| 184 |
+
}
|
| 185 |
+
return self;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// ==================================================== Normal ========================================================
|
| 189 |
+
|
| 190 |
+
#define CHECK_NORMAL_TENSOR_STD(std) \
|
| 191 |
+
do { \
|
| 192 |
+
TORCH_CHECK( \
|
| 193 |
+
!std.is_complex(), \
|
| 194 |
+
"normal expects standard deviation to be non-complex"); \
|
| 195 |
+
TORCH_CHECK( \
|
| 196 |
+
std.numel() == 0 || std.is_meta() || std.min().ge(0).item<bool>(), \
|
| 197 |
+
"normal expects all elements of std >= 0.0"); \
|
| 198 |
+
} while (0)
|
| 199 |
+
|
| 200 |
+
#define CHECK_NORMAL_STD(std) \
|
| 201 |
+
TORCH_CHECK(std >= 0.0, "normal expects std >= 0.0, but found std ", std);
|
| 202 |
+
|
| 203 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 204 |
+
Tensor& normal_impl_(Tensor& self, double mean, double std, std::optional<Generator> gen) {
|
| 205 |
+
CHECK_NORMAL_STD(std);
|
| 206 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 207 |
+
|
| 208 |
+
if (self.is_complex()) {
|
| 209 |
+
auto float_tensor = at::view_as_real(self);
|
| 210 |
+
// variance for normal distribution of the real and imaginary values
|
| 211 |
+
// is half of the input variance
|
| 212 |
+
normal_kernel<RNG>()(float_tensor, mean, std/(std::sqrt(2)), gen);
|
| 213 |
+
} else {
|
| 214 |
+
normal_kernel<RNG>()(self, mean, std, gen);
|
| 215 |
+
}
|
| 216 |
+
return self;
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 220 |
+
Tensor& normal_out_impl(Tensor& output, const Tensor& mean, double std, std::optional<Generator> gen) {
|
| 221 |
+
CHECK_NORMAL_STD(std);
|
| 222 |
+
auto std_tensor = at::empty_like(output, MemoryFormat::Contiguous);
|
| 223 |
+
auto shape = at::infer_size(mean.sizes(), std_tensor.sizes());
|
| 224 |
+
at::native::resize_output(output, shape);
|
| 225 |
+
normal_impl_<normal_kernel, RNG>(output, 0, std, gen);
|
| 226 |
+
output.add_(mean);
|
| 227 |
+
return output;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 231 |
+
Tensor& normal_out_impl(Tensor& output, double mean, const Tensor& std, std::optional<Generator> gen) {
|
| 232 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 233 |
+
auto mean_tensor = at::full({}, mean, output.options());
|
| 234 |
+
auto shape = at::infer_size(mean_tensor.sizes(), std.sizes());
|
| 235 |
+
at::native::resize_output(output, shape);
|
| 236 |
+
normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
|
| 237 |
+
// CUDA NB: addcmul_out copies the tensor to be added into the output.
|
| 238 |
+
// The previous function here was addcmul_out(output, mean_tensor, output, std, 1);
|
| 239 |
+
// The third argument is not a constant reference and hence the samples in output are overwritten.
|
| 240 |
+
// Consequently, the computation performed is mean_tensor + mean_tensor * std instead of mean_tensor + output * std
|
| 241 |
+
output.mul_(std).add_(mean_tensor);
|
| 242 |
+
return output;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 246 |
+
Tensor& normal_out_impl(Tensor& output, const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
|
| 247 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 248 |
+
auto shape = at::infer_size(mean.sizes(), std.sizes());
|
| 249 |
+
at::native::resize_output(output, shape);
|
| 250 |
+
normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
|
| 251 |
+
// CUDA NB: addcmul_out copies the tensor to be added into the output.
|
| 252 |
+
// The previous function here was addcmul_out(output, mean, output, std, 1);
|
| 253 |
+
// The third argument is not a constant reference and hence the samples in output are overwritten.
|
| 254 |
+
// Consequently, the computation performed is mean + mean * std instead of mean + output * std
|
| 255 |
+
output.mul_(std).add_(mean);
|
| 256 |
+
return output;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 260 |
+
Tensor normal_impl(const Tensor& mean, double std, std::optional<Generator> gen) {
|
| 261 |
+
CHECK_NORMAL_STD(std);
|
| 262 |
+
Tensor ret = at::empty_like(mean, MemoryFormat::Contiguous);
|
| 263 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 264 |
+
return ret;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 268 |
+
Tensor normal_impl(double mean, const Tensor& std, std::optional<Generator> gen) {
|
| 269 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 270 |
+
Tensor ret = at::empty_like(std, MemoryFormat::Contiguous);
|
| 271 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 272 |
+
return ret;
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 276 |
+
Tensor normal_impl(const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
|
| 277 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 278 |
+
auto shape = at::infer_size(mean.sizes(), std.sizes());
|
| 279 |
+
Tensor ret = at::empty(shape, mean.options(), MemoryFormat::Contiguous);
|
| 280 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 281 |
+
return ret;
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
// ==================================================== Uniform =======================================================
|
| 285 |
+
|
| 286 |
+
template<template<typename> class uniform_kernel, typename RNG>
|
| 287 |
+
at::Tensor& uniform_impl_(at::Tensor& self, double from, double to, std::optional<Generator> generator) {
|
| 288 |
+
if (self.is_complex()) {
|
| 289 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 290 |
+
auto float_tensor = at::view_as_real(self);
|
| 291 |
+
uniform_impl_<uniform_kernel, RNG>(float_tensor, from, to, generator);
|
| 292 |
+
} else {
|
| 293 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "check_uniform_bounds", [&] {
|
| 294 |
+
[[maybe_unused]] const auto dtype = self.dtype();
|
| 295 |
+
const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
|
| 296 |
+
const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
|
| 297 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 298 |
+
CHECK_OUT_OF_BOUNDS(to, "to", min, max, dtype);
|
| 299 |
+
TORCH_CHECK(from <= to, "uniform_ expects to return a [from, to) range, but found from=", from, " > to=", to);
|
| 300 |
+
TORCH_CHECK((to - from) <= std::numeric_limits<scalar_t>::max(),
|
| 301 |
+
"uniform_ expects to-from <= std::numeric_limits<", toString(self.scalar_type()),
|
| 302 |
+
">::max(), but found to=", to, " and from=", from,
|
| 303 |
+
" which result in to-from to exceed the limit");
|
| 304 |
+
from = std::min(std::max(from, min), max);
|
| 305 |
+
to = std::max(std::min(to, max), min);
|
| 306 |
+
});
|
| 307 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 308 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 309 |
+
uniform_kernel<RNG>()(iter, from, to, generator);
|
| 310 |
+
}
|
| 311 |
+
return self;
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
// ================================================== LogNormal =======================================================
|
| 315 |
+
|
| 316 |
+
template<template<typename> class log_normal_kernel, typename RNG>
|
| 317 |
+
at::Tensor& log_normal_impl_(at::Tensor& self, double mean, double std, std::optional<Generator> gen) {
|
| 318 |
+
TORCH_CHECK(std > 0.0, "log_normal_ expects std > 0.0, but found std=", std);
|
| 319 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 320 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 321 |
+
log_normal_kernel<RNG>()(iter, mean, std, gen);
|
| 322 |
+
return self;
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
// =================================================== Geometric ======================================================
|
| 326 |
+
|
| 327 |
+
template<template<typename> class geometric_kernel, typename RNG>
|
| 328 |
+
Tensor& geometric_impl_(Tensor& self, double p, std::optional<Generator> gen) {
|
| 329 |
+
TORCH_CHECK(0 < p && p < 1, "geometric_ expects p to be in (0, 1), but got p=", p);
|
| 330 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 331 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 332 |
+
geometric_kernel<RNG>()(iter, p, gen);
|
| 333 |
+
return self;
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// ================================================== Exponential =====================================================
|
| 337 |
+
|
| 338 |
+
template<template<typename> class exponential_kernel, typename RNG>
|
| 339 |
+
Tensor& exponential_impl_(Tensor& self, double lambda, std::optional<Generator> gen) {
|
| 340 |
+
TORCH_CHECK(lambda > 0.0, "exponential_ expects lambda > 0.0, but found lambda=", lambda);
|
| 341 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 342 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 343 |
+
exponential_kernel<RNG>()(iter, lambda, gen);
|
| 344 |
+
return self;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
// ==================================================== Cauchy ========================================================
|
| 348 |
+
|
| 349 |
+
template<template<typename> class cauchy_kernel, typename RNG>
|
| 350 |
+
Tensor& cauchy_impl_(Tensor& self, double median, double sigma, std::optional<Generator> gen) {
|
| 351 |
+
// TODO: instead of variable name 'sigma', use 'gamma' or 'scale'
|
| 352 |
+
// the variance, squared sigma, is undefined for cauchy distribution
|
| 353 |
+
TORCH_CHECK(sigma > 0.0, "cauchy_ expects sigma > 0.0, but found sigma=", sigma);
|
| 354 |
+
TORCH_CHECK(at::isFloatingType(self.scalar_type()), "Cauchy distribution is a continuous probability distribution. dtype must be a floating point but you specified ", self.dtype());
|
| 355 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 356 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 357 |
+
cauchy_kernel<RNG>()(iter, median, sigma, gen);
|
| 358 |
+
return self;
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// ==================================================== Bernoulli =====================================================
|
| 362 |
+
|
| 363 |
+
template<template<typename> class bernoulli_tensor_kernel, typename RNG>
|
| 364 |
+
Tensor& bernoulli_impl_(Tensor& self, const Tensor& p_, std::optional<Generator> gen) {
|
| 365 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 366 |
+
NoNamesGuard guard;
|
| 367 |
+
at::assert_no_internal_overlap(self);
|
| 368 |
+
bernoulli_tensor_kernel<RNG>()(self, p_, gen);
|
| 369 |
+
return self;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
template<template<typename> class bernoulli_scalar_kernel, typename RNG>
|
| 373 |
+
Tensor& bernoulli_impl_(Tensor& self, double p, std::optional<Generator> gen) {
|
| 374 |
+
TORCH_CHECK(0 <= p && p <= 1, "bernoulli_ expects p to be in [0, 1], but got p=", p);
|
| 375 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 376 |
+
at::assert_no_internal_overlap(self);
|
| 377 |
+
bernoulli_scalar_kernel<RNG>()(self, p, gen);
|
| 378 |
+
return self;
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
template<template<typename> class bernoulli_tensor_kernel, typename RNG>
|
| 382 |
+
Tensor& bernoulli_out_impl(Tensor& result, const Tensor& self, std::optional<Generator> gen) {
|
| 383 |
+
// result.resize_as_(self) requires self to have same dtype as result, so we
|
| 384 |
+
// use resize_ instead.
|
| 385 |
+
// TODO: Fix resize_as_. See pytorch/pytorch#11665.
|
| 386 |
+
result.resize_(self.sizes());
|
| 387 |
+
bernoulli_impl_<bernoulli_tensor_kernel, RNG>(result, self, gen);
|
| 388 |
+
namedinference::propagate_names(result, self);
|
| 389 |
+
return result;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
#undef CHECK_OUT_OF_BOUNDS
|
| 393 |
+
#undef WARN_OUT_OF_BOUNDS
|
| 394 |
+
|
| 395 |
+
} // namespace at::native::templates
|
| 396 |
+
|
| 397 |
+
#else
|
| 398 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 399 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Distributions.h
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <array>
|
| 5 |
+
#include <ATen/native/Math.h>
|
| 6 |
+
#include <c10/macros/Macros.h>
|
| 7 |
+
#include <c10/util/MathConstants.h>
|
| 8 |
+
|
| 9 |
+
// ROCM hcc doesn't work well with using std:: in kernel functions
|
| 10 |
+
#if defined(__CUDA_ARCH__)
|
| 11 |
+
#include <c10/cuda/CUDAMathCompat.h>
|
| 12 |
+
#define compat_exp c10::cuda::compat::exp
|
| 13 |
+
#define compat_ceil c10::cuda::compat::ceil
|
| 14 |
+
#define compat_floor c10::cuda::compat::floor
|
| 15 |
+
#define compat_log c10::cuda::compat::log
|
| 16 |
+
#define compat_pow c10::cuda::compat::pow
|
| 17 |
+
#define compat_sqrt c10::cuda::compat::sqrt
|
| 18 |
+
#define compat_tan c10::cuda::compat::tan
|
| 19 |
+
#define compat_abs c10::cuda::compat::abs
|
| 20 |
+
#define compat_log1p c10::cuda::compat::log1p
|
| 21 |
+
#elif defined(__HIPCC__)
|
| 22 |
+
#include <c10/hip/HIPMathCompat.h>
|
| 23 |
+
#define compat_exp c10::hip::compat::exp
|
| 24 |
+
#define compat_ceil c10::hip::compat::ceil
|
| 25 |
+
#define compat_floor c10::hip::compat::floor
|
| 26 |
+
#define compat_log c10::hip::compat::log
|
| 27 |
+
#define compat_pow c10::hip::compat::pow
|
| 28 |
+
#define compat_sqrt c10::hip::compat::sqrt
|
| 29 |
+
#define compat_tan c10::hip::compat::tan
|
| 30 |
+
#define compat_abs c10::hip::compat::abs
|
| 31 |
+
#define compat_log1p c10::hip::compat::log1p
|
| 32 |
+
#else
|
| 33 |
+
#define compat_exp std::exp
|
| 34 |
+
#define compat_ceil std::ceil
|
| 35 |
+
#define compat_floor std::floor
|
| 36 |
+
#define compat_log std::log
|
| 37 |
+
#define compat_pow std::pow
|
| 38 |
+
#define compat_sqrt std::sqrt
|
| 39 |
+
#define compat_tan std::tan
|
| 40 |
+
#define compat_abs std::abs
|
| 41 |
+
#define compat_log1p std::log1p
|
| 42 |
+
#endif
|
| 43 |
+
|
| 44 |
+
namespace {
|
| 45 |
+
|
| 46 |
+
#if !defined(__CUDA_ARCH__) && !defined(__HIPCC__)
|
| 47 |
+
// we cannot use std::isnan directly due to some incompatibility of
|
| 48 |
+
// gcc constexpr'ing and nvcc
|
| 49 |
+
using std::isnan;
|
| 50 |
+
#endif
|
| 51 |
+
|
| 52 |
+
// Here sampler_t should be function type scalar_t(void). For gpu
|
| 53 |
+
// "sampler" is a device function, but since ROCM doesn't have
|
| 54 |
+
// equivalent to nvstd::function, we use a template type parameter to
|
| 55 |
+
// capture it.
|
| 56 |
+
template<typename scalar_t, typename sampler_t>
|
| 57 |
+
struct BaseSampler {
|
| 58 |
+
sampler_t sampler;
|
| 59 |
+
C10_DEVICE BaseSampler(const sampler_t& sampler): sampler(sampler) {}
|
| 60 |
+
C10_DEVICE scalar_t sample() {
|
| 61 |
+
return sampler();
|
| 62 |
+
}
|
| 63 |
+
};
|
| 64 |
+
|
| 65 |
+
// The function `sample_gamma` is
|
| 66 |
+
// is adapted from Numpy's distributions.c implementation.
|
| 67 |
+
// It is MIT licensed, so here is the copyright:
|
| 68 |
+
|
| 69 |
+
/* Copyright 2005 Robert Kern (robert.kern@gmail.com)
|
| 70 |
+
*
|
| 71 |
+
* Permission is hereby granted, free of charge, to any person obtaining a
|
| 72 |
+
* copy of this software and associated documentation files (the
|
| 73 |
+
* "Software"), to deal in the Software without restriction, including
|
| 74 |
+
* without limitation the rights to use, copy, modify, merge, publish,
|
| 75 |
+
* distribute, sublicense, and/or sell copies of the Software, and to
|
| 76 |
+
* permit persons to whom the Software is furnished to do so, subject to
|
| 77 |
+
* the following conditions:
|
| 78 |
+
*
|
| 79 |
+
* The above copyright notice and this permission notice shall be included
|
| 80 |
+
* in all copies or substantial portions of the Software.
|
| 81 |
+
*
|
| 82 |
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
| 83 |
+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 84 |
+
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
| 85 |
+
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
| 86 |
+
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
| 87 |
+
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
| 88 |
+
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 89 |
+
*/
|
| 90 |
+
|
| 91 |
+
template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t, typename normal_sampler_t>
|
| 92 |
+
C10_DEVICE scalar_t sample_gamma(scalar_t alpha, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform, BaseSampler<accscalar_t, normal_sampler_t>& standard_normal) {
|
| 93 |
+
accscalar_t scale = 1.0f;
|
| 94 |
+
|
| 95 |
+
// Boost alpha for higher acceptance probability.
|
| 96 |
+
if (alpha < 1.0f) {
|
| 97 |
+
if (alpha == 0.f) return 0.f;
|
| 98 |
+
scale *= compat_pow(1 - standard_uniform.sample(), 1.0f / alpha);
|
| 99 |
+
alpha += 1.0f;
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
// This implements the acceptance-rejection method of Marsaglia and Tsang (2000)
|
| 103 |
+
// doi:10.1145/358407.358414
|
| 104 |
+
const accscalar_t d = alpha - 1.0f / 3.0f;
|
| 105 |
+
const accscalar_t c = 1.0f / compat_sqrt(9.0f * d);
|
| 106 |
+
for (;;) {
|
| 107 |
+
accscalar_t x, y;
|
| 108 |
+
do {
|
| 109 |
+
x = standard_normal.sample();
|
| 110 |
+
y = 1.0f + c * x;
|
| 111 |
+
} while (y <= 0);
|
| 112 |
+
const accscalar_t v = y * y * y;
|
| 113 |
+
const accscalar_t u = 1 - standard_uniform.sample();
|
| 114 |
+
const accscalar_t xx = x * x;
|
| 115 |
+
if (u < 1.0f - 0.0331f * xx * xx)
|
| 116 |
+
return static_cast<scalar_t>(scale * d * v);
|
| 117 |
+
if (compat_log(u) < 0.5f * xx + d * (1.0f - v + compat_log(v)))
|
| 118 |
+
return static_cast<scalar_t>(scale * d * v);
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
/* the functions stirling_approx_tail, binomial_inversion, and btrs are adapted
|
| 123 |
+
* from TensorFlow's random_binomial_op.cc implementation. That code is under
|
| 124 |
+
* copyright: 2019 The TensorFlow Authors.
|
| 125 |
+
*
|
| 126 |
+
* It was released under the Apache License, Version 2.0 (the "License"), available at:
|
| 127 |
+
* http://www.apache.org/licenses/LICENSE-2.0
|
| 128 |
+
*/
|
| 129 |
+
|
| 130 |
+
template<typename scalar_t>
|
| 131 |
+
C10_DEVICE scalar_t stirling_approx_tail(scalar_t k) {
|
| 132 |
+
constexpr static scalar_t kTailValues[] = {
|
| 133 |
+
0.0810614667953272,
|
| 134 |
+
0.0413406959554092,
|
| 135 |
+
0.0276779256849983,
|
| 136 |
+
0.02079067210376509,
|
| 137 |
+
0.0166446911898211,
|
| 138 |
+
0.0138761288230707,
|
| 139 |
+
0.0118967099458917,
|
| 140 |
+
0.0104112652619720,
|
| 141 |
+
0.00925546218271273,
|
| 142 |
+
0.00833056343336287
|
| 143 |
+
};
|
| 144 |
+
if (k < std::size(kTailValues)) {
|
| 145 |
+
return kTailValues[static_cast<size_t>(k)];
|
| 146 |
+
}
|
| 147 |
+
scalar_t kp1sq = (k + 1) * (k + 1);
|
| 148 |
+
return (1.0 / 12 - (1.0 / 360 - 1.0 / 1260 / kp1sq) / kp1sq) / (k + 1);
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
|
| 153 |
+
C10_DEVICE scalar_t binomial_inversion(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
|
| 154 |
+
accscalar_t U;
|
| 155 |
+
accscalar_t geom_sum = 0;
|
| 156 |
+
scalar_t num_geom = 0;
|
| 157 |
+
|
| 158 |
+
accscalar_t logprob = compat_log1p(-prob);
|
| 159 |
+
|
| 160 |
+
while (true) {
|
| 161 |
+
U = standard_uniform.sample();
|
| 162 |
+
accscalar_t geom = compat_ceil(compat_log(U) / logprob);
|
| 163 |
+
geom_sum += geom;
|
| 164 |
+
if (geom_sum > count) {
|
| 165 |
+
break;
|
| 166 |
+
}
|
| 167 |
+
num_geom = num_geom + 1;
|
| 168 |
+
}
|
| 169 |
+
return num_geom;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
|
| 173 |
+
C10_DEVICE scalar_t btrs(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
|
| 174 |
+
scalar_t k;
|
| 175 |
+
accscalar_t U, V, us;
|
| 176 |
+
|
| 177 |
+
// This is spq in the paper.
|
| 178 |
+
const accscalar_t stddev = compat_sqrt(count * prob * (1 - prob));
|
| 179 |
+
|
| 180 |
+
// Other coefficients for Transformed Rejection sampling.
|
| 181 |
+
const accscalar_t b = 1.15 + 2.53 * stddev;
|
| 182 |
+
const accscalar_t a = -0.0873 + 0.0248 * b + 0.01 * prob;
|
| 183 |
+
const accscalar_t c = count * prob + 0.5;
|
| 184 |
+
const accscalar_t v_r = 0.92 - 4.2 / b;
|
| 185 |
+
const accscalar_t r = prob / (1 - prob);
|
| 186 |
+
|
| 187 |
+
const accscalar_t alpha = (2.83 + 5.1 / b) * stddev;
|
| 188 |
+
const accscalar_t m = compat_floor((count + 1) * prob);
|
| 189 |
+
|
| 190 |
+
while (true) {
|
| 191 |
+
U = standard_uniform.sample() - 0.5;
|
| 192 |
+
V = standard_uniform.sample();
|
| 193 |
+
|
| 194 |
+
us = 0.5 - compat_abs(U);
|
| 195 |
+
k = static_cast<scalar_t>(compat_floor((2 * a / us + b) * U + c));
|
| 196 |
+
|
| 197 |
+
// Reject non-sensical answers.
|
| 198 |
+
if (k < 0 || k > count) {
|
| 199 |
+
continue;
|
| 200 |
+
}
|
| 201 |
+
// Region for which the box is tight, and we can return our calculated value.
|
| 202 |
+
// This should happen 0.86 * v_r times. In the limit as n * p is large,
|
| 203 |
+
// the acceptance rate converges to ~79% (and in the lower regime it is ~24%).
|
| 204 |
+
if (us >= 0.07 && V <= v_r) {
|
| 205 |
+
return k;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
// This deviates from Hormann's BTRS algorithm, as there is a log missing.
|
| 209 |
+
// For all (u, v) pairs outside of the bounding box, this calculates the
|
| 210 |
+
// transformed-reject ratio.
|
| 211 |
+
V = compat_log(V * alpha / (a / (us * us) + b));
|
| 212 |
+
accscalar_t upperbound =
|
| 213 |
+
((m + 0.5) * compat_log((m + 1) / (r * (count - m + 1))) +
|
| 214 |
+
(count + 1) * compat_log((count - m + 1) / (count - k + 1)) +
|
| 215 |
+
(k + 0.5) * compat_log(r * (count - k + 1) / (k + 1)) +
|
| 216 |
+
stirling_approx_tail<accscalar_t>(m) + stirling_approx_tail<accscalar_t>(count - m) -
|
| 217 |
+
stirling_approx_tail<accscalar_t>(k) - stirling_approx_tail<accscalar_t>(count - k));
|
| 218 |
+
|
| 219 |
+
if (V <= upperbound) {
|
| 220 |
+
return k;
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
template<typename scalar_t, typename accscalar_t, typename uniform_sampler_t>
|
| 226 |
+
C10_DEVICE scalar_t sample_binomial(scalar_t count, scalar_t prob, BaseSampler<accscalar_t, uniform_sampler_t>& standard_uniform) {
|
| 227 |
+
if (count <= 0.0 || prob <= 0.0) {
|
| 228 |
+
return 0;
|
| 229 |
+
} else if (prob >= 1.0) {
|
| 230 |
+
return count;
|
| 231 |
+
} else if (prob <= 0.5) {
|
| 232 |
+
if (count * prob >= 10.0) {
|
| 233 |
+
// btrs
|
| 234 |
+
return btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
|
| 235 |
+
} else {
|
| 236 |
+
// binomial inversion
|
| 237 |
+
return binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, prob, standard_uniform);
|
| 238 |
+
}
|
| 239 |
+
} else if (prob > 0.5) {
|
| 240 |
+
scalar_t qprob = 1.0 - prob;
|
| 241 |
+
if (count * qprob >= 10.0) {
|
| 242 |
+
// btrs
|
| 243 |
+
return count - btrs<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
|
| 244 |
+
} else {
|
| 245 |
+
// count - binomial inversion
|
| 246 |
+
return count - binomial_inversion<scalar_t, accscalar_t, uniform_sampler_t>(count, qprob, standard_uniform);
|
| 247 |
+
}
|
| 248 |
+
} else {
|
| 249 |
+
// prob is nan?
|
| 250 |
+
return static_cast<scalar_t>(NAN);
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
/*
|
| 255 |
+
* This function is derived from the implementation of the digamma function in the Cephes Math Library.
|
| 256 |
+
* See note [3-Clause BSD License for the Cephes Math Library] in ATen/native/Math.h.
|
| 257 |
+
*/
|
| 258 |
+
template<typename scalar_t, typename accscalar_t>
|
| 259 |
+
C10_DEVICE inline scalar_t digamma_one(scalar_t x) {
|
| 260 |
+
constexpr accscalar_t PSI_10 = 2.25175258906672110764;
|
| 261 |
+
if (x == 0) {
|
| 262 |
+
return INFINITY;
|
| 263 |
+
}
|
| 264 |
+
accscalar_t additional_summand = 0;
|
| 265 |
+
int x_is_integer = x == compat_floor(x);
|
| 266 |
+
if (x < 0) {
|
| 267 |
+
if (x_is_integer) {
|
| 268 |
+
return INFINITY;
|
| 269 |
+
}
|
| 270 |
+
// it is more standard to write this as recursion, but
|
| 271 |
+
// nvcc does not like that
|
| 272 |
+
additional_summand = -c10::pi<scalar_t> /
|
| 273 |
+
compat_tan(c10::pi<scalar_t> * x);
|
| 274 |
+
x = 1 - x;
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
// Push x to be >= 10
|
| 278 |
+
accscalar_t result = 0;
|
| 279 |
+
while (x < 10) {
|
| 280 |
+
result -= 1 / x;
|
| 281 |
+
x += 1;
|
| 282 |
+
}
|
| 283 |
+
if (x == 10) {
|
| 284 |
+
return result + PSI_10 + additional_summand;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
// Compute asymptotic digamma
|
| 288 |
+
static const accscalar_t A[] = {
|
| 289 |
+
8.33333333333333333333E-2,
|
| 290 |
+
-2.10927960927960927961E-2,
|
| 291 |
+
7.57575757575757575758E-3,
|
| 292 |
+
-4.16666666666666666667E-3,
|
| 293 |
+
3.96825396825396825397E-3,
|
| 294 |
+
-8.33333333333333333333E-3,
|
| 295 |
+
8.33333333333333333333E-2,
|
| 296 |
+
};
|
| 297 |
+
|
| 298 |
+
accscalar_t y = 0;
|
| 299 |
+
if (x < 1.0e17f) {
|
| 300 |
+
accscalar_t z = 1.0 / (x * x);
|
| 301 |
+
y = z * polevl<accscalar_t>(z, A, 6);
|
| 302 |
+
}
|
| 303 |
+
return static_cast<scalar_t>(
|
| 304 |
+
result + compat_log(x) - (0.5f / x) - y + additional_summand);
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
// Computes the reparameterized gradient -(d/dalpha cdf(x;alpha)) / pdf(x;alpha)
|
| 308 |
+
// for random number x drawn from a standard Gamma distribution Gamma(alpha).
|
| 309 |
+
template <typename scalar_t, typename accscalar_t>
|
| 310 |
+
C10_HOST_DEVICE scalar_t standard_gamma_grad_one(scalar_t alpha_, scalar_t x_) {
|
| 311 |
+
// Use a Taylor series expansion for small x.
|
| 312 |
+
accscalar_t x = static_cast<accscalar_t>(x_);
|
| 313 |
+
accscalar_t alpha = static_cast<accscalar_t>(alpha_);
|
| 314 |
+
if (x < 0.8f) {
|
| 315 |
+
accscalar_t numer = 1;
|
| 316 |
+
accscalar_t denom = alpha;
|
| 317 |
+
auto series1 = numer / denom;
|
| 318 |
+
auto series2 = numer / (denom * denom);
|
| 319 |
+
for (int i = 1; i <= 5; ++i) {
|
| 320 |
+
numer *= -x / static_cast<accscalar_t>(i);
|
| 321 |
+
denom += 1;
|
| 322 |
+
series1 += numer / denom;
|
| 323 |
+
series2 += numer / (denom * denom);
|
| 324 |
+
}
|
| 325 |
+
const auto pow_x_alpha = compat_pow(x, alpha);
|
| 326 |
+
const auto gamma_pdf = compat_pow(x, alpha - 1) * compat_exp(-x);
|
| 327 |
+
const auto gamma_cdf = pow_x_alpha * series1;
|
| 328 |
+
const auto gamma_cdf_alpha =
|
| 329 |
+
(compat_log(x) - digamma_one<accscalar_t, accscalar_t>(alpha)) *
|
| 330 |
+
gamma_cdf -
|
| 331 |
+
pow_x_alpha * series2;
|
| 332 |
+
const auto result = -gamma_cdf_alpha / gamma_pdf;
|
| 333 |
+
return isnan(result) ? static_cast<scalar_t>( 0.f ) : static_cast<scalar_t>(result);
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
// Use a Rice saddle point expansion for large alpha.
|
| 337 |
+
if (alpha > 8.0f) {
|
| 338 |
+
if (0.9f * alpha <= x && x <= 1.1f * alpha) {
|
| 339 |
+
const auto numer_1 = 1 + 24 * alpha * (1 + 12 * alpha);
|
| 340 |
+
const auto numer_2 = 1440 * (alpha * alpha) + 6 * x * (53 - 120 * x)
|
| 341 |
+
- 65 * x * x / alpha + alpha * (107 + 3600 * x);
|
| 342 |
+
const auto denom = 1244160 * (alpha * alpha) * (alpha * alpha);
|
| 343 |
+
return static_cast<scalar_t>(numer_1 * numer_2 / denom);
|
| 344 |
+
}
|
| 345 |
+
const auto denom = compat_sqrt(8 * alpha);
|
| 346 |
+
const auto term2 = denom / (alpha - x);
|
| 347 |
+
const auto term3 = compat_pow(
|
| 348 |
+
x - alpha - alpha * compat_log(x / alpha),
|
| 349 |
+
static_cast<accscalar_t>(-1.5));
|
| 350 |
+
const auto term23 = (x < alpha) ? term2 - term3 : term2 + term3;
|
| 351 |
+
const auto term1 = compat_log(x / alpha) * term23 -
|
| 352 |
+
compat_sqrt(2 / alpha) * (alpha + x) / ((alpha - x) * (alpha - x));
|
| 353 |
+
const auto stirling = 1 + 1 / (12 * alpha) * (1 + 1 / (24 * alpha));
|
| 354 |
+
const auto numer = x * term1;
|
| 355 |
+
return static_cast<scalar_t>(-stirling * numer / denom);
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
// Use a bivariate rational approximation to the reparameterized gradient.
|
| 359 |
+
const auto u = compat_log(x / alpha);
|
| 360 |
+
const auto v = compat_log(alpha);
|
| 361 |
+
static const accscalar_t coef_uv[3][8] = {
|
| 362 |
+
{0.16009398, -0.094634809, 0.025146376, -0.0030648343,
|
| 363 |
+
1, 0.32668115, 0.10406089, 0.0014179084},
|
| 364 |
+
{0.53487893, 0.1298071, 0.065735949, -0.0015649758,
|
| 365 |
+
0.16639465, 0.020070113, -0.0035938915, -0.00058392623},
|
| 366 |
+
{0.040121004, -0.0065914022, -0.0026286047, -0.0013441777,
|
| 367 |
+
0.017050642, -0.0021309326, 0.00085092367, -1.5247877e-07},
|
| 368 |
+
};
|
| 369 |
+
accscalar_t coef_v[8];
|
| 370 |
+
for (int i = 0; i < 8; ++ i) {
|
| 371 |
+
coef_v[i] = coef_uv[0][i] + u * (coef_uv[1][i] + u * coef_uv[2][i]);
|
| 372 |
+
}
|
| 373 |
+
const auto p = coef_v[0] + v * (coef_v[1] + v * (coef_v[2] + v * coef_v[3]));
|
| 374 |
+
const auto q = coef_v[4] + v * (coef_v[5] + v * (coef_v[6] + v * coef_v[7]));
|
| 375 |
+
return static_cast<scalar_t>(compat_exp(p / q));
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
|
| 379 |
+
// Assumes x is close to zero and uses a Taylor expansion.
|
| 380 |
+
template <typename scalar_t, typename accscalar_t>
|
| 381 |
+
C10_DEVICE inline scalar_t _beta_grad_alpha_small(scalar_t x, scalar_t alpha, scalar_t beta) {
|
| 382 |
+
const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha)
|
| 383 |
+
- digamma_one<scalar_t, accscalar_t>(alpha + beta) - compat_log(x);
|
| 384 |
+
scalar_t numer = 1;
|
| 385 |
+
scalar_t series = numer / alpha * (factor + 1 / alpha);
|
| 386 |
+
for (int i = 1; i <= 10; ++i) {
|
| 387 |
+
scalar_t casted_i = static_cast<scalar_t>(i);
|
| 388 |
+
numer *= (casted_i - beta) * x / casted_i;
|
| 389 |
+
const scalar_t denom = alpha + casted_i;
|
| 390 |
+
series += numer / denom * (factor + 1 / denom);
|
| 391 |
+
}
|
| 392 |
+
const scalar_t result = x * compat_pow(1 - x, -beta) * series;
|
| 393 |
+
return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt beta.
|
| 397 |
+
// Assumes x is close to zero and uses a Taylor expansion.
|
| 398 |
+
template <typename scalar_t, typename accscalar_t>
|
| 399 |
+
C10_DEVICE inline scalar_t _beta_grad_beta_small(scalar_t x, scalar_t alpha, scalar_t beta) {
|
| 400 |
+
const scalar_t factor = digamma_one<scalar_t, accscalar_t>(alpha + beta) - digamma_one<scalar_t, accscalar_t>(beta);
|
| 401 |
+
scalar_t numer = 1, betas = 1, dbetas = 0, series = factor / alpha;
|
| 402 |
+
for (int i = 1; i <= 8; ++i) {
|
| 403 |
+
scalar_t casted_i = static_cast<scalar_t>(i);
|
| 404 |
+
numer *= -x / casted_i;
|
| 405 |
+
dbetas = dbetas * (beta - casted_i) + betas;
|
| 406 |
+
betas = betas * (beta - casted_i);
|
| 407 |
+
series += numer / (alpha + casted_i) * (dbetas + factor * betas);
|
| 408 |
+
}
|
| 409 |
+
const scalar_t result = -compat_pow(1 - x, 1 - beta) * series;
|
| 410 |
+
return isnan(result) ? static_cast<scalar_t>( 0.f ) : result;
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha.
|
| 414 |
+
// Assumes alpha and beta are both large and uses a Rice saddle point expansion.
|
| 415 |
+
// To ensure numerical stability, this computation is performed at higher precision.
|
| 416 |
+
template<typename scalar_t, typename accscalar_t>
|
| 417 |
+
C10_DEVICE inline scalar_t _beta_grad_alpha_mid(accscalar_t x, accscalar_t alpha, accscalar_t beta) {
|
| 418 |
+
const accscalar_t total = alpha + beta;
|
| 419 |
+
const accscalar_t mean = alpha / total;
|
| 420 |
+
const accscalar_t std = compat_sqrt(alpha * beta / (total + 1)) / total;
|
| 421 |
+
if (mean - 0.1 * std <= x && x <= mean + 0.1 * std) {
|
| 422 |
+
// Avoid the singularity at x = mean.
|
| 423 |
+
const accscalar_t poly = 47 * x * (beta * beta) * (beta * beta) + alpha * (
|
| 424 |
+
(43 + 20 * (16 + 27 * beta) * x) * (beta * beta) * beta + alpha * (
|
| 425 |
+
3 * (59 + 180 * beta - 90 * x) * (beta * beta) + alpha * (
|
| 426 |
+
(453 + 1620 * beta * (1 - x) - 455 * x) * beta + alpha * (
|
| 427 |
+
8 * (1 - x) * (135 * beta - 11)))));
|
| 428 |
+
const accscalar_t prefactor_num = (1 + 12 * alpha) * (1 + 12 * beta) / (total * total);
|
| 429 |
+
const accscalar_t prefactor_den = 12960 * alpha * alpha * alpha * beta * beta * (1 + 12 * total);
|
| 430 |
+
return prefactor_num / (1 - x) * poly / prefactor_den;
|
| 431 |
+
}
|
| 432 |
+
const accscalar_t prefactor = -x / compat_sqrt(2 * alpha * beta / total);
|
| 433 |
+
const accscalar_t stirling = (1 + 1 / (12 * alpha) + 1 / (288 * alpha * alpha))
|
| 434 |
+
* (1 + 1 / (12 * beta) + 1 / (288 * beta * beta))
|
| 435 |
+
/ (1 + 1 / (12 * total) + 1 / (288 * total * total));
|
| 436 |
+
const accscalar_t term1_num = 2 * (alpha * alpha) * (x - 1) + alpha * beta * (x - 1) - x * (beta * beta);
|
| 437 |
+
const accscalar_t axbx = alpha * (x - 1) + beta * x;
|
| 438 |
+
const accscalar_t term1_den = compat_sqrt(2 * alpha / beta) * compat_pow(total, static_cast<accscalar_t>(1.5f)) * axbx * axbx;
|
| 439 |
+
const accscalar_t term1 = term1_num / term1_den;
|
| 440 |
+
const accscalar_t term2 = 0.5f * compat_log(alpha / (total * x));
|
| 441 |
+
const accscalar_t term3_num = compat_sqrt(8 * alpha * beta / total);
|
| 442 |
+
const accscalar_t term3_den = beta * x + alpha * (x - 1);
|
| 443 |
+
const accscalar_t term3 = term3_num / term3_den;
|
| 444 |
+
const accscalar_t term4_base = beta * compat_log(beta / (total * (1 - x))) +
|
| 445 |
+
alpha * compat_log(alpha / (total * x));
|
| 446 |
+
const accscalar_t term4 = compat_pow(term4_base, static_cast<accscalar_t>(-1.5f));
|
| 447 |
+
const accscalar_t term1234 = term1 + term2 * (term3 + (x < mean ? term4 : -term4));
|
| 448 |
+
return static_cast<scalar_t>(stirling * prefactor * term1234);
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
// Computes a scaled reparameterized gradient
|
| 452 |
+
// -(d/dalpha cdf(x;alpha,beta)) / pdf(x;alpha,beta) / (1-x)
|
| 453 |
+
// for random number x drawn from a Beta distribution Beta(alpha,beta).
|
| 454 |
+
// This function inputs total=alpha+beta to make it easy to implement
|
| 455 |
+
// Dirichlet reparameterized gradients in terms of Betas.
|
| 456 |
+
template<typename scalar_t, typename accscalar_t>
|
| 457 |
+
C10_HOST_DEVICE inline scalar_t dirichlet_grad_one(scalar_t x, scalar_t alpha, scalar_t total) {
|
| 458 |
+
accscalar_t x_ = static_cast<accscalar_t>(x);
|
| 459 |
+
accscalar_t alpha_ = static_cast<accscalar_t>(alpha);
|
| 460 |
+
accscalar_t total_ = static_cast<accscalar_t>(total);
|
| 461 |
+
|
| 462 |
+
const scalar_t beta = total - alpha;
|
| 463 |
+
const accscalar_t beta_ = total_ - alpha_;
|
| 464 |
+
const scalar_t boundary = total * x * (1 - x);
|
| 465 |
+
|
| 466 |
+
// Use an asymptotic approximation for x close to 0.
|
| 467 |
+
if (x <= 0.5f && boundary < 2.5f) {
|
| 468 |
+
return _beta_grad_alpha_small<scalar_t, accscalar_t>(x, alpha, beta);
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
// Use an asymptotic approximation for x close to 1.
|
| 472 |
+
if (x >= 0.5f && boundary < 0.75f) {
|
| 473 |
+
return -_beta_grad_beta_small<scalar_t, accscalar_t>(1 - x, beta, alpha);
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
// Use an asymptotic approximation when alpha and (total - alpha) are both large.
|
| 477 |
+
if (alpha > 6 && beta > 6) {
|
| 478 |
+
return _beta_grad_alpha_mid<scalar_t, accscalar_t>(x_, alpha_, beta_);
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
// Use a rational correction to an analytic approximation.
|
| 482 |
+
static const accscalar_t c[2][3][3][4] = {
|
| 483 |
+
{{{1.003668233, -0.01061107488, -0.0657888334, 0.01201642863},
|
| 484 |
+
{0.6336835991, -0.3557432599, 0.05486251648, -0.001465281033},
|
| 485 |
+
{-0.03276231906, 0.004474107445, 0.002429354597, -0.0001557569013}},
|
| 486 |
+
{{0.221950385, -0.3187676331, 0.01799915743, 0.01074823814},
|
| 487 |
+
{-0.2951249643, 0.06219954479, 0.01535556598, 0.001550077057},
|
| 488 |
+
{0.02155310298, 0.004170831599, 0.001292462449, 6.976601077e-05}},
|
| 489 |
+
{{-0.05980841433, 0.008441916499, 0.01085618172, 0.002319392565},
|
| 490 |
+
{0.02911413504, 0.01400243777, -0.002721828457, 0.000751041181},
|
| 491 |
+
{0.005900514878, -0.001936558688, -9.495446725e-06, 5.385558597e-05}}},
|
| 492 |
+
{{{1, -0.02924021934, -0.04438342661, 0.007285809825},
|
| 493 |
+
{0.6357567472, -0.3473456711, 0.05454656494, -0.002407477521},
|
| 494 |
+
{-0.03301322327, 0.004845219414, 0.00231480583, -0.0002307248149}},
|
| 495 |
+
{{0.5925320577, -0.1757678135, 0.01505928619, 0.000564515273},
|
| 496 |
+
{0.1014815858, -0.06589186703, 0.01272886114, -0.0007316646956},
|
| 497 |
+
{-0.007258481865, 0.001096195486, 0.0003934994223, -4.12701925e-05}},
|
| 498 |
+
{{0.06469649321, -0.0236701437, 0.002902096474, -5.896963079e-05},
|
| 499 |
+
{0.001925008108, -0.002869809258, 0.0008000589141, -6.063713228e-05},
|
| 500 |
+
{-0.0003477407336, 6.959756487e-05, 1.097287507e-05, -1.650964693e-06}}},
|
| 501 |
+
};
|
| 502 |
+
const accscalar_t u = compat_log(x_);
|
| 503 |
+
const accscalar_t a = compat_log(alpha_) - u;
|
| 504 |
+
const accscalar_t b = compat_log(total_) - a;
|
| 505 |
+
const accscalar_t pow_u[3] = {1, u, u * u};
|
| 506 |
+
const accscalar_t pow_a[3] = {1, a, a * a};
|
| 507 |
+
accscalar_t p = 0.0;
|
| 508 |
+
accscalar_t q = 0.0;
|
| 509 |
+
for (int i = 0; i < 3; ++i) {
|
| 510 |
+
for (int j = 0; j < 3; ++j) {
|
| 511 |
+
const accscalar_t ua = pow_u[i] * pow_a[j];
|
| 512 |
+
p += ua * (c[0][i][j][0] + b * (c[0][i][j][1] + b * (c[0][i][j][2] + b * c[0][i][j][3])));
|
| 513 |
+
q += ua * (c[1][i][j][0] + b * (c[1][i][j][1] + b * (c[1][i][j][2] + b * c[1][i][j][3])));
|
| 514 |
+
}
|
| 515 |
+
}
|
| 516 |
+
const accscalar_t approx = x_ * (digamma_one<scalar_t, accscalar_t>(total_) - digamma_one<scalar_t, accscalar_t>(alpha_)) / beta_;
|
| 517 |
+
return static_cast<scalar_t>(p / q * approx);
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
} // namespace
|
| 521 |
+
|
| 522 |
+
#else
|
| 523 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 524 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/EmbeddingBag.h
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <ATen/Config.h>
|
| 5 |
+
#include <cstdint>
|
| 6 |
+
|
| 7 |
+
#ifdef USE_FBGEMM
|
| 8 |
+
#include <fbgemm/FbgemmEmbedding.h>
|
| 9 |
+
#endif
|
| 10 |
+
|
| 11 |
+
namespace at::native {
|
| 12 |
+
|
| 13 |
+
enum class EmbeddingBagMode {
|
| 14 |
+
SUM = 0,
|
| 15 |
+
MEAN = 1,
|
| 16 |
+
MAX = 2,
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
[[maybe_unused]] static bool operator==(int64_t op1, EmbeddingBagMode op2) {
|
| 20 |
+
return op1 == static_cast<int64_t>(op2);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
[[maybe_unused]] static bool operator!=(int64_t op1, EmbeddingBagMode op2) {
|
| 24 |
+
return !(op1 == op2);
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
void check_arguments(
|
| 28 |
+
const Tensor& weight,
|
| 29 |
+
const Tensor& indices,
|
| 30 |
+
const Tensor& offsets,
|
| 31 |
+
const int64_t mode,
|
| 32 |
+
const std::optional<Tensor>& per_sample_weights,
|
| 33 |
+
bool include_last_offset);
|
| 34 |
+
|
| 35 |
+
void make_bag_size_out(
|
| 36 |
+
Tensor& bag_size_out,
|
| 37 |
+
const Tensor& offsets,
|
| 38 |
+
const Tensor& indices,
|
| 39 |
+
const int64_t mode,
|
| 40 |
+
const bool include_last_offset,
|
| 41 |
+
const bool requires_grad);
|
| 42 |
+
|
| 43 |
+
void make_max_indices_out(
|
| 44 |
+
Tensor& max_indices_out,
|
| 45 |
+
const Tensor& weight,
|
| 46 |
+
const Tensor& indices,
|
| 47 |
+
const Tensor& offsets,
|
| 48 |
+
const Tensor& bag_size,
|
| 49 |
+
const int64_t mode,
|
| 50 |
+
bool include_last_offset);
|
| 51 |
+
|
| 52 |
+
void make_offset2bag_out(
|
| 53 |
+
Tensor& offset2bag,
|
| 54 |
+
Tensor& output,
|
| 55 |
+
const Tensor& weight,
|
| 56 |
+
const Tensor& indices,
|
| 57 |
+
const Tensor& offsets,
|
| 58 |
+
const int64_t mode,
|
| 59 |
+
const std::optional<Tensor>& per_sample_weights,
|
| 60 |
+
const int64_t padding_idx = -1);
|
| 61 |
+
|
| 62 |
+
#ifdef USE_FBGEMM
|
| 63 |
+
|
| 64 |
+
template<bool has_weight, typename TIndex, typename TData>
|
| 65 |
+
struct _CallbackAndBlockSize {
|
| 66 |
+
using TCallback = typename fbgemm::EmbeddingSpMDMKernelSignature<TData, TIndex, TIndex, TData>::Type;
|
| 67 |
+
|
| 68 |
+
int64_t blockSize = -1;
|
| 69 |
+
TCallback callback = nullptr;
|
| 70 |
+
|
| 71 |
+
static TCallback generateCallback(int64_t block_size) {
|
| 72 |
+
return fbgemm::GenerateEmbeddingSpMDM<TData, TIndex, TIndex, TData>(
|
| 73 |
+
block_size,
|
| 74 |
+
has_weight,
|
| 75 |
+
/* normalize_by_lengths */false,
|
| 76 |
+
/* prefetch */16,
|
| 77 |
+
/* is_weight_positional */false,
|
| 78 |
+
/* use_offsets */true);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
_CallbackAndBlockSize() = default;
|
| 82 |
+
|
| 83 |
+
explicit _CallbackAndBlockSize(std::optional<int64_t> maybe_block_size)
|
| 84 |
+
: blockSize(maybe_block_size.value_or(-1))
|
| 85 |
+
, callback(maybe_block_size.has_value() ? generateCallback(maybe_block_size.value()) : nullptr)
|
| 86 |
+
{}
|
| 87 |
+
};
|
| 88 |
+
|
| 89 |
+
template<typename... StorageMixins>
|
| 90 |
+
struct _EmbeddingBagKernelCacheImpl : private StorageMixins... {
|
| 91 |
+
|
| 92 |
+
_EmbeddingBagKernelCacheImpl() = default;
|
| 93 |
+
// use each of the mixins to store corresponding kernel and block size
|
| 94 |
+
explicit _EmbeddingBagKernelCacheImpl(std::optional<int64_t> maybe_block_size)
|
| 95 |
+
: StorageMixins(maybe_block_size)...
|
| 96 |
+
{}
|
| 97 |
+
|
| 98 |
+
// this method is thread safe (call sites may call from different threads)
|
| 99 |
+
template<bool has_weight, typename TIndex, typename TData>
|
| 100 |
+
typename _CallbackAndBlockSize<has_weight, TIndex, TData>::TCallback
|
| 101 |
+
getCallback(int64_t block_size) const {
|
| 102 |
+
// if the cache doesn't store the kernel for the incoming block size
|
| 103 |
+
// (so it is different from the one stored in corresponding mixin)
|
| 104 |
+
// regenerate the kernel (not writing it into the cache so we avoid locks)
|
| 105 |
+
if (block_size != _CallbackAndBlockSize<has_weight, TIndex, TData>::blockSize) {
|
| 106 |
+
return _CallbackAndBlockSize<has_weight, TIndex, TData>::generateCallback(block_size);
|
| 107 |
+
}
|
| 108 |
+
// else retrieve the cached kernel from the corresponding mixin
|
| 109 |
+
return _CallbackAndBlockSize<has_weight, TIndex, TData>::callback;
|
| 110 |
+
}
|
| 111 |
+
};
|
| 112 |
+
|
| 113 |
+
// instantiate the cache with the list of storage mixins
|
| 114 |
+
// for each of the 8 _EmbeddingBagKernelCache* usages in the EmbeddingBag.cpp impl file
|
| 115 |
+
using _EmbeddingBagKernelCache = _EmbeddingBagKernelCacheImpl<
|
| 116 |
+
_CallbackAndBlockSize<true, int32_t, float>,
|
| 117 |
+
_CallbackAndBlockSize<false, int32_t, float>,
|
| 118 |
+
_CallbackAndBlockSize<true, int64_t, float>,
|
| 119 |
+
_CallbackAndBlockSize<false, int64_t, float>,
|
| 120 |
+
_CallbackAndBlockSize<true, int32_t, unsigned short>,
|
| 121 |
+
_CallbackAndBlockSize<false, int32_t, unsigned short>,
|
| 122 |
+
_CallbackAndBlockSize<true, int64_t, unsigned short>,
|
| 123 |
+
_CallbackAndBlockSize<false, int64_t, unsigned short>>;
|
| 124 |
+
#else
|
| 125 |
+
struct _EmbeddingBagKernelCache {
|
| 126 |
+
explicit _EmbeddingBagKernelCache(std::optional<int64_t> /* maybe_block_size */) {}
|
| 127 |
+
};
|
| 128 |
+
#endif
|
| 129 |
+
|
| 130 |
+
void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag,
|
| 131 |
+
Tensor& bag_size, Tensor* max_indices,
|
| 132 |
+
const Tensor &weight, const Tensor &indices,
|
| 133 |
+
const Tensor &offsets, const int64_t mode = 0,
|
| 134 |
+
const std::optional<Tensor>& per_sample_weights = std::nullopt,
|
| 135 |
+
bool include_last_offset = false,
|
| 136 |
+
int64_t padding_idx = -1,
|
| 137 |
+
_EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
|
| 138 |
+
|
| 139 |
+
void _embedding_bag_cpu_out(
|
| 140 |
+
at::Tensor& output,
|
| 141 |
+
at::Tensor& offset2bag,
|
| 142 |
+
at::Tensor& bag_size,
|
| 143 |
+
at::Tensor* p_max_indices,
|
| 144 |
+
const at::Tensor& weight,
|
| 145 |
+
const at::Tensor& indices,
|
| 146 |
+
const at::Tensor& offsets,
|
| 147 |
+
const bool scale_grad_by_freq,
|
| 148 |
+
const int64_t mode,
|
| 149 |
+
const bool sparse,
|
| 150 |
+
const std::optional<at::Tensor>& per_sample_weights,
|
| 151 |
+
const bool include_last_offset,
|
| 152 |
+
const std::optional<int64_t>& padding_idx,
|
| 153 |
+
_EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
|
| 154 |
+
|
| 155 |
+
} // namespace at::native
|
| 156 |
+
|
| 157 |
+
#else
|
| 158 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 159 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Fill.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
// Functions that fill Tensors with constants. Implementations are in Fill.cpp.
|
| 3 |
+
|
| 4 |
+
#pragma once
|
| 5 |
+
|
| 6 |
+
#include <ATen/native/DispatchStub.h>
|
| 7 |
+
|
| 8 |
+
namespace c10 {
|
| 9 |
+
class Scalar;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
namespace at {
|
| 13 |
+
class Tensor;
|
| 14 |
+
struct TensorIterator;
|
| 15 |
+
|
| 16 |
+
namespace native {
|
| 17 |
+
|
| 18 |
+
DECLARE_DISPATCH(void(*)(TensorIterator&, const c10::Scalar&), fill_stub)
|
| 19 |
+
|
| 20 |
+
Tensor& fill_out(Tensor& self, const Scalar& value);
|
| 21 |
+
|
| 22 |
+
}} // namespace at::native
|
| 23 |
+
|
| 24 |
+
#else
|
| 25 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 26 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/ForeachUtils.h
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/Device.h>
|
| 5 |
+
#include <ATen/Dispatch.h>
|
| 6 |
+
#include <ATen/ScalarType.h>
|
| 7 |
+
#include <ATen/core/Tensor.h>
|
| 8 |
+
#include <ATen/native/utils/ParamsHash.h>
|
| 9 |
+
#include <c10/util/Exception.h>
|
| 10 |
+
#include <c10/util/irange.h>
|
| 11 |
+
|
| 12 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 13 |
+
#include <ATen/NativeFunctions.h>
|
| 14 |
+
#else
|
| 15 |
+
#include <ATen/ops/result_type_native.h>
|
| 16 |
+
#endif
|
| 17 |
+
|
| 18 |
+
#include <unordered_map>
|
| 19 |
+
#include <vector>
|
| 20 |
+
|
| 21 |
+
namespace at::native {
|
| 22 |
+
namespace {
|
| 23 |
+
// Check if tensor list has either a boolean tensor or a integer tensor
|
| 24 |
+
inline bool has_integral_tensor(TensorList tensors, const bool includeBool) {
|
| 25 |
+
return std::any_of(
|
| 26 |
+
tensors.begin(), tensors.end(), [includeBool](const auto& t) {
|
| 27 |
+
return at::isIntegralType(t.scalar_type(), includeBool);
|
| 28 |
+
});
|
| 29 |
+
}
|
| 30 |
+
// check if tensor list has bool tensors
|
| 31 |
+
inline bool has_bool_tensor(TensorList tensors) {
|
| 32 |
+
return std::any_of(tensors.begin(), tensors.end(), [](const auto& t) -> bool {
|
| 33 |
+
return t.scalar_type() == ScalarType::Bool;
|
| 34 |
+
});
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Check foreach API restrictions
|
| 38 |
+
// - Tensor lists must be non-empty.
|
| 39 |
+
// - All TensorLists and ScalarLists must have the same number of elements.
|
| 40 |
+
// - Corresponding tensors must have the same size.
|
| 41 |
+
inline void check_foreach_api_restrictions(TensorList tensors) {
|
| 42 |
+
TORCH_CHECK(!tensors.empty(), "Tensor list must have at least one tensor.");
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
inline void check_foreach_api_restrictions(
|
| 46 |
+
TensorList tensors,
|
| 47 |
+
ArrayRef<Scalar> scalars) {
|
| 48 |
+
check_foreach_api_restrictions(tensors);
|
| 49 |
+
TORCH_CHECK(
|
| 50 |
+
tensors.size() == scalars.size(),
|
| 51 |
+
"Tensor list must have same number of elements as scalar list.");
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
inline void check_foreach_api_restrictions(
|
| 55 |
+
TensorList tensors1,
|
| 56 |
+
TensorList tensors2) {
|
| 57 |
+
check_foreach_api_restrictions(tensors1);
|
| 58 |
+
check_foreach_api_restrictions(tensors2);
|
| 59 |
+
TORCH_CHECK(
|
| 60 |
+
tensors1.size() == tensors2.size(),
|
| 61 |
+
"Tensor lists must have the same number of tensors, got ",
|
| 62 |
+
tensors1.size(),
|
| 63 |
+
" and ",
|
| 64 |
+
tensors2.size());
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
inline void check_foreach_api_restrictions(
|
| 68 |
+
TensorList tensors1,
|
| 69 |
+
TensorList tensors2,
|
| 70 |
+
TensorList tensors3) {
|
| 71 |
+
check_foreach_api_restrictions(tensors1, tensors2);
|
| 72 |
+
check_foreach_api_restrictions(tensors1, tensors3);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
inline void check_foreach_api_restrictions(
|
| 76 |
+
TensorList tensors1,
|
| 77 |
+
TensorList tensors2,
|
| 78 |
+
TensorList tensors3,
|
| 79 |
+
ArrayRef<Scalar> scalars) {
|
| 80 |
+
check_foreach_api_restrictions(tensors1, tensors2, tensors3);
|
| 81 |
+
check_foreach_api_restrictions(tensors1, scalars);
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
inline void check_foreach_api_restrictions(
|
| 85 |
+
TensorList tensors1,
|
| 86 |
+
TensorList tensors2,
|
| 87 |
+
ArrayRef<Scalar> scalars) {
|
| 88 |
+
check_foreach_api_restrictions(tensors1, tensors2);
|
| 89 |
+
check_foreach_api_restrictions(tensors1, scalars);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// Helper function called in check_fast_path_restrictions to check whether all
|
| 93 |
+
// corresponding tensors (aligning in index across the tensorLists) share the
|
| 94 |
+
// same device and dtype.
|
| 95 |
+
inline bool _check_tensors_share_device_and_dtype(
|
| 96 |
+
ArrayRef<TensorList> tensorLists,
|
| 97 |
+
const bool skip_dtype_check = false) {
|
| 98 |
+
const auto expected_dtype = tensorLists[0][0].dtype();
|
| 99 |
+
const auto expected_device = tensorLists[0][0].device();
|
| 100 |
+
|
| 101 |
+
auto is_tensor_okay = [&](const Tensor& tensor) {
|
| 102 |
+
return (skip_dtype_check || tensor.dtype() == expected_dtype) &&
|
| 103 |
+
tensor.device() == expected_device && tensor.layout() == at::kStrided &&
|
| 104 |
+
tensor.is_non_overlapping_and_dense();
|
| 105 |
+
};
|
| 106 |
+
|
| 107 |
+
return std::all_of(
|
| 108 |
+
tensorLists.cbegin(),
|
| 109 |
+
tensorLists.cend(),
|
| 110 |
+
[&](const TensorList& tensorList) {
|
| 111 |
+
return std::all_of(
|
| 112 |
+
tensorList.cbegin(), tensorList.cend(), is_tensor_okay);
|
| 113 |
+
});
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Helper function called in check_fast_path_restrictions to check if
|
| 117 |
+
// corresponding tensors in tensor lists have the same sizes and strides.
|
| 118 |
+
inline bool _check_tensors_share_sizes_and_strides(
|
| 119 |
+
ArrayRef<TensorList> tensorLists) {
|
| 120 |
+
auto is_diff_stride = [](const IntArrayRef& size,
|
| 121 |
+
const IntArrayRef& left_stride,
|
| 122 |
+
const IntArrayRef& right_stride) -> bool {
|
| 123 |
+
const size_t size_size = size.size();
|
| 124 |
+
for (const auto dim : c10::irange(size_size)) {
|
| 125 |
+
if (size[dim] == 1)
|
| 126 |
+
continue;
|
| 127 |
+
if (left_stride[dim] != right_stride[dim]) {
|
| 128 |
+
return true;
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
return false;
|
| 132 |
+
};
|
| 133 |
+
for (const auto i : c10::irange(1, tensorLists.size())) {
|
| 134 |
+
for (const auto j : c10::irange(tensorLists[0].size())) {
|
| 135 |
+
if (tensorLists[0][j].sizes() != tensorLists[i][j].sizes() ||
|
| 136 |
+
is_diff_stride(
|
| 137 |
+
tensorLists[0][j].sizes(),
|
| 138 |
+
tensorLists[0][j].strides(),
|
| 139 |
+
tensorLists[i][j].strides())) {
|
| 140 |
+
return false;
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
return true;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// Helper function called in check_fast_path_restrictions to check whether
|
| 149 |
+
// all tensors type promote properly with the scalars in scalarList. This
|
| 150 |
+
// function assumes that _check_tensors_share_device_and_dtype has already been
|
| 151 |
+
// called so that all corresponding tensors in tensorLists have the same dtype.
|
| 152 |
+
// Then, it is sufficient to check the type promotion with just one tensorList.
|
| 153 |
+
inline bool _check_tensors_do_type_promotion_with_scalars(
|
| 154 |
+
TensorList tensorList,
|
| 155 |
+
ArrayRef<Scalar> scalarList = {},
|
| 156 |
+
bool does_op_promote_integer_inputs_to_float = false) {
|
| 157 |
+
for (const auto i : c10::irange(tensorList.size())) {
|
| 158 |
+
// For division, integer inputs will result in float.
|
| 159 |
+
if (does_op_promote_integer_inputs_to_float &&
|
| 160 |
+
at::isIntegralType(tensorList[i].scalar_type(), /*includeBool*/ true)) {
|
| 161 |
+
return false;
|
| 162 |
+
}
|
| 163 |
+
if (!scalarList.empty()) {
|
| 164 |
+
const auto& scalar =
|
| 165 |
+
scalarList.size() == 1 ? scalarList[0] : scalarList[i];
|
| 166 |
+
const auto& tensor = tensorList[i];
|
| 167 |
+
// note(mkozuki): This check might be responsible for
|
| 168 |
+
// `_foreach_add(bool_tensors, bool_tensors)` being pushed to slow path.
|
| 169 |
+
if (tensor.scalar_type() != at::native::result_type(scalar, tensor)) {
|
| 170 |
+
return false;
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
return true;
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// To go via 'fast' path, several conditions must be satisfied
|
| 179 |
+
// - All tensors in all lists must have the same dtype.
|
| 180 |
+
// - All tensors must be on the same device
|
| 181 |
+
// - All tensors must have strided layout
|
| 182 |
+
// - All tensors must be non-overlapping and dense
|
| 183 |
+
// - Resulting tensor must have the same dtype as the input one
|
| 184 |
+
|
| 185 |
+
// [note: what's ``does_op_promote_integer_inputs_to_float=true``?]
|
| 186 |
+
// ``does_op_promote_integer_inputs_to_float=true`` means that the result of
|
| 187 |
+
// the op will be float even if inputs are integer or boolean, which
|
| 188 |
+
// currently fast path does not support. In short, this flag, when
|
| 189 |
+
// turned on, gatekeeps the op from going down the fastpath.
|
| 190 |
+
|
| 191 |
+
// Please, make sure to call check_foreach_api_restrictions before calling this
|
| 192 |
+
// method. There is a set of preconditions that have to be satisfied.
|
| 193 |
+
inline bool check_fast_path_restrictions(
|
| 194 |
+
ArrayRef<TensorList> tensorLists,
|
| 195 |
+
ArrayRef<Scalar> scalarList = {},
|
| 196 |
+
bool does_op_promote_integer_inputs_to_float = false) {
|
| 197 |
+
return _check_tensors_share_device_and_dtype(tensorLists) &&
|
| 198 |
+
_check_tensors_share_sizes_and_strides(tensorLists) &&
|
| 199 |
+
_check_tensors_do_type_promotion_with_scalars(
|
| 200 |
+
tensorLists[0],
|
| 201 |
+
scalarList,
|
| 202 |
+
does_op_promote_integer_inputs_to_float);
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
inline std::vector<c10::Scalar> convert_tensor_to_scalar_list(
|
| 206 |
+
const Tensor& scalarList_,
|
| 207 |
+
int64_t expect_length) {
|
| 208 |
+
std::vector<c10::Scalar> scalarList;
|
| 209 |
+
TORCH_CHECK(
|
| 210 |
+
scalarList_.device() == c10::kCPU,
|
| 211 |
+
"Expected scalars to be on CPU, got ",
|
| 212 |
+
scalarList_.device(),
|
| 213 |
+
" instead.");
|
| 214 |
+
TORCH_CHECK(
|
| 215 |
+
scalarList_.is_contiguous(), "Expected scalars to be contiguous.");
|
| 216 |
+
TORCH_CHECK(
|
| 217 |
+
scalarList_.dim() == 1,
|
| 218 |
+
"Expected packed scalar Tensor to be of dimension 1. Got ",
|
| 219 |
+
scalarList_.dim(),
|
| 220 |
+
" instead.");
|
| 221 |
+
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4(
|
| 222 |
+
kComplexHalf,
|
| 223 |
+
kHalf,
|
| 224 |
+
kBool,
|
| 225 |
+
kBFloat16,
|
| 226 |
+
scalarList_.scalar_type(),
|
| 227 |
+
"convert_tensor_to_scalar_list",
|
| 228 |
+
[&]() {
|
| 229 |
+
const scalar_t* scalar_data = scalarList_.const_data_ptr<scalar_t>();
|
| 230 |
+
TORCH_CHECK(
|
| 231 |
+
(expect_length == scalarList_.size(0)),
|
| 232 |
+
"Expected length of scalars to match input of length ",
|
| 233 |
+
expect_length,
|
| 234 |
+
" but got ",
|
| 235 |
+
scalarList_.size(0),
|
| 236 |
+
" instead.");
|
| 237 |
+
for (int64_t i = 0; i < scalarList_.size(0); i++) {
|
| 238 |
+
scalarList.emplace_back(scalar_data[i]);
|
| 239 |
+
}
|
| 240 |
+
});
|
| 241 |
+
return scalarList;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// see: [note: what's ``does_op_promote_integer_inputs_to_float=true``?]
|
| 245 |
+
inline bool can_use_fast_route(
|
| 246 |
+
ArrayRef<TensorList> tensorLists,
|
| 247 |
+
ArrayRef<Scalar> scalarList = {},
|
| 248 |
+
bool does_op_promote_integer_inputs_to_float = false) {
|
| 249 |
+
return check_fast_path_restrictions(
|
| 250 |
+
tensorLists, scalarList, does_op_promote_integer_inputs_to_float);
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
// see: [note: what's ``does_op_promote_integer_inputs_to_float=true``?]
|
| 254 |
+
inline bool can_use_fast_route(
|
| 255 |
+
TensorList tensors1,
|
| 256 |
+
TensorList tensors2,
|
| 257 |
+
bool does_op_promote_integer_inputs_to_float = false) {
|
| 258 |
+
return can_use_fast_route(
|
| 259 |
+
{tensors1, tensors2}, {}, does_op_promote_integer_inputs_to_float);
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
using DeviceDtypeKey = std::pair<at::Device, at::ScalarType>;
|
| 263 |
+
using IndicesT = std::vector<size_t>;
|
| 264 |
+
using nested_optional_tensorvec_t =
|
| 265 |
+
std::vector<std::vector<std::optional<at::Tensor>>>;
|
| 266 |
+
using TensorsAndIndicesT = std::pair<nested_optional_tensorvec_t, IndicesT>;
|
| 267 |
+
using FlatMap = std::unordered_map<
|
| 268 |
+
DeviceDtypeKey,
|
| 269 |
+
TensorsAndIndicesT,
|
| 270 |
+
ParamsHash<DeviceDtypeKey>>;
|
| 271 |
+
|
| 272 |
+
inline FlatMap _group_tensors_by_first_tensors_device_and_dtype(
|
| 273 |
+
const nested_optional_tensorvec_t& nested_tensorlist,
|
| 274 |
+
const bool with_indices) {
|
| 275 |
+
FlatMap grouped_tensors_with_indices;
|
| 276 |
+
|
| 277 |
+
TORCH_CHECK(!nested_tensorlist.empty());
|
| 278 |
+
TORCH_CHECK(!nested_tensorlist[0].empty());
|
| 279 |
+
const auto num_lists = nested_tensorlist.size();
|
| 280 |
+
const auto num_tensors = nested_tensorlist[0].size();
|
| 281 |
+
|
| 282 |
+
TORCH_CHECK(std::all_of(
|
| 283 |
+
nested_tensorlist.cbegin(),
|
| 284 |
+
nested_tensorlist.cend(),
|
| 285 |
+
[&](const auto& tensorlist) -> bool {
|
| 286 |
+
// note(crcrpar): Allow empty tensorlists following
|
| 287 |
+
// ref:
|
| 288 |
+
// https://github.com/pytorch/pytorch/blob/85885301fd3c6adb8b9dc3cf7afadf6945566684/torch/utils/_foreach_utils.py#L21-L24
|
| 289 |
+
return tensorlist.size() == num_tensors || tensorlist.size() == 0;
|
| 290 |
+
}));
|
| 291 |
+
|
| 292 |
+
for (const auto& tensor_index : c10::irange(num_tensors)) {
|
| 293 |
+
const auto key = [&]() -> DeviceDtypeKey {
|
| 294 |
+
const auto t = nested_tensorlist[0][tensor_index];
|
| 295 |
+
TORCH_CHECK(
|
| 296 |
+
t.has_value(),
|
| 297 |
+
"Tensors of the first list of nested Tensor lists are supposed to be defined but ",
|
| 298 |
+
"the ",
|
| 299 |
+
tensor_index,
|
| 300 |
+
"-th Tensor is not.");
|
| 301 |
+
return {t->device(), t->scalar_type()};
|
| 302 |
+
}();
|
| 303 |
+
TORCH_CHECK(
|
| 304 |
+
std::all_of(
|
| 305 |
+
nested_tensorlist.cbegin(),
|
| 306 |
+
nested_tensorlist.cend(),
|
| 307 |
+
[&](const auto& tensorlist) -> bool {
|
| 308 |
+
if (tensorlist.size() == 0) {
|
| 309 |
+
return true;
|
| 310 |
+
}
|
| 311 |
+
const auto& tensor = tensorlist[tensor_index];
|
| 312 |
+
// note(crcrpar): Currently the scope of this function is
|
| 313 |
+
// optimizers so there could be `state_steps` and other scalars
|
| 314 |
+
// whose elements are float tensors no matter what the parameter's
|
| 315 |
+
// dtype is.
|
| 316 |
+
if (!tensor.has_value()) {
|
| 317 |
+
return true;
|
| 318 |
+
} else {
|
| 319 |
+
const auto s = tensor->scalar_type();
|
| 320 |
+
const auto d = tensor->device();
|
| 321 |
+
// Note: `step` or `state_step` is float32 by default.
|
| 322 |
+
if (key.first == d) {
|
| 323 |
+
return key.second == s || s == at::ScalarType::Float ||
|
| 324 |
+
s == at::ScalarType::Double;
|
| 325 |
+
} else if (d.is_cpu()) {
|
| 326 |
+
// note(crcrpar): There are some test cases (e.g.
|
| 327 |
+
// TestOptim::test_adam) where state_steps are on CPU and the
|
| 328 |
+
// others are on CUDA. Currently a state_step Tensor has the
|
| 329 |
+
// dtype of float.
|
| 330 |
+
return s == at::ScalarType::Float ||
|
| 331 |
+
s == at::ScalarType::Double;
|
| 332 |
+
} else {
|
| 333 |
+
return false;
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
}),
|
| 337 |
+
"Tensors of the same index must be on the same device and the same dtype except `step` tensors that can be CPU and float32/64 notwithstanding");
|
| 338 |
+
grouped_tensors_with_indices.try_emplace(
|
| 339 |
+
key,
|
| 340 |
+
TensorsAndIndicesT{
|
| 341 |
+
[&]() -> nested_optional_tensorvec_t {
|
| 342 |
+
nested_optional_tensorvec_t nested_tensorvec;
|
| 343 |
+
nested_tensorvec.reserve(num_lists);
|
| 344 |
+
for (const auto& i : c10::irange(num_lists)) {
|
| 345 |
+
std::vector<std::optional<at::Tensor>> tensors;
|
| 346 |
+
if (!nested_tensorlist[i].empty()) {
|
| 347 |
+
// NB: num_tensors is the max possible length for any of
|
| 348 |
+
// the inner lists of tensor references. Reserving the max
|
| 349 |
+
// trades memory for perf. This should not have significant
|
| 350 |
+
// impact.
|
| 351 |
+
tensors.reserve(num_tensors);
|
| 352 |
+
}
|
| 353 |
+
nested_tensorvec.emplace_back(std::move(tensors));
|
| 354 |
+
}
|
| 355 |
+
return nested_tensorvec;
|
| 356 |
+
}(),
|
| 357 |
+
[&]() -> IndicesT {
|
| 358 |
+
if (!with_indices) {
|
| 359 |
+
return {};
|
| 360 |
+
} else {
|
| 361 |
+
IndicesT indices;
|
| 362 |
+
indices.reserve(num_tensors);
|
| 363 |
+
return indices;
|
| 364 |
+
}
|
| 365 |
+
}()});
|
| 366 |
+
for (const auto& list_index : c10::irange(num_lists)) {
|
| 367 |
+
if (!nested_tensorlist[list_index].empty()) {
|
| 368 |
+
grouped_tensors_with_indices[key].first[list_index].emplace_back(
|
| 369 |
+
nested_tensorlist[list_index][tensor_index]);
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
if (with_indices) {
|
| 373 |
+
grouped_tensors_with_indices[key].second.emplace_back(tensor_index);
|
| 374 |
+
}
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
return grouped_tensors_with_indices;
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
} // namespace
|
| 381 |
+
} // namespace at::native
|
| 382 |
+
|
| 383 |
+
#else
|
| 384 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 385 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FractionalMaxPooling.h
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <ATen/TensorUtils.h>
|
| 5 |
+
#include <c10/util/irange.h>
|
| 6 |
+
|
| 7 |
+
namespace at::native {
|
| 8 |
+
|
| 9 |
+
template<typename scalar_t>
|
| 10 |
+
inline std::vector<int64_t> generate_intervals(
|
| 11 |
+
scalar_t sample,
|
| 12 |
+
int64_t inputSize,
|
| 13 |
+
int64_t outputSize,
|
| 14 |
+
int64_t poolSize) {
|
| 15 |
+
std::vector<int64_t> sequence(outputSize);
|
| 16 |
+
if (outputSize > 1) {
|
| 17 |
+
scalar_t alpha = static_cast<scalar_t>(inputSize - poolSize) /
|
| 18 |
+
static_cast<scalar_t>(outputSize - 1);
|
| 19 |
+
|
| 20 |
+
for (const auto i : c10::irange(outputSize - 1)) {
|
| 21 |
+
sequence[i] =
|
| 22 |
+
static_cast<int>((i + sample) * alpha) - static_cast<int>(sample * alpha);
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
if (outputSize > 0) {
|
| 26 |
+
sequence[outputSize - 1] = inputSize - poolSize;
|
| 27 |
+
}
|
| 28 |
+
return sequence;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
template <int64_t ndim>
|
| 32 |
+
inline void fractional_max_pool_check_shape(
|
| 33 |
+
const Tensor& input,
|
| 34 |
+
const Tensor& randomSamples) {
|
| 35 |
+
|
| 36 |
+
TORCH_CHECK(
|
| 37 |
+
input.scalar_type() == randomSamples.scalar_type(),
|
| 38 |
+
"Expect _random_samples to have the same dtype as input");
|
| 39 |
+
|
| 40 |
+
int64_t ndimension = randomSamples.ndimension();
|
| 41 |
+
TORCH_CHECK(
|
| 42 |
+
ndimension == 3,
|
| 43 |
+
"Expect _random_samples to have 3 dimensions, got ", ndimension);
|
| 44 |
+
|
| 45 |
+
int64_t N = randomSamples.size(0);
|
| 46 |
+
int64_t C = randomSamples.size(1);
|
| 47 |
+
int64_t D = randomSamples.size(2);
|
| 48 |
+
|
| 49 |
+
int64_t input_batch = 0, input_channel = 0;
|
| 50 |
+
if (ndim == 2) {
|
| 51 |
+
// fractional_max_pool2d
|
| 52 |
+
if (input.ndimension() == 3) {
|
| 53 |
+
input_batch = 1;
|
| 54 |
+
input_channel = input.size(0);
|
| 55 |
+
} else {
|
| 56 |
+
input_batch = input.size(0);
|
| 57 |
+
input_channel = input.size(1);
|
| 58 |
+
}
|
| 59 |
+
} else {
|
| 60 |
+
// factional_max_pool3d
|
| 61 |
+
if (input.ndimension() == 4) {
|
| 62 |
+
input_batch = 1;
|
| 63 |
+
input_channel = input.size(0);
|
| 64 |
+
} else {
|
| 65 |
+
input_batch = input.size(0);
|
| 66 |
+
input_channel = input.size(1);
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
TORCH_CHECK(
|
| 71 |
+
N >= input_batch,
|
| 72 |
+
"Expect _random_samples.size(0) no less then input batch size.");
|
| 73 |
+
TORCH_CHECK(
|
| 74 |
+
C == input_channel,
|
| 75 |
+
"Expect _random_samples.size(1) equals to input channel size.");
|
| 76 |
+
TORCH_CHECK(
|
| 77 |
+
D == ndim,
|
| 78 |
+
"Expect _random_samples.size(2) equals to ", ndim, "; got ", D, ".");
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
} // namespace at::native
|
| 82 |
+
|
| 83 |
+
#else
|
| 84 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 85 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FunctionOfAMatrixUtils.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
#include <cstdint>
|
| 6 |
+
|
| 7 |
+
namespace at {
|
| 8 |
+
struct TensorIterator;
|
| 9 |
+
|
| 10 |
+
namespace native {
|
| 11 |
+
|
| 12 |
+
using _compute_linear_combination_fn = void(*)(
|
| 13 |
+
TensorIterator& iter,
|
| 14 |
+
int64_t in_stride,
|
| 15 |
+
int64_t coeff_stride,
|
| 16 |
+
int64_t num_summations
|
| 17 |
+
);
|
| 18 |
+
|
| 19 |
+
DECLARE_DISPATCH(_compute_linear_combination_fn, _compute_linear_combination_stub)
|
| 20 |
+
|
| 21 |
+
}} // namespace at::native
|
| 22 |
+
|
| 23 |
+
#else
|
| 24 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 25 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedAdagrad.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#include <ATen/core/Tensor.h>
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
|
| 5 |
+
namespace at::native {
|
| 6 |
+
|
| 7 |
+
using fused_adagrad_fn = void (*)(
|
| 8 |
+
const at::Tensor& param,
|
| 9 |
+
const at::Tensor& grad,
|
| 10 |
+
const at::Tensor& state_sum,
|
| 11 |
+
const at::Tensor& state_step,
|
| 12 |
+
const double lr,
|
| 13 |
+
const double lr_decay,
|
| 14 |
+
const double weight_decay,
|
| 15 |
+
const double eps,
|
| 16 |
+
const bool maximize,
|
| 17 |
+
const float* grad_scale_ptr);
|
| 18 |
+
|
| 19 |
+
DECLARE_DISPATCH(fused_adagrad_fn, fused_adagrad_stub)
|
| 20 |
+
|
| 21 |
+
} // namespace at::native
|
| 22 |
+
|
| 23 |
+
#else
|
| 24 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 25 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedAdam.h
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#include <ATen/core/Tensor.h>
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
|
| 5 |
+
namespace at::native {
|
| 6 |
+
|
| 7 |
+
enum class ADAM_MODE : uint8_t { ORIGINAL = 0, ADAMW = 1 };
|
| 8 |
+
|
| 9 |
+
using fused_adam_fn = void (*)(
|
| 10 |
+
const at::Tensor& param,
|
| 11 |
+
const at::Tensor& grad,
|
| 12 |
+
const at::Tensor& exp_avg,
|
| 13 |
+
const at::Tensor& exp_avg_sq,
|
| 14 |
+
const at::Tensor& max_exp_avg_sq,
|
| 15 |
+
const at::Tensor& state_step,
|
| 16 |
+
const double lr,
|
| 17 |
+
const double beta1,
|
| 18 |
+
const double beta2,
|
| 19 |
+
const double weight_decay,
|
| 20 |
+
const double eps,
|
| 21 |
+
const bool amsgrad,
|
| 22 |
+
const bool maximize,
|
| 23 |
+
const float* grad_scale_ptr,
|
| 24 |
+
const ADAM_MODE);
|
| 25 |
+
|
| 26 |
+
DECLARE_DISPATCH(fused_adam_fn, fused_adam_stub)
|
| 27 |
+
|
| 28 |
+
} // namespace at::native
|
| 29 |
+
|
| 30 |
+
#else
|
| 31 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 32 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/FusedSGD.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#include <ATen/core/Tensor.h>
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
|
| 5 |
+
namespace at::native {
|
| 6 |
+
|
| 7 |
+
using fused_sgd_fn = void (*)(
|
| 8 |
+
const at::Tensor& param,
|
| 9 |
+
const at::Tensor& grad,
|
| 10 |
+
const at::Tensor& momentum_buffer,
|
| 11 |
+
const double weight_decay,
|
| 12 |
+
const double momentum,
|
| 13 |
+
const double lr,
|
| 14 |
+
const double dampening,
|
| 15 |
+
const bool nesterov,
|
| 16 |
+
const bool maximize,
|
| 17 |
+
const bool is_first_step,
|
| 18 |
+
const float* grad_scale_ptr);
|
| 19 |
+
|
| 20 |
+
DECLARE_DISPATCH(fused_sgd_fn, fused_sgd_stub)
|
| 21 |
+
|
| 22 |
+
} // namespace at::native
|
| 23 |
+
|
| 24 |
+
#else
|
| 25 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 26 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Gelu.h
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <c10/util/Exception.h>
|
| 5 |
+
#include <string_view>
|
| 6 |
+
|
| 7 |
+
namespace at::native {
|
| 8 |
+
// These constants control the approximation behavior of gelu function.
|
| 9 |
+
enum class GeluType {
|
| 10 |
+
None, // Baseline Gelu
|
| 11 |
+
Tanh, // Tanh Gelu Approximation
|
| 12 |
+
END
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
inline GeluType get_gelutype_enum(const std::string_view approximate) {
|
| 16 |
+
if (approximate == "none") {
|
| 17 |
+
return GeluType::None;
|
| 18 |
+
} else if (approximate == "tanh") {
|
| 19 |
+
return GeluType::Tanh;
|
| 20 |
+
} else {
|
| 21 |
+
TORCH_CHECK(false, "approximate argument must be either none or tanh.");
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
inline std::string gelutype_to_string(const GeluType type) {
|
| 26 |
+
switch(type) {
|
| 27 |
+
case GeluType::None: return "none";
|
| 28 |
+
case GeluType::Tanh: return "tanh";
|
| 29 |
+
default: TORCH_CHECK(false, "unknown GELU type: ", static_cast<int>(type));
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
} // namespace at::native
|
| 35 |
+
|
| 36 |
+
#else
|
| 37 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 38 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <algorithm>
|
| 5 |
+
#include <cmath>
|
| 6 |
+
#include <cstdint>
|
| 7 |
+
#include <utility>
|
| 8 |
+
|
| 9 |
+
#include <ATen/native/GridSamplerUtils.h>
|
| 10 |
+
|
| 11 |
+
namespace at::native {
|
| 12 |
+
|
| 13 |
+
using detail::GridSamplerInterpolation;
|
| 14 |
+
using detail::GridSamplerPadding;
|
| 15 |
+
|
| 16 |
+
// Unnormalizes a coordinate from the -1 to +1 scale to its pixel index value,
|
| 17 |
+
// where we view each pixel as an area between (idx - 0.5) and (idx + 0.5).
|
| 18 |
+
// if align_corners: -1 and +1 get sent to the centers of the corner pixels
|
| 19 |
+
// -1 --> 0
|
| 20 |
+
// +1 --> (size - 1)
|
| 21 |
+
// scale_factor = (size - 1) / 2
|
| 22 |
+
// if not align_corners: -1 and +1 get sent to the image edges
|
| 23 |
+
// -1 --> -0.5
|
| 24 |
+
// +1 --> (size - 1) + 0.5 == size - 0.5
|
| 25 |
+
// scale_factor = size / 2
|
| 26 |
+
template <typename scalar_t>
|
| 27 |
+
static inline scalar_t grid_sampler_unnormalize(scalar_t coord, int64_t size,
|
| 28 |
+
bool align_corners) {
|
| 29 |
+
if (align_corners) {
|
| 30 |
+
// unnormalize coord from [-1, 1] to [0, size - 1]
|
| 31 |
+
return ((coord + 1) / 2) * (size - 1);
|
| 32 |
+
} else {
|
| 33 |
+
// unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
|
| 34 |
+
return ((coord + 1) * size - 1) / 2;
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
// grid_sampler_unnormalize_set_grad works the same as grid_sampler_unnormalize
|
| 39 |
+
// except that it also returns the `d output / d input` via pointer argument
|
| 40 |
+
// `grad_in`.
|
| 41 |
+
// This is useful in the backward pass of grid_sampler.
|
| 42 |
+
template <typename scalar_t>
|
| 43 |
+
static inline scalar_t grid_sampler_unnormalize_set_grad(scalar_t coord, int64_t size,
|
| 44 |
+
bool align_corners, scalar_t *grad_in) {
|
| 45 |
+
if (align_corners) {
|
| 46 |
+
// unnormalize coord from [-1, 1] to [0, size - 1]
|
| 47 |
+
*grad_in = static_cast<scalar_t>(size - 1) / 2;
|
| 48 |
+
return ((coord + 1) / 2) * (size - 1);
|
| 49 |
+
} else {
|
| 50 |
+
// unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
|
| 51 |
+
*grad_in = static_cast<scalar_t>(size) / 2;
|
| 52 |
+
return ((coord + 1) * size - 1) / 2;
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// Clips coordinates to between 0 and clip_limit - 1
|
| 57 |
+
template<typename scalar_t>
|
| 58 |
+
static inline scalar_t clip_coordinates(scalar_t in, int64_t clip_limit) {
|
| 59 |
+
return std::min(static_cast<scalar_t>(clip_limit - 1), std::max(in, static_cast<scalar_t>(0)));
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// clip_coordinates_set_grad works similarly to clip_coordinates except that
|
| 63 |
+
// it also returns the `d output / d input` via pointer argument `grad_in`.
|
| 64 |
+
// This is useful in the backward pass of grid_sampler.
|
| 65 |
+
template<typename scalar_t>
|
| 66 |
+
static inline scalar_t clip_coordinates_set_grad(scalar_t in, int64_t clip_limit,
|
| 67 |
+
scalar_t *grad_in) {
|
| 68 |
+
// Note that it is important for the gradient calculation that borders
|
| 69 |
+
// are considered out of bounds.
|
| 70 |
+
if (in <= static_cast<scalar_t>(0)) {
|
| 71 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 72 |
+
return static_cast<scalar_t>(0);
|
| 73 |
+
} else {
|
| 74 |
+
scalar_t max = static_cast<scalar_t>(clip_limit - 1);
|
| 75 |
+
if (in >= max) {
|
| 76 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 77 |
+
return max;
|
| 78 |
+
} else {
|
| 79 |
+
*grad_in = static_cast<scalar_t>(1);
|
| 80 |
+
return in;
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
// Reflects coordinates until they fall between low and high (inclusive).
|
| 86 |
+
// The bounds are passed as twice their value so that half-integer values
|
| 87 |
+
// can be represented as ints.
|
| 88 |
+
template<typename scalar_t>
|
| 89 |
+
static inline scalar_t reflect_coordinates(scalar_t in, int64_t twice_low,
|
| 90 |
+
int64_t twice_high) {
|
| 91 |
+
if (twice_low == twice_high) {
|
| 92 |
+
return static_cast<scalar_t>(0);
|
| 93 |
+
}
|
| 94 |
+
scalar_t min = static_cast<scalar_t>(twice_low) / 2;
|
| 95 |
+
scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
|
| 96 |
+
in = std::fabs(in - min);
|
| 97 |
+
// `fmod` returns same sign as `in`, which is positive after the `fabs` above.
|
| 98 |
+
scalar_t extra = std::fmod(in, span);
|
| 99 |
+
int flips = static_cast<int>(std::floor(in / span));
|
| 100 |
+
if (flips % 2 == 0) {
|
| 101 |
+
return extra + min;
|
| 102 |
+
} else {
|
| 103 |
+
return span - extra + min;
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// reflect_coordinates_set_grad works similarly to reflect_coordinates except
|
| 108 |
+
// that it also returns the `d output / d input` via pointer argument
|
| 109 |
+
// `grad_in`.
|
| 110 |
+
// This is useful in the backward pass of grid_sampler.
|
| 111 |
+
template<typename scalar_t>
|
| 112 |
+
static inline scalar_t reflect_coordinates_set_grad(scalar_t in, int64_t twice_low,
|
| 113 |
+
int64_t twice_high, scalar_t *grad_in) {
|
| 114 |
+
if (twice_low == twice_high) {
|
| 115 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 116 |
+
return static_cast<scalar_t>(0);
|
| 117 |
+
}
|
| 118 |
+
int grad_in_mult_;
|
| 119 |
+
scalar_t min = static_cast<scalar_t>(twice_low) / 2;
|
| 120 |
+
scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
|
| 121 |
+
in = in - min;
|
| 122 |
+
if (in < static_cast<scalar_t>(0)) {
|
| 123 |
+
grad_in_mult_ = -1;
|
| 124 |
+
in = -in;
|
| 125 |
+
} else {
|
| 126 |
+
grad_in_mult_ = 1;
|
| 127 |
+
}
|
| 128 |
+
// `fmod` returns same sign as `in`, which is positive after the `if` above.
|
| 129 |
+
scalar_t extra = std::fmod(in, span);
|
| 130 |
+
int flips = static_cast<int>(std::floor(in / span));
|
| 131 |
+
if (flips % 2 == 0) {
|
| 132 |
+
*grad_in = static_cast<scalar_t>(grad_in_mult_);
|
| 133 |
+
return extra + min;
|
| 134 |
+
} else {
|
| 135 |
+
*grad_in = static_cast<scalar_t>(-grad_in_mult_);
|
| 136 |
+
return span - extra + min;
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
// Mapping the out-of-boundary points back into boundary
|
| 141 |
+
// This would only affect padding_mode=border or reflection
|
| 142 |
+
template<typename scalar_t>
|
| 143 |
+
static inline scalar_t compute_coordinates(scalar_t coord, int64_t size,
|
| 144 |
+
GridSamplerPadding padding_mode,
|
| 145 |
+
bool align_corners) {
|
| 146 |
+
if (padding_mode == GridSamplerPadding::Border) {
|
| 147 |
+
// clip coordinates to image borders
|
| 148 |
+
coord = clip_coordinates(coord, size);
|
| 149 |
+
} else if (padding_mode == GridSamplerPadding::Reflection) {
|
| 150 |
+
// reflect coordinates by image borders
|
| 151 |
+
if (align_corners) {
|
| 152 |
+
coord = reflect_coordinates(coord, 0, 2*(size - 1));
|
| 153 |
+
} else {
|
| 154 |
+
coord = reflect_coordinates(coord, -1, 2*size - 1);
|
| 155 |
+
}
|
| 156 |
+
// clip coordinates to image borders
|
| 157 |
+
coord = clip_coordinates(coord, size);
|
| 158 |
+
}
|
| 159 |
+
return coord;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
// Computes the pixel source index value for a grid coordinate
|
| 163 |
+
template <typename scalar_t>
|
| 164 |
+
static inline scalar_t grid_sampler_compute_source_index(
|
| 165 |
+
scalar_t coord,
|
| 166 |
+
int64_t size,
|
| 167 |
+
GridSamplerPadding padding_mode,
|
| 168 |
+
bool align_corners) {
|
| 169 |
+
coord = grid_sampler_unnormalize(coord, size, align_corners);
|
| 170 |
+
coord = compute_coordinates(coord, size, padding_mode, align_corners);
|
| 171 |
+
return coord;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
// grid_sampler_compute_source_index_set_grad works similarly to
|
| 175 |
+
// grid_sampler_compute_source_index except that it also returns the
|
| 176 |
+
// `d output / d input` via pointer argument `grad_in`.
|
| 177 |
+
// This is useful in the backward pass of grid_sampler.
|
| 178 |
+
template <typename scalar_t>
|
| 179 |
+
static inline scalar_t grid_sampler_compute_source_index_set_grad(
|
| 180 |
+
scalar_t coord,
|
| 181 |
+
int64_t size,
|
| 182 |
+
GridSamplerPadding padding_mode,
|
| 183 |
+
bool align_corners,
|
| 184 |
+
scalar_t *grad_in) {
|
| 185 |
+
scalar_t grad_clip, grad_refl;
|
| 186 |
+
coord = grid_sampler_unnormalize_set_grad(coord, size, align_corners, grad_in);
|
| 187 |
+
if (padding_mode == GridSamplerPadding::Border) {
|
| 188 |
+
// clip coordinates to image borders
|
| 189 |
+
coord = clip_coordinates_set_grad(coord, size, &grad_clip);
|
| 190 |
+
*grad_in = (*grad_in) * grad_clip;
|
| 191 |
+
} else if (padding_mode == GridSamplerPadding::Reflection) {
|
| 192 |
+
// reflect coordinates by image borders
|
| 193 |
+
if (align_corners) {
|
| 194 |
+
coord = reflect_coordinates_set_grad(coord, 0, 2*(size - 1), &grad_refl);
|
| 195 |
+
} else {
|
| 196 |
+
coord = reflect_coordinates_set_grad(coord, -1, 2*size - 1, &grad_refl);
|
| 197 |
+
}
|
| 198 |
+
// clip coordinates to image borders
|
| 199 |
+
coord = clip_coordinates_set_grad(coord, size, &grad_clip);
|
| 200 |
+
*grad_in = (*grad_in) * grad_refl * grad_clip;
|
| 201 |
+
}
|
| 202 |
+
return coord;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) {
|
| 206 |
+
return h >= 0 && h < H && w >= 0 && w < W;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) {
|
| 210 |
+
return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
template<typename scalar_t>
|
| 214 |
+
static inline scalar_t get_value_bounded(
|
| 215 |
+
const scalar_t* data,
|
| 216 |
+
scalar_t x,
|
| 217 |
+
scalar_t y,
|
| 218 |
+
int64_t W,
|
| 219 |
+
int64_t H,
|
| 220 |
+
int64_t sW,
|
| 221 |
+
int64_t sH,
|
| 222 |
+
GridSamplerPadding padding_mode,
|
| 223 |
+
bool align_corners) {
|
| 224 |
+
|
| 225 |
+
x = compute_coordinates(x, W, padding_mode, align_corners);
|
| 226 |
+
y = compute_coordinates(y, H, padding_mode, align_corners);
|
| 227 |
+
|
| 228 |
+
int64_t ix = static_cast<int64_t>(x);
|
| 229 |
+
int64_t iy = static_cast<int64_t>(y);
|
| 230 |
+
|
| 231 |
+
if (within_bounds_2d(iy, ix, H, W)) {
|
| 232 |
+
return data[iy * sH + ix * sW];
|
| 233 |
+
}
|
| 234 |
+
return static_cast<scalar_t>(0);
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
template<typename scalar_t>
|
| 238 |
+
static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w,
|
| 239 |
+
int64_t sH, int64_t sW, int64_t H, int64_t W,
|
| 240 |
+
scalar_t delta) {
|
| 241 |
+
if (within_bounds_2d(h, w, H, W)) {
|
| 242 |
+
data[h * sH + w * sW] += delta;
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
template<typename scalar_t>
|
| 247 |
+
static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w,
|
| 248 |
+
int64_t sD, int64_t sH, int64_t sW,
|
| 249 |
+
int64_t D, int64_t H, int64_t W,
|
| 250 |
+
scalar_t delta) {
|
| 251 |
+
if (within_bounds_3d(d, h, w, D, H, W)) {
|
| 252 |
+
data[d * sD + h * sH + w * sW] += delta;
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
template<typename scalar_t>
|
| 257 |
+
static inline void add_value_bounded(
|
| 258 |
+
scalar_t* data,
|
| 259 |
+
scalar_t x,
|
| 260 |
+
scalar_t y,
|
| 261 |
+
int64_t W,
|
| 262 |
+
int64_t H,
|
| 263 |
+
int64_t sW,
|
| 264 |
+
int64_t sH,
|
| 265 |
+
scalar_t delta,
|
| 266 |
+
GridSamplerPadding padding_mode,
|
| 267 |
+
bool align_corners) {
|
| 268 |
+
|
| 269 |
+
x = compute_coordinates(x, W, padding_mode, align_corners);
|
| 270 |
+
y = compute_coordinates(y, H, padding_mode, align_corners);
|
| 271 |
+
|
| 272 |
+
int64_t ix = static_cast<int64_t>(x);
|
| 273 |
+
int64_t iy = static_cast<int64_t>(y);
|
| 274 |
+
|
| 275 |
+
safe_add_2d(data, iy, ix, sH, sW, H, W, delta);
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
// Calculate the differential of the cubic convolution, i.e. `d coeff / d x`
|
| 279 |
+
template<typename scalar_t>
|
| 280 |
+
static inline void get_cubic_coefficients_grad(
|
| 281 |
+
scalar_t coeffs[4],
|
| 282 |
+
scalar_t t) {
|
| 283 |
+
|
| 284 |
+
// Must be the same as forward calculation in
|
| 285 |
+
// aten/src/ATen/native/UpSample.h:get_cubic_upsample_coefficients
|
| 286 |
+
scalar_t A = -0.75;
|
| 287 |
+
|
| 288 |
+
scalar_t x;
|
| 289 |
+
x = -1 - t; // 1 < x = |-1 - tx| < 2
|
| 290 |
+
coeffs[0] = (-3 * A * x - 10 * A ) * x - 8 * A;
|
| 291 |
+
x = -t; // x = |0 - tx| <= 1
|
| 292 |
+
coeffs[1] = (-3 * (A + 2) * x - 2 * (A + 3)) * x;
|
| 293 |
+
x = 1 - t; // x = |1 - tx| <= 1
|
| 294 |
+
coeffs[2] = (3 * (A + 2) * x - 2 * (A + 3)) * x;
|
| 295 |
+
x = 2 - t; // 1 < x = |2 - tx| < 2
|
| 296 |
+
coeffs[3] = (3 * A * x - 10 * A) * x + 8 * A;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
} // namespace at::native
|
| 300 |
+
|
| 301 |
+
#else
|
| 302 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 303 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
// See NOTE: [Tensor vs. TensorBase]
|
| 5 |
+
// https://github.com/pytorch/pytorch/pull/66979
|
| 6 |
+
#include <ATen/core/TensorBase.h>
|
| 7 |
+
#include <ATen/native/TensorProperties.h>
|
| 8 |
+
#include <ATen/native/CanUse32BitIndexMath.h>
|
| 9 |
+
|
| 10 |
+
namespace at::native {
|
| 11 |
+
|
| 12 |
+
namespace detail {
|
| 13 |
+
|
| 14 |
+
enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic};
|
| 15 |
+
enum class GridSamplerPadding {Zeros, Border, Reflection};
|
| 16 |
+
|
| 17 |
+
} // namespace detail
|
| 18 |
+
|
| 19 |
+
using detail::GridSamplerInterpolation;
|
| 20 |
+
using detail::GridSamplerPadding;
|
| 21 |
+
|
| 22 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 23 |
+
inline void check_grid_sampler_common(
|
| 24 |
+
const TensorBase& input,
|
| 25 |
+
const TensorBase& grid
|
| 26 |
+
) {
|
| 27 |
+
auto input_opt = input.options();
|
| 28 |
+
auto grid_opt = grid.options();
|
| 29 |
+
|
| 30 |
+
TORCH_CHECK(
|
| 31 |
+
input.defined(),
|
| 32 |
+
"grid_sampler(): expected input to not be undefined");
|
| 33 |
+
TORCH_CHECK(
|
| 34 |
+
grid.defined(),
|
| 35 |
+
"grid_sampler(): expected grid to not be undefined");
|
| 36 |
+
TORCH_CHECK(
|
| 37 |
+
input_opt.device() == grid_opt.device(),
|
| 38 |
+
"grid_sampler(): expected input and grid to be on same device, but input "
|
| 39 |
+
"is on ", input_opt.device(), " and grid is on ", grid_opt.device());
|
| 40 |
+
TORCH_CHECK(
|
| 41 |
+
input_opt.layout() == kStrided && grid_opt.layout() == kStrided,
|
| 42 |
+
"grid_sampler(): expected input and grid to have torch.strided layout, but "
|
| 43 |
+
"input has ", input_opt.layout(), " and grid has ", grid_opt.layout());
|
| 44 |
+
TORCH_CHECK(
|
| 45 |
+
input.size(0) == grid.size(0),
|
| 46 |
+
"grid_sampler(): expected grid and input to have same batch size, but got "
|
| 47 |
+
"input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes());
|
| 48 |
+
TORCH_CHECK(
|
| 49 |
+
grid.size(-1) == input.dim() - 2,
|
| 50 |
+
"grid_sampler(): expected grid to have size ", input.dim() - 2, " in last "
|
| 51 |
+
"dimension, but got grid with sizes ", grid.sizes());
|
| 52 |
+
|
| 53 |
+
for (const auto i : c10::irange(2, input.dim())) {
|
| 54 |
+
TORCH_CHECK(input.size(i) > 0,
|
| 55 |
+
"grid_sampler(): expected input to have non-empty spatial dimensions, "
|
| 56 |
+
"but input has sizes ", input.sizes(), " with dimension ", i, " being "
|
| 57 |
+
"empty");
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 62 |
+
inline void check_grid_sampler_2d(
|
| 63 |
+
const TensorBase& input,
|
| 64 |
+
const TensorBase& grid
|
| 65 |
+
) {
|
| 66 |
+
TORCH_CHECK(
|
| 67 |
+
input.dim() == 4 && input.dim() == grid.dim(),
|
| 68 |
+
"grid_sampler(): expected 4D input and grid with same number of "
|
| 69 |
+
"dimensions, but got input with sizes ", input.sizes(),
|
| 70 |
+
" and grid with sizes ", grid.sizes());
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 74 |
+
inline void check_grid_sampler_3d(
|
| 75 |
+
const TensorBase& input,
|
| 76 |
+
const TensorBase& grid,
|
| 77 |
+
int64_t interpolation_mode
|
| 78 |
+
) {
|
| 79 |
+
TORCH_CHECK(
|
| 80 |
+
input.dim() == 5 && input.dim() == grid.dim(),
|
| 81 |
+
"grid_sampler(): expected 5D input and grid with same number of "
|
| 82 |
+
"dimensions, but got input with sizes ", input.sizes(),
|
| 83 |
+
" and grid with sizes ", grid.sizes());
|
| 84 |
+
TORCH_CHECK(
|
| 85 |
+
!(input.dim() == 5 &&
|
| 86 |
+
static_cast<GridSamplerInterpolation>(interpolation_mode) ==
|
| 87 |
+
GridSamplerInterpolation::Bicubic),
|
| 88 |
+
"grid_sampler(): bicubic interpolation only supports 4D input");
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 92 |
+
// cudnn does not support inputs larger than 1024.
|
| 93 |
+
inline bool cond_cudnn_grid_sampler(
|
| 94 |
+
const TensorBase& input,
|
| 95 |
+
const TensorBase& grid
|
| 96 |
+
) {
|
| 97 |
+
auto st = input.scalar_type();
|
| 98 |
+
if (!(st == kDouble || st == kFloat || st == kHalf))
|
| 99 |
+
return false;
|
| 100 |
+
st = grid.scalar_type();
|
| 101 |
+
if (!(st == kDouble || st == kFloat || st == kHalf))
|
| 102 |
+
return false;
|
| 103 |
+
return (
|
| 104 |
+
at::native::cudnn_is_acceptable(input) &&
|
| 105 |
+
at::native::cudnn_is_acceptable(grid) &&
|
| 106 |
+
at::native::canUse32BitIndexMath(input) &&
|
| 107 |
+
at::native::canUse32BitIndexMath(grid) &&
|
| 108 |
+
input.dim() == 4 &&
|
| 109 |
+
input.sym_size(1) <= 1024);
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
} // namespace at::native
|
| 113 |
+
|
| 114 |
+
#else
|
| 115 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 116 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/GroupedMMUtils.h
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <ATen/TensorUtils.h>
|
| 6 |
+
|
| 7 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 8 |
+
#include <ATen/CPUFunctions.h>
|
| 9 |
+
#include <ATen/Functions.h>
|
| 10 |
+
#include <ATen/NativeFunctions.h>
|
| 11 |
+
#else
|
| 12 |
+
#include <ATen/ops/bmm.h>
|
| 13 |
+
#include <ATen/ops/empty.h>
|
| 14 |
+
#include <ATen/ops/empty_strided.h>
|
| 15 |
+
#include <ATen/ops/mm.h>
|
| 16 |
+
#endif
|
| 17 |
+
|
| 18 |
+
namespace at::native {
|
| 19 |
+
|
| 20 |
+
inline bool check_valid_strides_and_return_transposed(const Tensor& mat) {
|
| 21 |
+
IntArrayRef tensor_strides = mat.strides();
|
| 22 |
+
IntArrayRef tensor_sizes = mat.sizes();
|
| 23 |
+
int end_dim = mat.dim() - 1;
|
| 24 |
+
int alignment = 16 / mat.element_size();
|
| 25 |
+
TORCH_CHECK(uint64_t(mat.data_ptr()) % 16 ==0, "expected data_ptr to be aligned to 16 bytes\n");
|
| 26 |
+
if ((tensor_strides[end_dim - 1] == 1) && (tensor_strides[end_dim] >= std::max<int64_t>(1, tensor_sizes[end_dim - 1]))) {
|
| 27 |
+
TORCH_CHECK(tensor_strides[end_dim] % alignment == 0, "strides should be multiple of 16 bytes");
|
| 28 |
+
return true;
|
| 29 |
+
} else if ((tensor_strides[end_dim] == 1) && (tensor_strides[end_dim - 1] >= std::max<int64_t>(1, tensor_sizes[end_dim]))) {
|
| 30 |
+
TORCH_CHECK(tensor_strides[end_dim - 1] % alignment == 0, "strides should be multiple of 16 bytes");
|
| 31 |
+
return false;
|
| 32 |
+
} else {
|
| 33 |
+
TORCH_CHECK(false, "Invalid strides/sizes, got ", mat.strides(), " for strides and ", mat.sizes(), " for sizes");
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
inline at::Tensor create_grouped_gemm_output_tensor(const Tensor& mat_a,
|
| 38 |
+
const Tensor& mat_b,
|
| 39 |
+
const std::optional<at::Tensor>& offs,
|
| 40 |
+
c10::ScalarType out_dtype
|
| 41 |
+
) {
|
| 42 |
+
c10::SmallVector<int64_t, 3> out_size;
|
| 43 |
+
const bool a_is_2d = mat_a.dim() == 2;
|
| 44 |
+
const bool b_is_2d = mat_b.dim() == 2;
|
| 45 |
+
if (a_is_2d) {
|
| 46 |
+
if (b_is_2d) {
|
| 47 |
+
out_size = {offs->size(0), mat_a.size(0), mat_b.size(1)};
|
| 48 |
+
} else {
|
| 49 |
+
TORCH_CHECK(offs->size(0) == mat_b.size(0), "matrix batch sizes have to match");
|
| 50 |
+
out_size = {mat_a.size(0), mat_b.size(-1)};
|
| 51 |
+
}
|
| 52 |
+
} else {
|
| 53 |
+
if (b_is_2d) {
|
| 54 |
+
// this case is not actually encountered for MoE gemms
|
| 55 |
+
TORCH_CHECK(offs->size(0) == mat_a.size(0), "matrix batch sizes have to match");
|
| 56 |
+
out_size = {mat_a.size(1), mat_b.size(1)};
|
| 57 |
+
} else { // regular bmm
|
| 58 |
+
TORCH_CHECK(mat_a.size(0) == mat_b.size(0), "batched dimension has to match");
|
| 59 |
+
out_size = {mat_a.size(0), mat_a.size(1), mat_b.size(-1)};
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
#ifndef USE_ROCM
|
| 64 |
+
// For TMA transfers, strides of output tensor have to be either
|
| 65 |
+
// 1, or aligned to 16 bytes.
|
| 66 |
+
const auto last_dim = out_size.size() - 1;
|
| 67 |
+
const auto alignment = 16 / c10::elementSize(out_dtype);
|
| 68 |
+
const int64_t size_padded = (out_size[last_dim] + alignment - 1) / alignment * alignment;
|
| 69 |
+
std::vector<int64_t> out_stride;
|
| 70 |
+
if (a_is_2d != b_is_2d) {
|
| 71 |
+
out_stride = {size_padded, 1};
|
| 72 |
+
} else {
|
| 73 |
+
out_stride = {out_size[1] * size_padded, size_padded, 1};
|
| 74 |
+
}
|
| 75 |
+
return at::empty_strided(out_size, out_stride, mat_a.options().dtype(out_dtype));
|
| 76 |
+
#else
|
| 77 |
+
return at::empty(out_size, mat_a.options().dtype(out_dtype));
|
| 78 |
+
#endif
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
inline void _grouped_mm_validate_inputs(const Tensor& mat_a, const Tensor& mat_b,
|
| 82 |
+
const std::optional<at::Tensor>& offs,
|
| 83 |
+
const std::optional<at::Tensor>& bias,
|
| 84 |
+
std::optional<c10::ScalarType> out_dtype) {
|
| 85 |
+
TORCH_CHECK((mat_a.dtype() == at::kBFloat16) || (mat_a.dtype() == at::kFloat) || (mat_a.dtype() == at::kHalf), "Expected mat_a to be Float32, BFloat16 or Float16 matrix, got ", mat_a.scalar_type());
|
| 86 |
+
TORCH_CHECK((mat_b.dtype() == at::kBFloat16) || (mat_b.dtype() == at::kFloat) || (mat_b.dtype() == at::kHalf), "Expected mat_b to be Float32, BFloat16 or Float16 matrix, got ", mat_b.scalar_type());
|
| 87 |
+
TORCH_CHECK(mat_a.dim() == 2 || mat_a.dim() == 3, "mat_a has to be 2 or 3d");
|
| 88 |
+
TORCH_CHECK(mat_b.dim() == 2 || mat_b.dim() == 3, "mat_b has to be 2 or 3d");
|
| 89 |
+
const bool a_is_2d = mat_a.dim() == 2;
|
| 90 |
+
const bool b_is_2d = mat_b.dim() == 2;
|
| 91 |
+
if (!a_is_2d || !b_is_2d) {
|
| 92 |
+
TORCH_CHECK(mat_a.size(-1) == mat_b.size(-2), "contraction dimension of mat_a and mat_b must match");
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// check that the strides are valid, the fn will throw an error if not
|
| 96 |
+
check_valid_strides_and_return_transposed(mat_a);
|
| 97 |
+
check_valid_strides_and_return_transposed(mat_b);
|
| 98 |
+
TORCH_CHECK(offs.has_value() == (a_is_2d || b_is_2d), "Have to provide offsets if there is a 2d matrix, or no offset if both matrices are 3d");
|
| 99 |
+
|
| 100 |
+
if (offs.has_value()) {
|
| 101 |
+
TORCH_CHECK(offs->dim() == 1, "offs has to be 1D");
|
| 102 |
+
TORCH_CHECK(offs->dtype() == at::kInt, "Offsets have to be int32");
|
| 103 |
+
}
|
| 104 |
+
TORCH_CHECK(!bias.has_value(), "Bias not supported yet");
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
inline c10::ScalarType _resolve_grouped_mm_out_dtype(const Tensor& mat_a, const Tensor& mat_b,
|
| 108 |
+
std::optional<c10::ScalarType> out_dtype) {
|
| 109 |
+
const auto out_dtype_ = out_dtype.value_or(mat_a.scalar_type());
|
| 110 |
+
// TODO(future PR): enable float32 output dtype for bfloat16 and float16 inputs
|
| 111 |
+
TORCH_CHECK(out_dtype_ == mat_a.dtype(), "Grouped gemm output dtype must match `mat_a` dtype");
|
| 112 |
+
return out_dtype_;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
inline void _grouped_mm_fallback(const Tensor& mat_a, const Tensor& mat_b,
|
| 117 |
+
const std::optional<at::Tensor>& offs,
|
| 118 |
+
const std::optional<at::Tensor>& bias,
|
| 119 |
+
std::optional<c10::ScalarType> out_dtype,
|
| 120 |
+
Tensor out) {
|
| 121 |
+
LOG(INFO) << "fallback path for `torch._grouped_mm`, performance may not be optimal";
|
| 122 |
+
const bool a_is_2d = mat_a.dim() == 2;
|
| 123 |
+
const bool b_is_2d = mat_b.dim() == 2;
|
| 124 |
+
if (a_is_2d && !b_is_2d) {
|
| 125 |
+
// 2d x 3d with offsets
|
| 126 |
+
int group_start_idx = 0;
|
| 127 |
+
auto offs_cpu = offs.value().cpu();
|
| 128 |
+
for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) {
|
| 129 |
+
int group_end_idx = offs_cpu[group_idx].item<int>();
|
| 130 |
+
auto mat_a_slice = mat_a.slice(0, group_start_idx, group_end_idx);
|
| 131 |
+
auto out_slice = out.slice(0, group_start_idx, group_end_idx);
|
| 132 |
+
at::mm_out(out_slice, mat_a_slice, mat_b[group_idx]);
|
| 133 |
+
group_start_idx = group_end_idx;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
} else if (!a_is_2d && b_is_2d) {
|
| 137 |
+
// 3d x 2d with offsets
|
| 138 |
+
int group_start_idx = 0;
|
| 139 |
+
auto offs_cpu = offs.value().cpu();
|
| 140 |
+
for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) {
|
| 141 |
+
int group_end_idx = offs_cpu[group_idx].item<int>();
|
| 142 |
+
auto mat_b_slice = mat_b.slice(1, group_start_idx, group_end_idx);
|
| 143 |
+
auto out_slice = out.slice(1, group_start_idx, group_end_idx);
|
| 144 |
+
at::mm_out(out_slice, mat_a[group_idx], mat_b_slice);
|
| 145 |
+
group_start_idx = group_end_idx;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
} else if (a_is_2d && b_is_2d) {
|
| 149 |
+
// 2d x 2d with offsets
|
| 150 |
+
int group_start_idx = 0;
|
| 151 |
+
auto offs_cpu = offs.value().cpu();
|
| 152 |
+
for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) {
|
| 153 |
+
int group_end_idx = offs_cpu[group_idx].item<int>();
|
| 154 |
+
auto mat_a_slice = mat_a.slice(1, group_start_idx, group_end_idx);
|
| 155 |
+
auto mat_b_slice = mat_b.slice(0, group_start_idx, group_end_idx);
|
| 156 |
+
auto out_slice = out[group_idx];
|
| 157 |
+
at::mm_out(out_slice, mat_a_slice, mat_b_slice);
|
| 158 |
+
group_start_idx = group_end_idx;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
} else {
|
| 162 |
+
// 3d x 3d without offsets - regular bmm
|
| 163 |
+
at::bmm_out(out, mat_a, mat_b);
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
} // namespace at::native
|
| 169 |
+
|
| 170 |
+
#else
|
| 171 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 172 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Histogram.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/core/Tensor.h>
|
| 5 |
+
#include <ATen/native/DispatchStub.h>
|
| 6 |
+
|
| 7 |
+
namespace at::native {
|
| 8 |
+
|
| 9 |
+
using histogramdd_fn = void(*)(const Tensor&, const std::optional<Tensor>&, bool, Tensor&, const TensorList&);
|
| 10 |
+
using histogramdd_linear_fn = void(*)(const Tensor&, const std::optional<Tensor>&, bool, Tensor&, const TensorList&, bool);
|
| 11 |
+
using histogram_select_outer_bin_edges_fn = void(*)(const Tensor& input, const int64_t N, std::vector<double> &leftmost_edges, std::vector<double> &rightmost_edges);
|
| 12 |
+
|
| 13 |
+
DECLARE_DISPATCH(histogramdd_fn, histogramdd_stub)
|
| 14 |
+
DECLARE_DISPATCH(histogramdd_linear_fn, histogramdd_linear_stub)
|
| 15 |
+
DECLARE_DISPATCH(histogram_select_outer_bin_edges_fn, histogram_select_outer_bin_edges_stub)
|
| 16 |
+
|
| 17 |
+
} // namespace at::native
|
| 18 |
+
|
| 19 |
+
#else
|
| 20 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 21 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/IndexKernel.h
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
#include <c10/util/ArrayRef.h>
|
| 5 |
+
|
| 6 |
+
namespace at {
|
| 7 |
+
class Tensor;
|
| 8 |
+
class TensorBase;
|
| 9 |
+
struct TensorIterator;
|
| 10 |
+
struct TensorIteratorBase;
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
namespace c10 {
|
| 14 |
+
class Scalar;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
namespace at::native {
|
| 18 |
+
|
| 19 |
+
using index_fn = void(*)(TensorIteratorBase &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides);
|
| 20 |
+
using index_fill_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride, const Scalar& source);
|
| 21 |
+
using index_copy_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride);
|
| 22 |
+
using index_put_fn = void(*)(TensorIterator &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides, bool accumulate);
|
| 23 |
+
using put_fn = void(*)(TensorIterator & iter, const TensorBase& self, const bool accumulate);
|
| 24 |
+
using take_fn = void(*)(TensorIterator & iter, const TensorBase& input);
|
| 25 |
+
using flip_fn = void(*)(TensorIterator &, const bool);
|
| 26 |
+
using masked_fill_fn = void(*)(TensorIterator &, const Scalar& scalar);
|
| 27 |
+
using masked_select_fn = void(*)(TensorIterator &, int64_t orig_stride);
|
| 28 |
+
using masked_scatter_fn = void(*)(TensorIterator &, const TensorBase &);
|
| 29 |
+
|
| 30 |
+
DECLARE_DISPATCH(index_fn, index_stub)
|
| 31 |
+
DECLARE_DISPATCH(index_fill_fn, index_fill_stub)
|
| 32 |
+
DECLARE_DISPATCH(index_copy_fn, index_copy_stub)
|
| 33 |
+
DECLARE_DISPATCH(index_put_fn, index_put_stub)
|
| 34 |
+
DECLARE_DISPATCH(put_fn, put_stub)
|
| 35 |
+
DECLARE_DISPATCH(take_fn, take_stub)
|
| 36 |
+
DECLARE_DISPATCH(flip_fn, flip_stub)
|
| 37 |
+
DECLARE_DISPATCH(masked_fill_fn, masked_fill_stub)
|
| 38 |
+
DECLARE_DISPATCH(masked_select_fn, masked_select_serial_stub)
|
| 39 |
+
DECLARE_DISPATCH(masked_select_fn, masked_select_stub)
|
| 40 |
+
DECLARE_DISPATCH(masked_scatter_fn, masked_scatter_stub)
|
| 41 |
+
|
| 42 |
+
} // namespace at::native
|
| 43 |
+
|
| 44 |
+
#else
|
| 45 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 46 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/IndexingUtils.h
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/ExpandUtils.h>
|
| 4 |
+
#include <ATen/native/CanUse32BitIndexMath.h>
|
| 5 |
+
#include <ATen/native/TensorIterator.h>
|
| 6 |
+
#include <ATen/core/IListRef.h>
|
| 7 |
+
#include <c10/util/irange.h>
|
| 8 |
+
|
| 9 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 10 |
+
#include <ATen/Functions.h>
|
| 11 |
+
#else
|
| 12 |
+
#include <ATen/ops/empty.h>
|
| 13 |
+
#include <ATen/ops/nonzero.h>
|
| 14 |
+
#endif
|
| 15 |
+
|
| 16 |
+
namespace at::native {
|
| 17 |
+
|
| 18 |
+
[[noreturn]]
|
| 19 |
+
static void invalid_mask(const Tensor & self, int64_t idx, const Tensor & mask, int64_t maskIdx) {
|
| 20 |
+
TORCH_CHECK_INDEX(false, "The shape of the mask ", mask.sizes(), " at index ", maskIdx,
|
| 21 |
+
" does not match the shape of the indexed tensor ", self.sizes(), " at index ", idx);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
[[maybe_unused]] static std::vector<Tensor> expandTensors(
|
| 25 |
+
const Tensor& self,
|
| 26 |
+
IOptTensorListRef indices,
|
| 27 |
+
bool ensure_same_device = false) {
|
| 28 |
+
// If indices come in as ByteTensor or BoolTensor (masks), expand them into
|
| 29 |
+
// the equivalent indexing by LongTensors
|
| 30 |
+
std::vector<Tensor> result;
|
| 31 |
+
for (const auto& index_opt : indices) {
|
| 32 |
+
if (!index_opt.has_value()) {
|
| 33 |
+
result.emplace_back();
|
| 34 |
+
} else {
|
| 35 |
+
const auto& index = *index_opt;
|
| 36 |
+
if (index.scalar_type() == kByte || index.scalar_type() == kBool) {
|
| 37 |
+
if (index.scalar_type() == kByte) {
|
| 38 |
+
TORCH_WARN("indexing with dtype torch.uint8 is now deprecated," \
|
| 39 |
+
" please use a dtype torch.bool instead.");
|
| 40 |
+
}
|
| 41 |
+
// The sizes of the ByteTensor mask or bool tensor must match the sizes of the
|
| 42 |
+
// corresponding dimensions in self
|
| 43 |
+
for (const auto j : c10::irange(index.dim())) {
|
| 44 |
+
int64_t srcIdx = static_cast<int64_t>(result.size() + j);
|
| 45 |
+
if (index.size(j) != self.size(srcIdx)) {
|
| 46 |
+
invalid_mask(self, srcIdx, index, j);
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
// Replace with nonzeros
|
| 50 |
+
at::Tensor nonzero;
|
| 51 |
+
if (ensure_same_device && index.device() != self.device()) {
|
| 52 |
+
bool non_blocking = index.is_cpu() && self.device().is_cuda();
|
| 53 |
+
auto out = at::empty({0}, index.options().dtype(kLong).pinned_memory(non_blocking));
|
| 54 |
+
nonzero = at::nonzero_out(out, index).to(self.device(), non_blocking);
|
| 55 |
+
} else {
|
| 56 |
+
nonzero = index.nonzero();
|
| 57 |
+
}
|
| 58 |
+
for (const auto j : c10::irange(index.dim())) {
|
| 59 |
+
result.emplace_back(nonzero.select(1, j));
|
| 60 |
+
}
|
| 61 |
+
} else if (ensure_same_device && index.device() != self.device()) {
|
| 62 |
+
result.emplace_back(index.to(self.device()));
|
| 63 |
+
} else {
|
| 64 |
+
result.emplace_back(index);
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
return result;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
[[maybe_unused]] static void checkIndexTensorTypes(
|
| 72 |
+
IOptTensorListRef indices,
|
| 73 |
+
bool allow_int = false) {
|
| 74 |
+
for (const auto& tensor : indices) {
|
| 75 |
+
if (tensor.has_value() && tensor->defined()) {
|
| 76 |
+
auto scalarType = tensor->scalar_type();
|
| 77 |
+
if (allow_int) {
|
| 78 |
+
if (scalarType != kLong && scalarType != kByte && scalarType != kBool && scalarType != kInt) {
|
| 79 |
+
TORCH_CHECK_INDEX(false, "tensors used as indices must be long, int, byte or bool tensors");
|
| 80 |
+
}
|
| 81 |
+
} else {
|
| 82 |
+
if (scalarType != kLong && scalarType != kByte && scalarType != kBool) {
|
| 83 |
+
TORCH_CHECK_INDEX(false, "tensors used as indices must be long, byte or bool tensors");
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
inline torch::List<std::optional<Tensor>> toListOfOptionalTensors(ArrayRef<Tensor> list) {
|
| 91 |
+
torch::List<std::optional<Tensor>> result;
|
| 92 |
+
result.reserve(list.size());
|
| 93 |
+
for (const Tensor& a : list) {
|
| 94 |
+
result.push_back(a);
|
| 95 |
+
}
|
| 96 |
+
return result;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
inline torch::List<std::optional<Tensor>> toListOfOptionalTensors(ArrayRef<IValue> list) {
|
| 100 |
+
torch::List<std::optional<Tensor>> result;
|
| 101 |
+
result.reserve(list.size());
|
| 102 |
+
for (const IValue& a : list) {
|
| 103 |
+
result.push_back(a.isTensor() ? std::optional<Tensor>(a.toTensor()) : std::optional<Tensor>());
|
| 104 |
+
}
|
| 105 |
+
return result;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
[[maybe_unused]] static bool hasContiguousSubspace(TensorList tl) {
|
| 109 |
+
// true if all the non-null tensors are adjacent
|
| 110 |
+
auto isDefined = [](const Tensor & tensor){ return tensor.defined(); };
|
| 111 |
+
auto isNull = [](const Tensor & tensor){ return !tensor.defined(); };
|
| 112 |
+
auto start = std::find_if(tl.begin(), tl.end(), isDefined);
|
| 113 |
+
auto stop = std::find_if(tl.rbegin(), tl.rend(), isDefined);
|
| 114 |
+
auto it = std::find_if(start, stop.base(), isNull);
|
| 115 |
+
return it == stop.base();
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// Transposes the tensor and indices together so that all the non-null indices
|
| 119 |
+
// index the first k dimensions of the tensor. Returns the transposed tensor
|
| 120 |
+
// and the reordered indices. For example:
|
| 121 |
+
// transposeToFront(tensor, {nullptr, a, nullptr, b})
|
| 122 |
+
// returns
|
| 123 |
+
// tensor.permute([1, 3, 0, 2]), {a, b, nullptr, nullptr}
|
| 124 |
+
[[maybe_unused]] static std::tuple<Tensor, std::vector<Tensor>> transposeToFront(
|
| 125 |
+
const Tensor& self,
|
| 126 |
+
TensorList indices) {
|
| 127 |
+
std::vector<int64_t> dims;
|
| 128 |
+
std::vector<Tensor> transposedIndices;
|
| 129 |
+
dims.reserve(self.dim());
|
| 130 |
+
for (const auto i : c10::irange(self.dim())) {
|
| 131 |
+
if (indices[i].defined()) {
|
| 132 |
+
dims.push_back(i);
|
| 133 |
+
transposedIndices.emplace_back(indices[i]);
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
for (const auto i : c10::irange(self.dim())) {
|
| 137 |
+
if (!indices[i].defined()) {
|
| 138 |
+
dims.push_back(i);
|
| 139 |
+
transposedIndices.emplace_back();
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
return std::make_tuple(self.permute(dims), std::move(transposedIndices));
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
inline std::tuple<Tensor, std::vector<Tensor>, std::vector<int64_t>>
|
| 146 |
+
transposeToFrontAndInvPerm(const Tensor& self, TensorList indices) {
|
| 147 |
+
std::vector<int64_t> dims;
|
| 148 |
+
std::vector<int64_t> invPerm;
|
| 149 |
+
std::vector<Tensor> transposedIndices;
|
| 150 |
+
dims.reserve(self.dim());
|
| 151 |
+
invPerm.resize(self.dim());
|
| 152 |
+
for (const auto i : c10::irange(self.dim())) {
|
| 153 |
+
if (indices[i].defined()) {
|
| 154 |
+
dims.push_back(i);
|
| 155 |
+
transposedIndices.emplace_back(indices[i]);
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
for (const auto i : c10::irange(self.dim())) {
|
| 159 |
+
if (!indices[i].defined()) {
|
| 160 |
+
dims.push_back(i);
|
| 161 |
+
transposedIndices.emplace_back();
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
for (const auto i : c10::irange(self.dim())) {
|
| 165 |
+
invPerm[dims[i]] = i;
|
| 166 |
+
}
|
| 167 |
+
return std::make_tuple(self.permute(dims), std::move(transposedIndices), std::move(invPerm));
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
struct AdvancedIndex {
|
| 171 |
+
AdvancedIndex(const Tensor& src, TensorList indices);
|
| 172 |
+
|
| 173 |
+
Tensor src;
|
| 174 |
+
std::vector<Tensor> indices;
|
| 175 |
+
DimVector indexed_sizes;
|
| 176 |
+
DimVector indexed_strides;
|
| 177 |
+
int64_t dims_before;
|
| 178 |
+
int64_t dims_after;
|
| 179 |
+
};
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
} //namespace at::native
|
| 183 |
+
|
| 184 |
+
#else
|
| 185 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 186 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
#include <ATen/OpMathType.h>
|
| 6 |
+
#include <ATen/TensorIterator.h>
|
| 7 |
+
#include <c10/core/Scalar.h>
|
| 8 |
+
|
| 9 |
+
namespace at::native {
|
| 10 |
+
|
| 11 |
+
template <typename scalar_t>
|
| 12 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(scalar_t weight) {
|
| 13 |
+
return std::abs(weight) < scalar_t(0.5);
|
| 14 |
+
}
|
| 15 |
+
template <typename scalar_t>
|
| 16 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(c10::complex<scalar_t> weight) {
|
| 17 |
+
// Avoid the sqrt in abs(weight)
|
| 18 |
+
return (weight.real() * weight.real() + weight.imag() * weight.imag()) < scalar_t(0.25);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
template <typename scalar_t, typename weight_t>
|
| 22 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE scalar_t lerp(scalar_t self_, scalar_t end_, weight_t weight_) {
|
| 23 |
+
using opmath_t = at::opmath_type<scalar_t>;
|
| 24 |
+
using opmath_weight_t = at::opmath_type<weight_t>;
|
| 25 |
+
|
| 26 |
+
opmath_t self = self_;
|
| 27 |
+
opmath_t end = end_;
|
| 28 |
+
opmath_weight_t weight = weight_;
|
| 29 |
+
|
| 30 |
+
// Conditional for better numeric. This has been discussed in
|
| 31 |
+
// https://github.com/pytorch/pytorch/pull/18871
|
| 32 |
+
return is_lerp_weight_small(weight)
|
| 33 |
+
? self + weight * (end - self)
|
| 34 |
+
: end - (end - self) * (opmath_t(1) - weight);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
using lerp_fn_scalar = void (*)(
|
| 38 |
+
at::TensorIteratorBase& iter,
|
| 39 |
+
const Scalar& weight);
|
| 40 |
+
|
| 41 |
+
using lerp_fn_tensor = void (*)(
|
| 42 |
+
at::TensorIteratorBase& iter);
|
| 43 |
+
|
| 44 |
+
DECLARE_DISPATCH(lerp_fn_scalar, lerp_kernel_scalar_weight)
|
| 45 |
+
DECLARE_DISPATCH(lerp_fn_tensor, lerp_kernel_tensor_weight)
|
| 46 |
+
|
| 47 |
+
} // namespace at::native
|
| 48 |
+
|
| 49 |
+
#else
|
| 50 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 51 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebra.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
|
| 6 |
+
namespace c10 {
|
| 7 |
+
class Scalar;
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
namespace at {
|
| 11 |
+
struct TensorIterator;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
namespace at::native {
|
| 15 |
+
|
| 16 |
+
using addr_fn = void (*)(TensorIterator &, const Scalar& beta, const Scalar& alpha);
|
| 17 |
+
DECLARE_DISPATCH(addr_fn, addr_stub)
|
| 18 |
+
} // namespace at::native
|
| 19 |
+
|
| 20 |
+
#else
|
| 21 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 22 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
|
| 4 |
+
#include <c10/core/ScalarType.h>
|
| 5 |
+
#include <c10/util/irange.h>
|
| 6 |
+
#include <c10/util/Exception.h>
|
| 7 |
+
#include <c10/util/strides.h>
|
| 8 |
+
#include <ATen/core/Tensor.h>
|
| 9 |
+
#include <ATen/ExpandUtils.h>
|
| 10 |
+
#include <ATen/TensorUtils.h>
|
| 11 |
+
#include <ATen/native/TensorIterator.h>
|
| 12 |
+
#include <ATen/native/TransposeType.h>
|
| 13 |
+
#include <limits>
|
| 14 |
+
#include <type_traits>
|
| 15 |
+
#include <sstream>
|
| 16 |
+
#include <cstring>
|
| 17 |
+
#include <cctype>
|
| 18 |
+
|
| 19 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 20 |
+
#include <ATen/Functions.h>
|
| 21 |
+
#else
|
| 22 |
+
#include <ATen/ops/arange.h>
|
| 23 |
+
#include <ATen/ops/empty.h>
|
| 24 |
+
#include <ATen/ops/empty_like.h>
|
| 25 |
+
#include <ATen/ops/empty_strided.h>
|
| 26 |
+
#include <ATen/ops/zeros.h>
|
| 27 |
+
#endif
|
| 28 |
+
|
| 29 |
+
namespace at::native {
|
| 30 |
+
|
| 31 |
+
inline c10::MaybeOwned<Tensor> expect_resolved_conj(const Tensor& tensor) {
|
| 32 |
+
if (tensor.is_conj()) {
|
| 33 |
+
return c10::MaybeOwned<Tensor>::owned(tensor.resolve_conj());
|
| 34 |
+
} else {
|
| 35 |
+
return c10::MaybeOwned<Tensor>::borrowed(tensor);
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
inline DimVector batched_matrix_contiguous_strides(
|
| 40 |
+
const IntArrayRef sizes,
|
| 41 |
+
const bool f_contig = false) {
|
| 42 |
+
// f_contig chooses between the strides of a batch of Fortran (F-contiguous)
|
| 43 |
+
// and C-contiguous matrices
|
| 44 |
+
auto strides = c10::contiguous_strides(sizes);
|
| 45 |
+
auto dim = strides.size();
|
| 46 |
+
|
| 47 |
+
if (f_contig && dim >= 2) {
|
| 48 |
+
// Fix the strides of the last two dimensions, so that we return
|
| 49 |
+
// C-contiguous batches of F-contiguous matrices.
|
| 50 |
+
strides[dim - 1] = std::max(sizes[dim - 2], static_cast<int64_t>(1));
|
| 51 |
+
strides[dim - 2] = 1;
|
| 52 |
+
}
|
| 53 |
+
return strides;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/*
|
| 57 |
+
* Clones a Tensor so that the following conditions hold:
|
| 58 |
+
* If we think of a Tensor of having size (B, M, N), where B is any number
|
| 59 |
+
* of batch dimensions, then:
|
| 60 |
+
* - Each (M, N) matrix is in column major form
|
| 61 |
+
* - Let Tensor P have size (B, M, N) and Q have size (B, M', N').
|
| 62 |
+
* Then when laid out in memory, the M by N matrix starting at
|
| 63 |
+
* P.data_ptr()[B * M * N] is of the same corresponding batch as the M' by N'
|
| 64 |
+
* matrix starting at Q.data_ptr()[B * M' * N'].
|
| 65 |
+
*/
|
| 66 |
+
inline Tensor cloneBatchedColumnMajor(const Tensor& src) {
|
| 67 |
+
// If src is already in batched column major format, then
|
| 68 |
+
// this will be efficient (no reordering of the data will occur)
|
| 69 |
+
// because the first transpose will make the tensor contiguous,
|
| 70 |
+
// and cloning a contiguous tensor is fast.
|
| 71 |
+
auto result = src.mT().clone(at::MemoryFormat::Contiguous);
|
| 72 |
+
result.transpose_(-2, -1);
|
| 73 |
+
return result;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/*
|
| 77 |
+
* contig chooses between C-contig (true) and F-contig (false)
|
| 78 |
+
*/
|
| 79 |
+
inline c10::MaybeOwned<Tensor> borrow_else_clone(const bool cond, const Tensor& borrow, const Tensor& clone, const bool contig) {
|
| 80 |
+
return cond ? c10::MaybeOwned<Tensor>::borrowed(borrow)
|
| 81 |
+
: c10::MaybeOwned<Tensor>::owned(contig ? clone.clone(MemoryFormat::Contiguous)
|
| 82 |
+
: cloneBatchedColumnMajor(clone));
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
/*
|
| 86 |
+
* This method is designed to be a faster alternative to
|
| 87 |
+
* `cloneBatchedColumnMajor` with some additional features,
|
| 88 |
+
* namely:
|
| 89 |
+
* 1. It uses `copy` instead of `clone` which could be much faster.
|
| 90 |
+
* 2. `nrows` parameter used to create inputs with the number of rows larger
|
| 91 |
+
* than the original input, which is required for some LAPACK/MAGMA methods.
|
| 92 |
+
* 3. `desired_batch_size` is used to create copies with the batch size
|
| 93 |
+
* which is either the original batch size of the input, or its larger
|
| 94 |
+
* broadcasted shape.
|
| 95 |
+
*/
|
| 96 |
+
inline Tensor copyBatchedColumnMajor(const Tensor& src, int64_t nrows = -1,
|
| 97 |
+
at::OptionalIntArrayRef desired_batch_sizes = std::nullopt) {
|
| 98 |
+
nrows = (nrows == -1) ? src.size(-2) : nrows;
|
| 99 |
+
auto copy_sizes = desired_batch_sizes.has_value()
|
| 100 |
+
? desired_batch_sizes.value().vec()
|
| 101 |
+
: IntArrayRef(src.sizes().data(), src.dim() - 2).vec();
|
| 102 |
+
copy_sizes.insert(copy_sizes.end(), {nrows, src.size(-1)});
|
| 103 |
+
const auto copy_strides = batched_matrix_contiguous_strides(copy_sizes, /*f-contig*/true);
|
| 104 |
+
auto copy = at::empty_strided(copy_sizes, copy_strides, src.options());
|
| 105 |
+
copy.narrow(-2, 0, src.size(-2)).copy_(src);
|
| 106 |
+
return copy;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
/*
|
| 110 |
+
* Given batches of matrices with arbitrary batch dim,
|
| 111 |
+
* computes the number of batches.
|
| 112 |
+
*/
|
| 113 |
+
inline int64_t batchCount(const Tensor& batched_matrices) {
|
| 114 |
+
int64_t result = 1;
|
| 115 |
+
for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
|
| 116 |
+
result *= batched_matrices.size(i);
|
| 117 |
+
}
|
| 118 |
+
return result;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// Computes the number of elements of a matrix in a batched matrix tensor
|
| 122 |
+
inline int64_t matrixStride(const Tensor& batched_matrices) {
|
| 123 |
+
return batched_matrices.size(-1) * batched_matrices.size(-2);
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// Validates input shapes for operations on batches of square matrices (inverse, cholesky, symeig, eig)
|
| 127 |
+
inline void checkIsMatrix(const Tensor& A, const char* const f_name, const char* const arg_name = "A") {
|
| 128 |
+
TORCH_CHECK(A.dim() >= 2, f_name, ": The input tensor ", arg_name, " must have at least 2 dimensions.");
|
| 129 |
+
}
|
| 130 |
+
inline void squareCheckInputs(const Tensor& self, const char* const f_name, const char* const arg_name = "A") {
|
| 131 |
+
checkIsMatrix(self, f_name, arg_name);
|
| 132 |
+
TORCH_CHECK(self.sym_size(-1) == self.sym_size(-2),
|
| 133 |
+
f_name,
|
| 134 |
+
": ", arg_name, " must be batches of square matrices, "
|
| 135 |
+
"but they are ", self.sym_size(-2), " by ", self.sym_size(-1), " matrices");
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
inline void checkInputsSolver(const Tensor& A,
|
| 139 |
+
const Tensor& B,
|
| 140 |
+
const bool left,
|
| 141 |
+
const char* const f_name) {
|
| 142 |
+
squareCheckInputs(A, f_name, "A");
|
| 143 |
+
checkIsMatrix(B, f_name, "B");
|
| 144 |
+
TORCH_CHECK(left ? A.size(-2) == B.size(-2) : A.size(-1) == B.size(-1),
|
| 145 |
+
f_name, ": Incompatible shapes of A and B for the equation ",
|
| 146 |
+
left ? "AX = B" : "XA = B",
|
| 147 |
+
" (", A.size(-2), "x", A.size(-1), " and ", B.size(-2), "x", B.size(-1), ")");
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
inline bool is_row_or_column_contiguous(const Tensor& t) {
|
| 151 |
+
// This could be made more general, similar to how it's checked in matmul, which would allow to
|
| 152 |
+
// elide the copy with strides such as (6, 12, 1, 3) or (3, 1, 9), but this is quite tricky.
|
| 153 |
+
// We choose to be conservative for simplicity
|
| 154 |
+
return t.is_contiguous() || t.transpose(-2, -1).is_contiguous();
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
inline TransposeType to_transpose_type(const bool contig, const bool conj) {
|
| 158 |
+
if (conj) {
|
| 159 |
+
if (contig) { TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); }
|
| 160 |
+
else { return TransposeType::ConjTranspose; }
|
| 161 |
+
} else {
|
| 162 |
+
if (contig) { return TransposeType::NoTranspose; }
|
| 163 |
+
else { return TransposeType::Transpose; }
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
// This function is designed to be used with linear algebra methods that minimize
|
| 169 |
+
// L(ax - b) = 0, where L is generally the identity map (`solve`, for example)
|
| 170 |
+
// or the L2 norm (`lstsq`).
|
| 171 |
+
// It is expected that `a` and `b` are contiguous tensors of column-major matrices
|
| 172 |
+
// (so that a.view({-1, a.size(-2), a.size(-1)}) succeeds, same for `b`),
|
| 173 |
+
// with the following additional properties:
|
| 174 |
+
//
|
| 175 |
+
// 1. a.dim() == b.dim()
|
| 176 |
+
// 2. a.shape[:-2] broadcasts over b.shape[:-2]
|
| 177 |
+
// 3. a.size(i) <= b.size(i) for i=0,..., a.dim() - 3 (only for batch dimensions)
|
| 178 |
+
//
|
| 179 |
+
// MAGMA/LAPACK modify tensor `a` in-place, and the main goal of this method
|
| 180 |
+
// is to be memory efficient, which means that if there exists an index i such that
|
| 181 |
+
// a.shape[i] < b.shape[i], 0 <= i <= a.dim() - 3,
|
| 182 |
+
// then instead of materializing copies of `a` in the broadcasted shape, we keep
|
| 183 |
+
// a buffer copy of `a` along with flags that check whether specific batch dimension
|
| 184 |
+
// indices for `a` were already accessed. If they were, we copy the data from the buffer
|
| 185 |
+
// into `a`. The number of copies does not exceed
|
| 186 |
+
// prod(max(a.shape[:-2], b.shape[:-2]) - a.shape[:-2] + 1)
|
| 187 |
+
// and this value is attained by tensors with non-empty batch dimensions.
|
| 188 |
+
//
|
| 189 |
+
// func_t `f` is a callable that is being supplied with
|
| 190 |
+
// scalar_t* a_working_ptr, scalar_t* b_working_ptr, int64_t a_linear_batch_idx.
|
| 191 |
+
// a_working_ptr and b_working_ptr can directly be passed to LAPACK/MAGMA routines,
|
| 192 |
+
// and a_linear_batch_idx is an index in the 3d representation which corresponds to
|
| 193 |
+
// the memory a_working_ptr points to, in other words:
|
| 194 |
+
// a_working_ptr == a.view({-1, a.size(-2), a.size(-1)}.select(0, a_linear_batch_idx).data_ptr<scalar_t>();
|
| 195 |
+
// a_linear_batch_idx is useful to store metadata related to `a`, such as, for example,
|
| 196 |
+
// its rank or singular values (see linalg_lstsq).
|
| 197 |
+
template<typename scalar_t, typename func_t>
|
| 198 |
+
void batch_iterator_with_broadcasting(const Tensor& a, const Tensor& b, const func_t& f) {
|
| 199 |
+
IntArrayRef a_batch_sizes(a.sizes().data(), a.dim() - 2);
|
| 200 |
+
IntArrayRef b_batch_sizes(b.sizes().data(), b.dim() - 2);
|
| 201 |
+
|
| 202 |
+
auto a_linear_batch_idx = at::arange(batchCount(a)).view(a_batch_sizes);
|
| 203 |
+
auto b_linear_batch_idx = at::arange(batchCount(b)).view(b_batch_sizes);
|
| 204 |
+
|
| 205 |
+
TensorIterator iter = TensorIteratorConfig()
|
| 206 |
+
.set_check_mem_overlap(false)
|
| 207 |
+
.check_all_same_dtype(false)
|
| 208 |
+
.resize_outputs(false)
|
| 209 |
+
.add_output(b_linear_batch_idx)
|
| 210 |
+
.add_input(a_linear_batch_idx)
|
| 211 |
+
.build();
|
| 212 |
+
|
| 213 |
+
auto m = a.size(-2);
|
| 214 |
+
auto n = a.size(-1);
|
| 215 |
+
auto a_3d = a.view({batchCount(a), m, n});
|
| 216 |
+
auto b_3d = b.view({batchCount(b), b.size(-2), b.size(-1)});
|
| 217 |
+
|
| 218 |
+
auto a_broadcasts_over_b = (a_batch_sizes != b_batch_sizes);
|
| 219 |
+
Tensor a_buffer, a_was_accessed, a_buffer_3d;
|
| 220 |
+
std::function<void(int64_t)> check_if_copy_needed_for_a
|
| 221 |
+
= [](int64_t /*a_curr_linear_batch_idx*/){};
|
| 222 |
+
if (a_broadcasts_over_b) {
|
| 223 |
+
a_buffer = at::empty_strided(a.sizes(), a.strides(), a.options())
|
| 224 |
+
.copy_(a);
|
| 225 |
+
a_was_accessed = at::zeros(batchCount(a), at::kBool);
|
| 226 |
+
a_buffer_3d = a_buffer.view({batchCount(a), m, n});
|
| 227 |
+
check_if_copy_needed_for_a = [&](int64_t a_curr_linear_batch_idx) {
|
| 228 |
+
auto* a_was_accessed_flag = a_was_accessed
|
| 229 |
+
.select(0, a_curr_linear_batch_idx)
|
| 230 |
+
.data_ptr<bool>();
|
| 231 |
+
if (!(*a_was_accessed_flag)) {
|
| 232 |
+
*a_was_accessed_flag = true;
|
| 233 |
+
}
|
| 234 |
+
else {
|
| 235 |
+
a_3d.select(0, a_curr_linear_batch_idx)
|
| 236 |
+
.copy_(a_buffer_3d.select(0, a_curr_linear_batch_idx));
|
| 237 |
+
}
|
| 238 |
+
};
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
auto loop = [&](char** data, const int64_t* strides, int64_t nelems) {
|
| 242 |
+
auto* b_batch_idx_ptr = data[0];
|
| 243 |
+
auto* a_batch_idx_ptr = data[1];
|
| 244 |
+
|
| 245 |
+
for ([[maybe_unused]] const auto elem : c10::irange(nelems)) {
|
| 246 |
+
auto b_curr_linear_batch_idx =
|
| 247 |
+
*reinterpret_cast<int64_t*>(b_batch_idx_ptr);
|
| 248 |
+
auto a_curr_linear_batch_idx = *reinterpret_cast<int64_t*>(a_batch_idx_ptr);
|
| 249 |
+
|
| 250 |
+
check_if_copy_needed_for_a(a_curr_linear_batch_idx);
|
| 251 |
+
|
| 252 |
+
auto* a_working_ptr = a_3d.select(0, a_curr_linear_batch_idx)
|
| 253 |
+
.data_ptr<scalar_t>();
|
| 254 |
+
auto* b_working_ptr = b_3d.select(0, b_curr_linear_batch_idx)
|
| 255 |
+
.data_ptr<scalar_t>();
|
| 256 |
+
f(a_working_ptr, b_working_ptr, a_curr_linear_batch_idx);
|
| 257 |
+
|
| 258 |
+
b_batch_idx_ptr += strides[0];
|
| 259 |
+
a_batch_idx_ptr += strides[1];
|
| 260 |
+
}
|
| 261 |
+
};
|
| 262 |
+
iter.serial_for_each(loop, {0, batchCount(b)});
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
// Returns the epsilon value for floating types except half
|
| 266 |
+
inline double _get_epsilon(const ScalarType& sc_type) {
|
| 267 |
+
switch (sc_type) {
|
| 268 |
+
case at::ScalarType::Float:
|
| 269 |
+
return static_cast<double>(std::numeric_limits<float>::epsilon());
|
| 270 |
+
case at::ScalarType::Double:
|
| 271 |
+
return std::numeric_limits<double>::epsilon();
|
| 272 |
+
default:
|
| 273 |
+
TORCH_CHECK(false, "This function doesn't handle types other than float and double");
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
// Validates input shapes and devices
|
| 278 |
+
// for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve)
|
| 279 |
+
inline void linearSolveCheckInputs(const Tensor& self, const Tensor& A, const char* name) {
|
| 280 |
+
TORCH_CHECK(self.device() == A.device(),
|
| 281 |
+
"Expected b and A to be on the same device, but found b on ",
|
| 282 |
+
self.device(), " and A on ", A.device(), " instead.");
|
| 283 |
+
|
| 284 |
+
TORCH_CHECK(self.scalar_type() == A.scalar_type(),
|
| 285 |
+
"Expected b and A to have the same dtype, but found b of type ",
|
| 286 |
+
self.scalar_type(), " and A of type ", A.scalar_type(), " instead.");
|
| 287 |
+
|
| 288 |
+
TORCH_CHECK(A.size(-1) == A.size(-2),
|
| 289 |
+
"A must be batches of square matrices, "
|
| 290 |
+
"but they are ", A.size(-2), " by ", A.size(-1), " matrices");
|
| 291 |
+
|
| 292 |
+
TORCH_CHECK(A.size(-1) == self.size(-2),
|
| 293 |
+
"Incompatible matrix sizes for ", name, ": each A "
|
| 294 |
+
"matrix is ", A.size(-1), " by ", A.size(-1),
|
| 295 |
+
" but each b matrix is ", self.size(-2), " by ", self.size(-1));
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
inline void checkFloatingOrComplex(const Tensor& t, const char* const f_name, const bool allow_low_precision_dtypes=true) {
|
| 299 |
+
auto dtype = t.scalar_type();
|
| 300 |
+
TORCH_CHECK((at::isFloatingType(dtype) || at::isComplexType(dtype)),
|
| 301 |
+
f_name, ": Expected a floating point or complex tensor as input. Got ", dtype);
|
| 302 |
+
if (!allow_low_precision_dtypes) {
|
| 303 |
+
TORCH_CHECK(dtype == kFloat || dtype == kDouble || dtype == kComplexFloat || dtype == kComplexDouble,
|
| 304 |
+
f_name, ": Low precision dtypes not supported. Got ", dtype);
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
// Checks if all the Tensors in a TensorList are of the same dimensions
|
| 310 |
+
inline void checkAllSameDim(TensorList tensors, int64_t dim) {
|
| 311 |
+
for (auto &t : tensors) {
|
| 312 |
+
TORCH_CHECK(t.dim() == dim, "Tensor dimension is ", t.dim(), ", expected ", dim, " instead.");
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
inline std::tuple<std::vector<int64_t>, std::vector<int64_t>> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2) {
|
| 317 |
+
// broadcast the batch dimensions of arg1 and arg2.
|
| 318 |
+
IntArrayRef arg1_batch_sizes(arg1.sizes().data(), arg1.ndimension() - 2);
|
| 319 |
+
IntArrayRef arg2_batch_sizes(arg2.sizes().data(), arg2.ndimension() - 2);
|
| 320 |
+
std::vector<int64_t> expand_batch_portion = infer_size(arg1_batch_sizes, arg2_batch_sizes);
|
| 321 |
+
|
| 322 |
+
std::vector<int64_t> arg1_expand_size({expand_batch_portion});
|
| 323 |
+
arg1_expand_size.insert(arg1_expand_size.end(), { arg1.size(-2), arg1.size(-1) });
|
| 324 |
+
|
| 325 |
+
std::vector<int64_t> arg2_expand_size({expand_batch_portion});
|
| 326 |
+
arg2_expand_size.insert(arg2_expand_size.end(), { arg2.size(-2), arg2.size(-1) });
|
| 327 |
+
return std::make_tuple(std::move(arg1_expand_size), std::move(arg2_expand_size));
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
inline std::tuple<Tensor,Tensor> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2, const char* name) {
|
| 331 |
+
// If there's no name we assume we don't want to check the errors
|
| 332 |
+
if (name != nullptr) {
|
| 333 |
+
linearSolveCheckInputs(arg1, arg2, name);
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
auto [arg1_expand_size, arg2_expand_size] = at::native::_linalg_broadcast_batch_dims(arg1, arg2);
|
| 337 |
+
|
| 338 |
+
auto arg1_broadcasted = arg1_expand_size == arg1.sizes() ? arg1 : arg1.expand(arg1_expand_size);
|
| 339 |
+
auto arg2_broadcasted = arg2_expand_size == arg2.sizes() ? arg2 : arg2.expand(arg2_expand_size);
|
| 340 |
+
return std::make_tuple(arg1_broadcasted, arg2_broadcasted);
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
inline std::vector<int64_t> broadcast_batch_size(const Tensor& t1, const Tensor& t2, int64_t n_batch_dims) {
|
| 344 |
+
IntArrayRef t1_batch_sizes(t1.sizes().data(), n_batch_dims);
|
| 345 |
+
IntArrayRef t2_batch_sizes(t2.sizes().data(), n_batch_dims);
|
| 346 |
+
auto broadcasted_batch_sizes = infer_size(t1_batch_sizes, t2_batch_sizes);
|
| 347 |
+
return broadcasted_batch_sizes;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
// Return a permutation with the given axes moved to the end.
|
| 351 |
+
inline Tensor _move_to_end(const Tensor& self, IntArrayRef axes) {
|
| 352 |
+
const std::vector<int64_t> a = axes.vec();
|
| 353 |
+
const int64_t ndim = self.ndimension();
|
| 354 |
+
std::vector<int64_t> perm;
|
| 355 |
+
|
| 356 |
+
for (const auto i : c10::irange(ndim)) {
|
| 357 |
+
auto it = std::find(a.begin(), a.end(), i);
|
| 358 |
+
if (it == a.end()) {
|
| 359 |
+
perm.push_back(i);
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
for (auto i : a) {
|
| 363 |
+
perm.push_back(i);
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
TORCH_CHECK((int64_t)perm.size() == ndim,
|
| 367 |
+
"duplicate or invalid axis in 'dim' argument for tensor with ndim==", ndim);
|
| 368 |
+
|
| 369 |
+
return self.permute(perm);
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
// parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced)
|
| 373 |
+
inline std::tuple<bool, bool> _parse_qr_mode(std::string_view mode) {
|
| 374 |
+
bool compute_q;
|
| 375 |
+
bool reduced;
|
| 376 |
+
if (mode == "reduced") {
|
| 377 |
+
compute_q = true;
|
| 378 |
+
reduced = true;
|
| 379 |
+
} else if (mode == "complete") {
|
| 380 |
+
compute_q = true;
|
| 381 |
+
reduced = false;
|
| 382 |
+
} else if (mode == "r") {
|
| 383 |
+
compute_q = false;
|
| 384 |
+
reduced = true; // this is actually irrelevant in this mode
|
| 385 |
+
} else {
|
| 386 |
+
TORCH_CHECK(false, "qr received unrecognized mode '", mode,
|
| 387 |
+
"' but expected one of 'reduced' (default), 'r', or 'complete'");
|
| 388 |
+
}
|
| 389 |
+
return std::make_tuple(compute_q, reduced);
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
// Function to compute sizes, strides and the extra columns for the Q matrix in the QR Decomposition
|
| 393 |
+
inline std::tuple<DimVector, DimVector, int64_t> _compute_geometry_for_Q(
|
| 394 |
+
const Tensor& input,
|
| 395 |
+
bool reduced) {
|
| 396 |
+
int64_t m = input.size(-2), n = input.size(-1);
|
| 397 |
+
int64_t n_columns_q;
|
| 398 |
+
|
| 399 |
+
// We need to compute the required size of Q based on the `reduced` option
|
| 400 |
+
DimVector q_sizes(input.sizes());
|
| 401 |
+
if (!reduced && m > n) {
|
| 402 |
+
q_sizes[input.dim() - 1] = m;
|
| 403 |
+
n_columns_q = m;
|
| 404 |
+
} else {
|
| 405 |
+
q_sizes[input.dim() - 1] = n;
|
| 406 |
+
n_columns_q = std::min(m, n);
|
| 407 |
+
}
|
| 408 |
+
auto q_strides = batched_matrix_contiguous_strides(q_sizes, /*f-contig*/true);
|
| 409 |
+
return std::make_tuple(q_sizes, q_strides, n_columns_q);
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
inline bool svd_uses_cusolver(const Tensor& A) {
|
| 413 |
+
// if cusolver is available, it is used unconditionally
|
| 414 |
+
return A.is_cuda()
|
| 415 |
+
&& at::globalContext().hasCuSOLVER()
|
| 416 |
+
&& at::globalContext().linalgPreferredBackend() != at::LinalgBackend::Magma;
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
// Function used instead of .to so that the original strides are retained
|
| 421 |
+
// .to doesn't retain strides and make the output tensor contiguous
|
| 422 |
+
inline Tensor same_stride_to(const Tensor& original_tensor, const at::TensorOptions& options) {
|
| 423 |
+
auto strided_to = at::empty_strided(original_tensor.sizes(),
|
| 424 |
+
original_tensor.strides(),
|
| 425 |
+
options);
|
| 426 |
+
strided_to.copy_(original_tensor);
|
| 427 |
+
return strided_to;
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
// Creates a dimension permutation array that can be given to `at::permute()`, which will shift
|
| 431 |
+
// the two specified dimensions to the end of a tensor, without changing the order of
|
| 432 |
+
// the other dimensions. `dim1` will be placed at the very end, and `dim0` will be
|
| 433 |
+
// placed just to the left of it.
|
| 434 |
+
//
|
| 435 |
+
// For instance, given a 4-D tensor, dimensions 1 and 3 can be shifted to the end by
|
| 436 |
+
// calling `create_dim_backshift_permutation(1, 3, 4)`. The resulting vector will
|
| 437 |
+
// be `vec(0, 2, 1, 3)`.
|
| 438 |
+
inline std::vector<int64_t> create_dim_backshift_permutation(int64_t dim0, int64_t dim1, int64_t ndim) {
|
| 439 |
+
TORCH_CHECK(
|
| 440 |
+
(dim0 != dim1) && (dim0 < ndim) && (dim0 >= 0) && (dim1 < ndim) && (dim1 >= 0),
|
| 441 |
+
"duplicate or invalid dimensions");
|
| 442 |
+
std::vector<int64_t> permutation(ndim);
|
| 443 |
+
int64_t cur_permuted_dim = 0;
|
| 444 |
+
for (const auto dim_ind : c10::irange(ndim)) {
|
| 445 |
+
if ((dim_ind != dim0) && (dim_ind != dim1)) {
|
| 446 |
+
permutation[cur_permuted_dim++] = dim_ind;
|
| 447 |
+
}
|
| 448 |
+
}
|
| 449 |
+
permutation[cur_permuted_dim++] = dim0;
|
| 450 |
+
permutation[cur_permuted_dim] = dim1;
|
| 451 |
+
return permutation;
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
// Creates a dimension permutation array that can be given to `at::permute()`, which
|
| 455 |
+
// will reverse a given permutation.
|
| 456 |
+
// The reverse permutation array is created by swapping the indices and their
|
| 457 |
+
// associated values from the given permutation array.
|
| 458 |
+
inline std::vector<int64_t> create_reverse_permutation(std::vector<int64_t> permutation) {
|
| 459 |
+
int64_t ndim = permutation.size();
|
| 460 |
+
std::vector<int64_t> reverse_permutation(ndim);
|
| 461 |
+
for (const auto dim_ind : c10::irange(ndim)) {
|
| 462 |
+
reverse_permutation[permutation[dim_ind]] = dim_ind;
|
| 463 |
+
}
|
| 464 |
+
return reverse_permutation;
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
// Compute R-work array size for MAGMA/LAPACK cgesdd/zgesdd
|
| 468 |
+
// See https://github.com/Reference-LAPACK/lapack/blob/122506cd8b6ce050a200920c3d4c0b153b150fd8/SRC/cgesdd.f#L186
|
| 469 |
+
inline int64_t computeLRWorkDim(const char jobz, int64_t m, int64_t n) {
|
| 470 |
+
auto mn = std::min(m, n);
|
| 471 |
+
auto mx = std::max(m, n);
|
| 472 |
+
if (jobz == 'N') {
|
| 473 |
+
#ifdef __APPLE__
|
| 474 |
+
// According to `vecLib.framework/Headers/clapack.h` Accelerate.framework is based on LAPACK 3.2.1
|
| 475 |
+
return 7 * mn;
|
| 476 |
+
#else
|
| 477 |
+
// These setting is valid for on LAPACK 3.6+
|
| 478 |
+
return 5 * mn;
|
| 479 |
+
#endif
|
| 480 |
+
}
|
| 481 |
+
if (mx > 10 * mn) {
|
| 482 |
+
return 5 * mn * mn + 5 * mn;
|
| 483 |
+
}
|
| 484 |
+
return std::max(5 * mn * mn + 5 * mn, 2 * mx * mn + 2 * mn * mn + mn);
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
// This function checks whether the uplo argument input is valid
|
| 488 |
+
// Allowed strings are "u", "U", "l", "L"
|
| 489 |
+
inline void checkUplo(const std::string_view uplo) {
|
| 490 |
+
// To use std::toupper safely with plain chars (or signed chars), the argument should first be converted to unsigned char
|
| 491 |
+
char uplo_uppercase = static_cast<char>(std::toupper(static_cast<unsigned char>(uplo[0])));
|
| 492 |
+
TORCH_CHECK(uplo.size() == 1 && (uplo_uppercase == 'U' || uplo_uppercase == 'L'),
|
| 493 |
+
"Expected UPLO argument to be 'L' or 'U', but got ", uplo);
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
inline void checkSameDevice(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
|
| 497 |
+
TORCH_CHECK(
|
| 498 |
+
result.device() == input.device(),
|
| 499 |
+
fn_name,
|
| 500 |
+
": Expected ", result_name, " and input tensors to be on the same device, but got ",
|
| 501 |
+
result_name, " on ", result.device(), " and input on ", input.device());
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
// Check the dtype of result and input tensors (for _out variants).
|
| 505 |
+
// Most linear algebra functions have the same dtype for input and output
|
| 506 |
+
// (either floating or complex type input), so we can check whether input's dtype can be casted to result's dtype.
|
| 507 |
+
// According to https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-does-out-work-in-pytorch
|
| 508 |
+
// c10::canCast is used for checking the "safe copy" dtype requirements.
|
| 509 |
+
inline void checkLinalgCompatibleDtype(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
|
| 510 |
+
bool can_cast = c10::canCast(input.scalar_type(), result.scalar_type());
|
| 511 |
+
TORCH_CHECK(
|
| 512 |
+
can_cast,
|
| 513 |
+
fn_name,
|
| 514 |
+
": Expected ", result_name, " to be safely castable from ", input.scalar_type(), " dtype, but got ",
|
| 515 |
+
result_name, " with dtype ", result.scalar_type());
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
// Alternatively, we can check whether the specific expected output type (result_type) can be safely casted to out tensor dtype (out_type)
|
| 519 |
+
inline void checkLinalgCompatibleDtype(const std::string& fn_name, ScalarType out_type, ScalarType result_type, const std::string& out_name = "result") {
|
| 520 |
+
bool can_cast = c10::canCast(result_type, out_type);
|
| 521 |
+
TORCH_CHECK(
|
| 522 |
+
can_cast,
|
| 523 |
+
fn_name,
|
| 524 |
+
": Expected ", out_name, " to be safely castable from ", result_type, " dtype, but got ",
|
| 525 |
+
out_name, " with dtype ", out_type);
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
inline void checkNotComplexTolerance(const Tensor& tol, const std::string_view f_name, const std::string_view tol_name) {
|
| 529 |
+
TORCH_CHECK(!at::isComplexType(tol.scalar_type()),
|
| 530 |
+
f_name, ": ", tol_name, " tensor of complex type is not supported. Got ", tol.scalar_type());
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
/*
|
| 534 |
+
Two types of 'other' tensors are supported when solving
|
| 535 |
+
a system of linear equations matmul(input, x) = other:
|
| 536 |
+
* 1-dimensional (1D) tensor or batch of 1D tensors (vector case)
|
| 537 |
+
* 2-dimensional (2D) tensor or batch of 2D tensors (matrix case).
|
| 538 |
+
The original torch.solve supported only the matrix case, while NumPy works for both cases.
|
| 539 |
+
For the batched input we need to be able to distinguish them.
|
| 540 |
+
Let input.shape = (batch_dimensions, m, n), then 'other' is of vector type if other.shape == (batch_dimensions, m).
|
| 541 |
+
This rule is compatible with NumPy, see https://github.com/numpy/numpy/blob/v1.20.0/numpy/linalg/linalg.py#L384-L389
|
| 542 |
+
*/
|
| 543 |
+
inline bool linalg_solve_is_vector_rhs(const Tensor& input, const Tensor& other) {
|
| 544 |
+
auto expected_batched_rhs_shape = SymIntArrayRef(input.sym_sizes().data(), input.dim() - 1); // input.shape[:-1]
|
| 545 |
+
bool vector_case = other.dim() == 1 || (input.dim() - 1 == other.dim() && other.sym_sizes().equals(expected_batched_rhs_shape));
|
| 546 |
+
return vector_case;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
/*
|
| 550 |
+
Computes linear indices for a tensor with original_shape to access its elements like it was a materialized broadcast tensor.
|
| 551 |
+
*/
|
| 552 |
+
inline Tensor get_linear_indices(int64_t numel, IntArrayRef original_shape, IntArrayRef broadcast_shape) {
|
| 553 |
+
TensorOptions options = at::TensorOptions().dtype(at::kLong).device(at::kCPU);
|
| 554 |
+
return at::arange(numel, options).view(original_shape).broadcast_to(broadcast_shape).contiguous();
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
class BroadcastLinearIndices {
|
| 558 |
+
private:
|
| 559 |
+
Tensor linear_indices_;
|
| 560 |
+
bool is_broadcasting_;
|
| 561 |
+
|
| 562 |
+
public:
|
| 563 |
+
BroadcastLinearIndices(
|
| 564 |
+
int64_t numel,
|
| 565 |
+
IntArrayRef original_shape,
|
| 566 |
+
IntArrayRef broadcast_shape) : is_broadcasting_(!original_shape.equals(broadcast_shape)) {
|
| 567 |
+
// The assumption is that the broadcast_shape is a materialized broadcast
|
| 568 |
+
// shape of the original_shape. We need to compute the linear indices
|
| 569 |
+
// compatible with the original_shape to access the elements in the original
|
| 570 |
+
// tensor corresponding to the broadcast tensor.
|
| 571 |
+
if (is_broadcasting_) {
|
| 572 |
+
linear_indices_ =
|
| 573 |
+
get_linear_indices(numel, original_shape, broadcast_shape);
|
| 574 |
+
}
|
| 575 |
+
}
|
| 576 |
+
int64_t operator()(int64_t broadcast_linear_index) {
|
| 577 |
+
return is_broadcasting_
|
| 578 |
+
? linear_indices_.data_ptr<int64_t>()[broadcast_linear_index]
|
| 579 |
+
: broadcast_linear_index;
|
| 580 |
+
}
|
| 581 |
+
};
|
| 582 |
+
|
| 583 |
+
inline bool is_blas_compatible_column_major_order(const Tensor& input) {
|
| 584 |
+
IntArrayRef input_strides = input.strides();
|
| 585 |
+
IntArrayRef input_sizes = input.sizes();
|
| 586 |
+
auto ndim = input.dim();
|
| 587 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
|
| 588 |
+
if (ndim > 3) {
|
| 589 |
+
return input.transpose(-2, -1).is_contiguous();
|
| 590 |
+
}
|
| 591 |
+
auto leading_dimension = input_strides[ndim - 1];
|
| 592 |
+
auto rows = input_sizes[ndim - 2];
|
| 593 |
+
bool batch_stride_compatible = true;
|
| 594 |
+
if (ndim == 3) {
|
| 595 |
+
auto cols = input_sizes[ndim - 1];
|
| 596 |
+
batch_stride_compatible =
|
| 597 |
+
input_strides[ndim - 3] >= leading_dimension * cols;
|
| 598 |
+
}
|
| 599 |
+
return (input_strides[ndim - 2] == 1) &&
|
| 600 |
+
(leading_dimension >= std::max<int64_t>(1, rows)) &&
|
| 601 |
+
batch_stride_compatible;
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
inline bool is_blas_compatible_row_major_order(const Tensor& input) {
|
| 605 |
+
IntArrayRef input_strides = input.strides();
|
| 606 |
+
IntArrayRef input_sizes = input.sizes();
|
| 607 |
+
auto ndim = input.dim();
|
| 608 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
|
| 609 |
+
if (ndim > 3) {
|
| 610 |
+
return input.is_contiguous();
|
| 611 |
+
}
|
| 612 |
+
auto leading_dimension = input_strides[ndim - 2];
|
| 613 |
+
auto cols = input_sizes[ndim - 1];
|
| 614 |
+
bool batch_stride_compatible = true;
|
| 615 |
+
if (ndim == 3) {
|
| 616 |
+
auto rows = input_sizes[ndim - 2];
|
| 617 |
+
batch_stride_compatible =
|
| 618 |
+
input_strides[ndim - 3] >= leading_dimension * rows;
|
| 619 |
+
}
|
| 620 |
+
return (input_strides[ndim - 1] == 1) &&
|
| 621 |
+
(leading_dimension >= std::max<int64_t>(1, cols)) &&
|
| 622 |
+
batch_stride_compatible;
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
} // namespace at::native
|
| 626 |
+
|
| 627 |
+
#else
|
| 628 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 629 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/LossMulti.h
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
| 2 |
+
#pragma once
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <ATen/AccumulateType.h>
|
| 5 |
+
#include <ATen/Dispatch.h>
|
| 6 |
+
#include <ATen/TensorUtils.h>
|
| 7 |
+
|
| 8 |
+
namespace at::native {
|
| 9 |
+
inline void multilabel_margin_loss_shape_check(
|
| 10 |
+
int64_t& nframe,
|
| 11 |
+
int64_t& dim,
|
| 12 |
+
const int64_t& ndims,
|
| 13 |
+
const Tensor& input,
|
| 14 |
+
const Tensor& target) {
|
| 15 |
+
TORCH_CHECK(
|
| 16 |
+
(ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0,
|
| 17 |
+
"Expected non-empty vector or matrix with optional 0-dim batch size, but got: ",
|
| 18 |
+
input.sizes());
|
| 19 |
+
|
| 20 |
+
if (ndims <= 1) {
|
| 21 |
+
nframe = 1;
|
| 22 |
+
dim = ndims == 0 ? 1 : input.size(0);
|
| 23 |
+
TORCH_CHECK(
|
| 24 |
+
target.dim() <= 1 && target.numel() == dim,
|
| 25 |
+
"inconsistent target size: ", target.sizes(), " for input of size: ",
|
| 26 |
+
input.sizes());
|
| 27 |
+
} else {
|
| 28 |
+
nframe = input.size(0);
|
| 29 |
+
dim = input.size(1);
|
| 30 |
+
TORCH_CHECK(
|
| 31 |
+
target.dim() == 2 && target.size(0) == nframe &&
|
| 32 |
+
target.size(1) == dim,
|
| 33 |
+
"inconsistent target size: ", target.sizes(), " for input of size: ",
|
| 34 |
+
input.sizes());
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
inline void multi_margin_loss_shape_check(
|
| 39 |
+
int64_t& nframe,
|
| 40 |
+
int64_t& dim,
|
| 41 |
+
const int64_t& ndims,
|
| 42 |
+
const Tensor& input,
|
| 43 |
+
const Tensor& target,
|
| 44 |
+
const std::optional<Tensor>& weight) {
|
| 45 |
+
TORCH_CHECK(
|
| 46 |
+
(ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0,
|
| 47 |
+
"Expected non-empty vector or matrix with optional 0-dim batch size, but got: ",
|
| 48 |
+
input.sizes());
|
| 49 |
+
|
| 50 |
+
if (ndims <= 1) {
|
| 51 |
+
nframe = 1;
|
| 52 |
+
dim = ndims == 0 ? 1 : input.size(0);
|
| 53 |
+
} else {
|
| 54 |
+
nframe = input.size(0);
|
| 55 |
+
dim = input.size(1);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
TORCH_CHECK(
|
| 59 |
+
target.dim() <= 1 && target.numel() == nframe,
|
| 60 |
+
"inconsistent target size, expected ", nframe, " but got ",
|
| 61 |
+
target.sizes());
|
| 62 |
+
if (weight && weight->defined()) {
|
| 63 |
+
TORCH_CHECK(
|
| 64 |
+
weight->dim() <= 1 && weight->numel() == dim,
|
| 65 |
+
"inconsistent weight size, expected ", dim, " but got ",
|
| 66 |
+
weight->sizes());
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
} // namespace at::native
|
| 71 |
+
|
| 72 |
+
#else
|
| 73 |
+
#error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
|
| 74 |
+
#endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/ATen/native/Math.h
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|