jasonfan commited on
Commit
b4dab06
·
verified ·
1 Parent(s): e987678

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DeadlockDetection.h +52 -0
  2. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Deprecated.h +102 -0
  3. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DimVector.h +17 -0
  4. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DynamicCounter.h +49 -0
  5. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Enumerate.h +159 -0
  6. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Exception.h +782 -0
  7. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ExclusivelyOwned.h +140 -0
  8. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ExclusivelyOwnedTensorTraits.h +75 -0
  9. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/FbcodeMaps.h +29 -0
  10. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Flags.h +242 -0
  11. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float4_e2m1fn_x2.h +28 -0
  12. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fn-inl.h +274 -0
  13. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fn.h +240 -0
  14. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fnuz-inl.h +279 -0
  15. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fnuz.h +139 -0
  16. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2-inl.h +286 -0
  17. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2.h +148 -0
  18. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2fnuz-inl.h +285 -0
  19. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2fnuz.h +138 -0
  20. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e8m0fnu-inl.h +112 -0
  21. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e8m0fnu.h +120 -0
  22. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_fnuz_cvt.h +64 -0
  23. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/FunctionRef.h +73 -0
  24. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Gauge.h +49 -0
  25. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Half-inl.h +350 -0
  26. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Half.h +424 -0
  27. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/IdWrapper.h +77 -0
  28. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/IntrusiveList.h +206 -0
  29. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Lazy.h +120 -0
  30. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/LeftRight.h +229 -0
  31. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Load.h +38 -0
  32. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Logging.h +372 -0
  33. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/MathConstants.h +142 -0
  34. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/MaybeOwned.h +237 -0
  35. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Metaprogramming.h +224 -0
  36. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/NetworkFlow.h +54 -0
  37. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Optional.h +60 -0
  38. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/OptionalArrayRef.h +237 -0
  39. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ParallelGuard.h +20 -0
  40. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Registry.h +329 -0
  41. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ScopeExit.h +50 -0
  42. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Semaphore.h +71 -0
  43. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/SmallBuffer.h +87 -0
  44. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/SmallVector.h +1467 -0
  45. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/StringUtil.h +262 -0
  46. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Synchronized.h +62 -0
  47. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ThreadLocal.h +156 -0
  48. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ThreadLocalDebugInfo.h +85 -0
  49. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Type.h +30 -0
  50. code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/TypeCast.h +210 -0
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DeadlockDetection.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Export.h>
4
+ #include <c10/util/Exception.h>
5
+
6
+ /// This file provides some simple utilities for detecting common deadlocks in
7
+ /// PyTorch. For now, we focus exclusively on detecting Python GIL deadlocks,
8
+ /// as the GIL is a wide ranging lock that is taken out in many situations.
9
+ /// The basic strategy is before performing an operation that may block, you
10
+ /// can use TORCH_ASSERT_NO_GIL_WITHOUT_PYTHON_DEP() to assert that the GIL is
11
+ /// not held. This macro is to be used in contexts where no static dependency
12
+ /// on Python is available (we will handle indirecting a virtual call for you).
13
+ ///
14
+ /// If the GIL is held by a torchdeploy interpreter, we always report false.
15
+ /// If you are in a context where Python bindings are available, it's better
16
+ /// to directly assert on PyGILState_Check (as it avoids a vcall and also
17
+ /// works correctly with torchdeploy.)
18
+
19
+ #define TORCH_ASSERT_NO_GIL_WITHOUT_PYTHON_DEP() \
20
+ TORCH_INTERNAL_ASSERT( \
21
+ !c10::impl::check_python_gil(), \
22
+ "Holding GIL before a blocking operation! Please release the GIL before blocking, or see https://github.com/pytorch/pytorch/issues/56297 for how to release the GIL for destructors of objects")
23
+
24
+ namespace c10::impl {
25
+
26
+ C10_API bool check_python_gil();
27
+
28
+ struct C10_API PythonGILHooks {
29
+ virtual ~PythonGILHooks() = default;
30
+ // Returns true if we hold the GIL. If not linked against Python we
31
+ // always return false.
32
+ virtual bool check_python_gil() const = 0;
33
+ };
34
+
35
+ C10_API void SetPythonGILHooks(PythonGILHooks* factory);
36
+
37
+ // DO NOT call this registerer from a torch deploy instance! You will clobber
38
+ // other registrations
39
+ struct C10_API PythonGILHooksRegisterer {
40
+ explicit PythonGILHooksRegisterer(PythonGILHooks* factory) {
41
+ SetPythonGILHooks(factory);
42
+ }
43
+ PythonGILHooksRegisterer(const PythonGILHooksRegisterer&) = delete;
44
+ PythonGILHooksRegisterer(PythonGILHooksRegisterer&&) = delete;
45
+ PythonGILHooksRegisterer& operator=(const PythonGILHooksRegisterer&) = delete;
46
+ PythonGILHooksRegisterer& operator=(PythonGILHooksRegisterer&&) = delete;
47
+ ~PythonGILHooksRegisterer() {
48
+ SetPythonGILHooks(nullptr);
49
+ }
50
+ };
51
+
52
+ } // namespace c10::impl
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Deprecated.h ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /**
4
+ * This file provides portable macros for marking declarations
5
+ * as deprecated. You should generally use C10_DEPRECATED,
6
+ * except when marking 'using' declarations as deprecated,
7
+ * in which case you should use C10_DEFINE_DEPRECATED_USING
8
+ * (due to portability concerns).
9
+ */
10
+
11
+ // Sample usage:
12
+ //
13
+ // C10_DEPRECATED void bad_func();
14
+ // struct C10_DEPRECATED BadStruct {
15
+ // ...
16
+ // };
17
+
18
+ // NB: __cplusplus doesn't work for MSVC, so for now MSVC always uses
19
+ // the "__declspec(deprecated)" implementation and not the C++14
20
+ // "[[deprecated]]" attribute. We tried enabling "[[deprecated]]" for C++14 on
21
+ // MSVC, but ran into issues with some older MSVC versions.
22
+ #if (defined(__cplusplus) && __cplusplus >= 201402L)
23
+ #define C10_DEPRECATED [[deprecated]]
24
+ #define C10_DEPRECATED_MESSAGE(message) [[deprecated(message)]]
25
+ #elif defined(__GNUC__)
26
+ #define C10_DEPRECATED __attribute__((deprecated))
27
+ // TODO Is there some way to implement this?
28
+ #define C10_DEPRECATED_MESSAGE(message) __attribute__((deprecated))
29
+
30
+ #elif defined(_MSC_VER)
31
+ #define C10_DEPRECATED __declspec(deprecated)
32
+ #define C10_DEPRECATED_MESSAGE(message) __declspec(deprecated(message))
33
+ #else
34
+ #warning "You need to implement C10_DEPRECATED for this compiler"
35
+ #define C10_DEPRECATED
36
+ #endif
37
+
38
+ // Sample usage:
39
+ //
40
+ // C10_DEFINE_DEPRECATED_USING(BadType, int)
41
+ //
42
+ // which is the portable version of
43
+ //
44
+ // using BadType [[deprecated]] = int;
45
+
46
+ // technically [[deprecated]] syntax is from c++14 standard, but it works in
47
+ // many compilers.
48
+ #if defined(__has_cpp_attribute)
49
+ #if __has_cpp_attribute(deprecated) && !defined(__CUDACC__)
50
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
51
+ using TypeName [[deprecated]] = TypeThingy;
52
+ #endif
53
+ #endif
54
+
55
+ #if defined(_MSC_VER)
56
+ #if defined(__CUDACC__)
57
+ // neither [[deprecated]] nor __declspec(deprecated) work on nvcc on Windows;
58
+ // you get the error:
59
+ //
60
+ // error: attribute does not apply to any entity
61
+ //
62
+ // So we just turn the macro off in this case.
63
+ #if defined(C10_DEFINE_DEPRECATED_USING)
64
+ #undef C10_DEFINE_DEPRECATED_USING
65
+ #endif
66
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
67
+ using TypeName = TypeThingy;
68
+ #else
69
+ // [[deprecated]] does work in windows without nvcc, though msc doesn't support
70
+ // `__has_cpp_attribute` when c++14 is supported, otherwise
71
+ // __declspec(deprecated) is used as the alternative.
72
+ #ifndef C10_DEFINE_DEPRECATED_USING
73
+ #if defined(_MSVC_LANG) && _MSVC_LANG >= 201402L
74
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
75
+ using TypeName [[deprecated]] = TypeThingy;
76
+ #else
77
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
78
+ using TypeName = __declspec(deprecated) TypeThingy;
79
+ #endif
80
+ #endif
81
+ #endif
82
+ #endif
83
+
84
+ #if !defined(C10_DEFINE_DEPRECATED_USING) && defined(__GNUC__)
85
+ // nvcc has a bug where it doesn't understand __attribute__((deprecated))
86
+ // declarations even when the host compiler supports it. We'll only use this gcc
87
+ // attribute when not cuda, and when using a GCC compiler that doesn't support
88
+ // the c++14 syntax we checked for above (available in __GNUC__ >= 5)
89
+ #if !defined(__CUDACC__)
90
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
91
+ using TypeName __attribute__((deprecated)) = TypeThingy;
92
+ #else
93
+ // using cuda + gcc < 5, neither deprecated syntax is available so turning off.
94
+ #define C10_DEFINE_DEPRECATED_USING(TypeName, TypeThingy) \
95
+ using TypeName = TypeThingy;
96
+ #endif
97
+ #endif
98
+
99
+ #if !defined(C10_DEFINE_DEPRECATED_USING)
100
+ #warning "You need to implement C10_DEFINE_DEPRECATED_USING for this compiler"
101
+ #define C10_DEFINE_DEPRECATED_USING
102
+ #endif
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DimVector.h ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SymInt.h>
4
+ #include <c10/core/impl/SizesAndStrides.h>
5
+ #include <c10/util/SmallVector.h>
6
+ #include <cstddef>
7
+ #include <cstdint>
8
+
9
+ namespace c10 {
10
+
11
+ constexpr size_t kDimVectorStaticSize = C10_SIZES_AND_STRIDES_MAX_INLINE_SIZE;
12
+
13
+ /// A container for sizes or strides
14
+ using DimVector = SmallVector<int64_t, kDimVectorStaticSize>;
15
+ using SymDimVector = SmallVector<c10::SymInt, kDimVectorStaticSize>;
16
+
17
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/DynamicCounter.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <functional>
4
+ #include <memory>
5
+ #include <string_view>
6
+
7
+ #include <c10/macros/Macros.h>
8
+
9
+ namespace c10::monitor {
10
+
11
+ class C10_API DynamicCounter {
12
+ public:
13
+ using Callback = std::function<int64_t()>;
14
+
15
+ // Creates a dynamic counter that can be queried at any point in time by
16
+ // multiple backends. Only one counter with a given key can exist at any point
17
+ // in time.
18
+ //
19
+ // The callback is invoked every time the counter is queried.
20
+ // The callback must be thread-safe.
21
+ // The callback must not throw.
22
+ // The callback must not block.
23
+ DynamicCounter(std::string_view key, Callback getCounterCallback);
24
+
25
+ // Unregisters the callback.
26
+ // Waits for all ongoing callback invocations to finish.
27
+ ~DynamicCounter();
28
+
29
+ private:
30
+ struct Guard;
31
+ std::unique_ptr<Guard> guard_;
32
+ };
33
+
34
+ namespace detail {
35
+ class DynamicCounterBackendIf {
36
+ public:
37
+ virtual ~DynamicCounterBackendIf() = default;
38
+
39
+ virtual void registerCounter(
40
+ std::string_view key,
41
+ DynamicCounter::Callback getCounterCallback) = 0;
42
+ // MUST wait for all ongoing callback invocations to finish
43
+ virtual void unregisterCounter(std::string_view key) = 0;
44
+ };
45
+
46
+ void C10_API
47
+ registerDynamicCounterBackend(std::unique_ptr<DynamicCounterBackendIf>);
48
+ } // namespace detail
49
+ } // namespace c10::monitor
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Enumerate.h ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Ported from folly/container/Enumerate.h
3
+ */
4
+
5
+ #pragma once
6
+
7
+ #include <iterator>
8
+ #include <memory>
9
+
10
+ #ifdef _WIN32
11
+ #include <basetsd.h> // @manual
12
+ using ssize_t = SSIZE_T;
13
+ #endif
14
+
15
+ #include <c10/macros/Macros.h>
16
+
17
+ /**
18
+ * Similar to Python's enumerate(), enumerate() can be used to
19
+ * iterate a range with a for-range loop, and it also allows to
20
+ * retrieve the count of iterations so far. Can be used in constexpr
21
+ * context.
22
+ *
23
+ * For example:
24
+ *
25
+ * for (auto&& [index, element] : enumerate(vec)) {
26
+ * // index is a const reference to a size_t containing the iteration count.
27
+ * // element is a reference to the type contained within vec, mutable
28
+ * // unless vec is const.
29
+ * }
30
+ *
31
+ * If the binding is const, the element reference is too.
32
+ *
33
+ * for (const auto&& [index, element] : enumerate(vec)) {
34
+ * // element is always a const reference.
35
+ * }
36
+ *
37
+ * It can also be used as follows:
38
+ *
39
+ * for (auto&& it : enumerate(vec)) {
40
+ * // *it is a reference to the current element. Mutable unless vec is const.
41
+ * // it->member can be used as well.
42
+ * // it.index contains the iteration count.
43
+ * }
44
+ *
45
+ * As before, const auto&& it can also be used.
46
+ */
47
+
48
+ namespace c10 {
49
+
50
+ namespace detail {
51
+
52
+ template <class T>
53
+ struct MakeConst {
54
+ using type = const T;
55
+ };
56
+ template <class T>
57
+ struct MakeConst<T&> {
58
+ using type = const T&;
59
+ };
60
+ template <class T>
61
+ struct MakeConst<T*> {
62
+ using type = const T*;
63
+ };
64
+
65
+ template <class Iterator>
66
+ class Enumerator {
67
+ public:
68
+ constexpr explicit Enumerator(Iterator it) : it_(std::move(it)) {}
69
+
70
+ class Proxy {
71
+ public:
72
+ using difference_type = ssize_t;
73
+ using value_type = typename std::iterator_traits<Iterator>::value_type;
74
+ using reference = typename std::iterator_traits<Iterator>::reference;
75
+ using pointer = typename std::iterator_traits<Iterator>::pointer;
76
+ using iterator_category = std::input_iterator_tag;
77
+
78
+ C10_ALWAYS_INLINE constexpr explicit Proxy(const Enumerator& e)
79
+ : index(e.idx_), element(*e.it_) {}
80
+
81
+ // Non-const Proxy: Forward constness from Iterator.
82
+ C10_ALWAYS_INLINE constexpr reference operator*() {
83
+ return element;
84
+ }
85
+ C10_ALWAYS_INLINE constexpr pointer operator->() {
86
+ return std::addressof(element);
87
+ }
88
+
89
+ // Const Proxy: Force const references.
90
+ C10_ALWAYS_INLINE constexpr typename MakeConst<reference>::type operator*()
91
+ const {
92
+ return element;
93
+ }
94
+ C10_ALWAYS_INLINE constexpr typename MakeConst<pointer>::type operator->()
95
+ const {
96
+ return std::addressof(element);
97
+ }
98
+
99
+ public:
100
+ size_t index;
101
+ reference element;
102
+ };
103
+
104
+ C10_ALWAYS_INLINE constexpr Proxy operator*() const {
105
+ return Proxy(*this);
106
+ }
107
+
108
+ C10_ALWAYS_INLINE constexpr Enumerator& operator++() {
109
+ ++it_;
110
+ ++idx_;
111
+ return *this;
112
+ }
113
+
114
+ template <typename OtherIterator>
115
+ C10_ALWAYS_INLINE constexpr bool operator==(
116
+ const Enumerator<OtherIterator>& rhs) const {
117
+ return it_ == rhs.it_;
118
+ }
119
+
120
+ template <typename OtherIterator>
121
+ C10_ALWAYS_INLINE constexpr bool operator!=(
122
+ const Enumerator<OtherIterator>& rhs) const {
123
+ return !(it_ == rhs.it_);
124
+ }
125
+
126
+ private:
127
+ template <typename OtherIterator>
128
+ friend class Enumerator;
129
+
130
+ Iterator it_;
131
+ size_t idx_ = 0;
132
+ };
133
+
134
+ template <class Range>
135
+ class RangeEnumerator {
136
+ Range r_;
137
+ using BeginIteratorType = decltype(std::declval<Range>().begin());
138
+ using EndIteratorType = decltype(std::declval<Range>().end());
139
+
140
+ public:
141
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
142
+ constexpr explicit RangeEnumerator(Range&& r) : r_(std::forward<Range>(r)) {}
143
+
144
+ constexpr Enumerator<BeginIteratorType> begin() {
145
+ return Enumerator<BeginIteratorType>(r_.begin());
146
+ }
147
+ constexpr Enumerator<EndIteratorType> end() {
148
+ return Enumerator<EndIteratorType>(r_.end());
149
+ }
150
+ };
151
+
152
+ } // namespace detail
153
+
154
+ template <class Range>
155
+ constexpr detail::RangeEnumerator<Range> enumerate(Range&& r) {
156
+ return detail::RangeEnumerator<Range>(std::forward<Range>(r));
157
+ }
158
+
159
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Exception.h ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_EXCEPTION_H_
2
+ #define C10_UTIL_EXCEPTION_H_
3
+
4
+ #include <c10/macros/Export.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Backtrace.h>
7
+ #include <c10/util/Lazy.h>
8
+ #include <c10/util/StringUtil.h>
9
+
10
+ #include <cstdint>
11
+ #include <exception>
12
+ #include <memory>
13
+ #include <string>
14
+ #include <variant>
15
+ #include <vector>
16
+
17
+ #if defined(_MSC_VER) && _MSC_VER <= 1900
18
+ #define __func__ __FUNCTION__
19
+ #endif
20
+
21
+ namespace c10 {
22
+
23
+ /// The primary ATen error class.
24
+ /// Provides a complete error message with source location information via
25
+ /// `what()`, and a more concise message via `what_without_backtrace()`.
26
+ /// Don't throw this directly; use TORCH_CHECK/TORCH_INTERNAL_ASSERT instead.
27
+ ///
28
+ /// NB: c10::Error is handled specially by the default torch to suppress the
29
+ /// backtrace, see torch/csrc/Exceptions.h
30
+ class C10_API Error : public std::exception {
31
+ private:
32
+ // The actual error message.
33
+ std::string msg_;
34
+
35
+ // Context for the message (in order of decreasing specificity). Context will
36
+ // be automatically formatted appropriately, so it is not necessary to add
37
+ // extra leading/trailing newlines to strings inside this vector
38
+ std::vector<std::string> context_;
39
+
40
+ // The C++ backtrace at the point when this exception was raised. This
41
+ // may be empty if there is no valid backtrace. (We don't use optional
42
+ // here to reduce the dependencies this file has.)
43
+ Backtrace backtrace_;
44
+
45
+ // These two are derived fields from msg_stack_ and backtrace_, but we need
46
+ // fields for the strings so that we can return a const char* (as the
47
+ // signature of std::exception requires). Currently, the invariant
48
+ // is that these fields are ALWAYS populated consistently with respect
49
+ // to msg_stack_ and backtrace_.
50
+ mutable OptimisticLazy<std::string> what_;
51
+ std::string what_without_backtrace_;
52
+
53
+ // This is a little debugging trick: you can stash a relevant pointer
54
+ // in caller, and then when you catch the exception, you can compare
55
+ // against pointers you have on hand to get more information about
56
+ // where the exception came from. In Caffe2, this is used to figure
57
+ // out which operator raised an exception.
58
+ const void* caller_;
59
+
60
+ public:
61
+ // PyTorch-style Error constructor. NB: the implementation of this
62
+ // is actually in Logging.cpp
63
+ Error(SourceLocation source_location, std::string msg);
64
+
65
+ // Caffe2-style error message
66
+ Error(
67
+ const char* file,
68
+ const uint32_t line,
69
+ const char* condition,
70
+ const std::string& msg,
71
+ Backtrace backtrace,
72
+ const void* caller = nullptr);
73
+
74
+ // Base constructor
75
+ Error(
76
+ std::string msg,
77
+ Backtrace backtrace = nullptr,
78
+ const void* caller = nullptr);
79
+
80
+ // Add some new context to the message stack. The last added context
81
+ // will be formatted at the end of the context list upon printing.
82
+ // WARNING: This method is O(n) in the size of the stack, so don't go
83
+ // wild adding a ridiculous amount of context to error messages.
84
+ void add_context(std::string msg);
85
+
86
+ const std::string& msg() const {
87
+ return msg_;
88
+ }
89
+
90
+ const std::vector<std::string>& context() const {
91
+ return context_;
92
+ }
93
+
94
+ const Backtrace& backtrace() const;
95
+
96
+ /// Returns the complete error message, including the source location.
97
+ /// The returned pointer is invalidated if you call add_context() on
98
+ /// this object.
99
+ const char* what() const noexcept override;
100
+
101
+ const void* caller() const noexcept {
102
+ return caller_;
103
+ }
104
+
105
+ /// Returns only the error message string, without source location.
106
+ /// The returned pointer is invalidated if you call add_context() on
107
+ /// this object.
108
+ virtual const char* what_without_backtrace() const noexcept {
109
+ return what_without_backtrace_.c_str();
110
+ }
111
+
112
+ private:
113
+ void refresh_what();
114
+ std::string compute_what(bool include_backtrace) const;
115
+ };
116
+
117
+ class C10_API Warning {
118
+ public:
119
+ class C10_API UserWarning{};
120
+ class C10_API DeprecationWarning{};
121
+
122
+ using warning_variant_t = std::variant<UserWarning, DeprecationWarning>;
123
+
124
+ Warning(
125
+ warning_variant_t type,
126
+ const SourceLocation& source_location,
127
+ std::string msg,
128
+ bool verbatim);
129
+
130
+ Warning(
131
+ warning_variant_t type,
132
+ SourceLocation source_location,
133
+ const char* msg,
134
+ bool verbatim);
135
+
136
+ Warning(
137
+ warning_variant_t type,
138
+ SourceLocation source_location,
139
+ ::c10::detail::CompileTimeEmptyString msg,
140
+ bool verbatim);
141
+
142
+ // Getters for members
143
+ warning_variant_t type() const;
144
+ const SourceLocation& source_location() const;
145
+ const std::string& msg() const;
146
+ bool verbatim() const;
147
+
148
+ private:
149
+ // The type of warning
150
+ warning_variant_t type_;
151
+
152
+ // Where the warning happened.
153
+ SourceLocation source_location_;
154
+
155
+ // The actual warning message.
156
+ std::string msg_;
157
+
158
+ // See note: [Verbatim Warnings]
159
+ bool verbatim_;
160
+ };
161
+
162
+ using UserWarning = Warning::UserWarning;
163
+ using DeprecationWarning = Warning::DeprecationWarning;
164
+
165
+ // Issue a warning with a given message. Dispatched to the current
166
+ // warning handler.
167
+ void C10_API warn(const Warning& warning);
168
+
169
+ class C10_API WarningHandler {
170
+ public:
171
+ virtual ~WarningHandler() = default;
172
+ /// The default warning handler. Prints the message to stderr.
173
+ virtual void process(const Warning& warning);
174
+ };
175
+
176
+ namespace WarningUtils {
177
+
178
+ // Note: [Verbatim Warnings]
179
+ // Warnings originating in C++ code can appear out-of-place to Python users:
180
+ // a user runs a line in Python, but the warning references a line in C++.
181
+ // Some parts of PyTorch, like the JIT, are cognizant of this mismatch
182
+ // and take care to map warnings back to the user's program, but most
183
+ // of PyTorch simply throws a context-free warning. To allow warning
184
+ // handlers to add context where appropriate, warn takes the
185
+ // "verbatim" flag. When this is false a warning handler might append
186
+ // the C++ warning to a Python warning message that relates the warning
187
+ // back to the user's program. Callers who have already accounted for
188
+ // context in their warnings should set verbatim to true so their warnings
189
+ // appear without modification.
190
+
191
+ /// Sets the global warning handler. This is not thread-safe, so it should
192
+ /// generally be called once during initialization or while holding the GIL
193
+ /// for programs that use python.
194
+ /// User is responsible for keeping the WarningHandler alive until
195
+ /// it is not needed.
196
+ C10_API void set_warning_handler(WarningHandler* handler) noexcept(true);
197
+ /// Gets the global warning handler.
198
+ C10_API WarningHandler* get_warning_handler() noexcept(true);
199
+
200
+ class C10_API WarningHandlerGuard {
201
+ WarningHandler* prev_handler_;
202
+
203
+ public:
204
+ WarningHandlerGuard(WarningHandler* new_handler)
205
+ : prev_handler_(c10::WarningUtils::get_warning_handler()) {
206
+ c10::WarningUtils::set_warning_handler(new_handler);
207
+ }
208
+ WarningHandlerGuard(WarningHandlerGuard&& other) = delete;
209
+ WarningHandlerGuard(const WarningHandlerGuard&) = delete;
210
+ WarningHandlerGuard& operator=(const WarningHandlerGuard&) = delete;
211
+ WarningHandlerGuard& operator=(WarningHandlerGuard&&) = delete;
212
+ ~WarningHandlerGuard() {
213
+ c10::WarningUtils::set_warning_handler(prev_handler_);
214
+ }
215
+ };
216
+
217
+ /// The TORCH_WARN_ONCE macro is difficult to test for. Use
218
+ /// setWarnAlways(true) to turn it into TORCH_WARN, which can be
219
+ /// tested for more easily.
220
+ C10_API void set_warnAlways(bool) noexcept(true);
221
+ C10_API bool get_warnAlways() noexcept(true);
222
+
223
+ // A RAII guard that sets warn_always (not thread-local) on
224
+ // construction, and sets it back to the original value upon destruction.
225
+ struct C10_API WarnAlways {
226
+ public:
227
+ explicit WarnAlways(bool setting = true);
228
+ ~WarnAlways();
229
+
230
+ private:
231
+ bool prev_setting;
232
+ };
233
+
234
+ } // namespace WarningUtils
235
+
236
+ // Like Error, but we always report the C++ backtrace, instead of only
237
+ // reporting when TORCH_SHOW_CPP_STACKTRACES
238
+ class C10_API ErrorAlwaysShowCppStacktrace : public Error {
239
+ using Error::Error;
240
+ const char* what_without_backtrace() const noexcept override {
241
+ return what();
242
+ }
243
+ };
244
+
245
+ // Used in ATen for out-of-bound indices that can reasonably only be detected
246
+ // lazily inside a kernel (See: advanced indexing). These turn into
247
+ // IndexError when they cross to Python.
248
+ class C10_API IndexError : public Error {
249
+ using Error::Error;
250
+ };
251
+
252
+ // Used in ATen for invalid values. These turn into
253
+ // ValueError when they cross to Python.
254
+ class C10_API ValueError : public Error {
255
+ using Error::Error;
256
+ };
257
+
258
+ // Used in ATen for invalid types. These turn into
259
+ // TypeError when they cross to Python.
260
+ class C10_API TypeError : public Error {
261
+ using Error::Error;
262
+ };
263
+
264
+ // Used in ATen for functionality that is not implemented. These turn into
265
+ // NotImplementedError when they cross to Python.
266
+ class C10_API NotImplementedError : public Error {
267
+ using Error::Error;
268
+ };
269
+
270
+ // Used in ATen for non finite indices. These turn into
271
+ // ExitException when they cross to Python.
272
+ class C10_API EnforceFiniteError : public Error {
273
+ using Error::Error;
274
+ };
275
+
276
+ // Used in Onnxifi backend lowering. These turn into
277
+ // ExitException when they cross to Python.
278
+ class C10_API OnnxfiBackendSystemError : public Error {
279
+ using Error::Error;
280
+ };
281
+
282
+ // Used for numerical errors from the linalg module. These
283
+ // turn into LinAlgError when they cross into Python.
284
+ class C10_API LinAlgError : public Error {
285
+ using Error::Error;
286
+ };
287
+
288
+ class C10_API OutOfMemoryError : public Error {
289
+ using Error::Error;
290
+ };
291
+
292
+ // Used for handling syntactic errors in input arguments.
293
+ // These turn into SyntaxError when the cross into Python.
294
+ class C10_API SyntaxError : public Error {
295
+ using Error::Error;
296
+ };
297
+
298
+ // Raised when accelerator API call hits an error.
299
+ // These turn into AcceleratorError when the cross into Python
300
+ class C10_API AcceleratorError : public Error {
301
+ int32_t error_code;
302
+
303
+ public:
304
+ AcceleratorError(SourceLocation loc, int32_t code, const std::string& msg)
305
+ : Error(loc, msg), error_code(code) {}
306
+ int32_t get_error_code() const {
307
+ return error_code;
308
+ }
309
+ };
310
+
311
+ // Base error type for all distributed errors.
312
+ // These turn into DistError when they cross into Python.
313
+ class C10_API DistError : public Error {
314
+ using Error::Error;
315
+ };
316
+
317
+ // Used for collective communication library errors from the distributed module.
318
+ // These turn into DistBackendError when they cross into Python.
319
+ class C10_API DistBackendError : public DistError {
320
+ using DistError::DistError;
321
+ };
322
+
323
+ // Used for errors originating from the store.
324
+ // These turn into DistStoreError when they cross into Python.
325
+ class C10_API DistStoreError : public DistError {
326
+ using DistError::DistError;
327
+ };
328
+
329
+ // Used for errors originating from the TCP/IP stack and not from collective
330
+ // libraries. These turn into DistNetworkError when they cross into Python.
331
+ class C10_API DistNetworkError : public DistError {
332
+ using DistError::DistError;
333
+ };
334
+
335
+ // Raised when a queue is empty and a non-blocking pop is called.
336
+ // Translated to torch.distributed.QueueEmptyError in Python
337
+ class C10_API DistQueueEmptyError : public DistStoreError {
338
+ using DistStoreError::DistStoreError;
339
+ };
340
+
341
+ // A utility function to return an exception std::string by prepending its
342
+ // exception type before its what() content
343
+ C10_API std::string GetExceptionString(const std::exception& e);
344
+
345
+ } // namespace c10
346
+
347
+ // Private helper macro for implementing TORCH_INTERNAL_ASSERT and TORCH_CHECK
348
+ //
349
+ // Note: In the debug build With MSVC, __LINE__ might be of long type (a.k.a
350
+ // int32_t), which is different from the definition of `SourceLocation` that
351
+ // requires unsigned int (a.k.a uint32_t) and may cause a compile error with the
352
+ // message: error C2397: conversion from 'long' to 'uint32_t' requires a
353
+ // narrowing conversion Here the static cast is used to pass the build. if this
354
+ // is used inside a lambda the __func__ macro expands to operator(), which isn't
355
+ // very useful, but hard to fix in a macro so suppressing the warning.
356
+ #define C10_THROW_ERROR(err_type, msg) \
357
+ throw ::c10::err_type( \
358
+ {__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, msg)
359
+
360
+ #define C10_BUILD_ERROR(err_type, msg) \
361
+ ::c10::err_type({__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, msg)
362
+
363
+ // Private helper macro for workaround MSVC misexpansion of nested macro
364
+ // invocations involving __VA_ARGS__. See
365
+ // https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
366
+ #define C10_EXPAND_MSVC_WORKAROUND(x) x
367
+
368
+ // On nvcc, C10_UNLIKELY thwarts missing return statement analysis. In cases
369
+ // where the unlikely expression may be a constant, use this macro to ensure
370
+ // return statement analysis keeps working (at the cost of not getting the
371
+ // likely/unlikely annotation on nvcc).
372
+ // https://github.com/pytorch/pytorch/issues/21418
373
+ //
374
+ // Currently, this is only used in the error reporting macros below. If you
375
+ // want to use it more generally, move me to Macros.h
376
+ //
377
+ // TODO: Brian Vaughan observed that we might be able to get this to work on
378
+ // nvcc by writing some sort of C++ overload that distinguishes constexpr inputs
379
+ // from non-constexpr. Since there isn't any evidence that losing C10_UNLIKELY
380
+ // in nvcc is causing us perf problems, this is not yet implemented, but this
381
+ // might be an interesting piece of C++ code for an intrepid bootcamper to
382
+ // write.
383
+ #if defined(__CUDACC__)
384
+ #define C10_UNLIKELY_OR_CONST(e) e
385
+ #else
386
+ #define C10_UNLIKELY_OR_CONST(e) C10_UNLIKELY(e)
387
+ #endif
388
+
389
+ // ----------------------------------------------------------------------------
390
+ // Error reporting macros
391
+ // ----------------------------------------------------------------------------
392
+
393
+ #ifdef STRIP_ERROR_MESSAGES
394
+ #define TORCH_RETHROW(e, ...) throw
395
+ #else
396
+ #define TORCH_RETHROW(e, ...) \
397
+ do { \
398
+ e.add_context(::c10::str(__VA_ARGS__)); \
399
+ throw; \
400
+ } while (false)
401
+ #endif
402
+
403
+ // A utility macro to provide assert()-like functionality; that is, enforcement
404
+ // of internal invariants in code. It supports an arbitrary number of extra
405
+ // arguments (evaluated only on failure), which will be printed in the assert
406
+ // failure message using operator<< (this is useful to print some variables
407
+ // which may be useful for debugging.)
408
+ //
409
+ // Usage:
410
+ // TORCH_INTERNAL_ASSERT(should_be_true);
411
+ // TORCH_INTERNAL_ASSERT(x == 0, "x = ", x);
412
+ //
413
+ // Assuming no bugs in PyTorch, the conditions tested by this macro should
414
+ // always be true; e.g., it should be possible to disable all of these
415
+ // conditions without changing observable user behavior. If you would like to
416
+ // do error reporting for user input, please use TORCH_CHECK instead.
417
+ //
418
+ // NOTE: It is SAFE to use this macro in production code; on failure, this
419
+ // simply raises an exception, it does NOT unceremoniously quit the process
420
+ // (unlike assert()).
421
+ //
422
+ #ifdef STRIP_ERROR_MESSAGES
423
+ #define TORCH_INTERNAL_ASSERT(cond, ...) \
424
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
425
+ ::c10::detail::torchCheckFail( \
426
+ __func__, \
427
+ __FILE__, \
428
+ static_cast<uint32_t>(__LINE__), \
429
+ #cond " INTERNAL ASSERT FAILED at " C10_STRINGIZE(__FILE__)); \
430
+ }
431
+ #else
432
+ // It would be nice if we could build a combined string literal out of
433
+ // the TORCH_INTERNAL_ASSERT prefix and a user-provided string literal
434
+ // as the first argument, but there doesn't seem to be any good way to
435
+ // do that while still supporting having a first argument that isn't a
436
+ // string literal.
437
+ #define TORCH_INTERNAL_ASSERT(cond, ...) \
438
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
439
+ ::c10::detail::torchInternalAssertFail( \
440
+ __func__, \
441
+ __FILE__, \
442
+ static_cast<uint32_t>(__LINE__), \
443
+ #cond \
444
+ " INTERNAL ASSERT FAILED at " C10_STRINGIZE(__FILE__) ":" C10_STRINGIZE( \
445
+ __LINE__) ", please report a bug to PyTorch. ", \
446
+ c10::str(__VA_ARGS__)); \
447
+ }
448
+ #endif
449
+
450
+ // A utility macro to make it easier to test for error conditions from user
451
+ // input. Like TORCH_INTERNAL_ASSERT, it supports an arbitrary number of extra
452
+ // arguments (evaluated only on failure), which will be printed in the error
453
+ // message using operator<< (e.g., you can pass any object which has
454
+ // operator<< defined. Most objects in PyTorch have these definitions!)
455
+ //
456
+ // Usage:
457
+ // TORCH_CHECK(should_be_true); // A default error message will be provided
458
+ // // in this case; but we recommend writing an
459
+ // // explicit error message, as it is more
460
+ // // user friendly.
461
+ // TORCH_CHECK(x == 0, "Expected x to be 0, but got ", x);
462
+ //
463
+ // On failure, this macro will raise an exception. If this exception propagates
464
+ // to Python, it will convert into a Python RuntimeError.
465
+ //
466
+ // NOTE: It is SAFE to use this macro in production code; on failure, this
467
+ // simply raises an exception, it does NOT unceremoniously quit the process
468
+ // (unlike CHECK() from glog.)
469
+ //
470
+ #define TORCH_CHECK_WITH(error_t, cond, ...) \
471
+ TORCH_CHECK_WITH_MSG(error_t, cond, "", __VA_ARGS__)
472
+
473
+ #ifdef STRIP_ERROR_MESSAGES
474
+ #define TORCH_CHECK_MSG(cond, type, ...) \
475
+ (#cond #type " CHECK FAILED at " C10_STRINGIZE(__FILE__))
476
+ #define TORCH_CHECK_WITH_MSG(error_t, cond, type, ...) \
477
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
478
+ C10_THROW_ERROR(Error, TORCH_CHECK_MSG(cond, type, __VA_ARGS__)); \
479
+ }
480
+ #else
481
+
482
+ namespace c10::detail {
483
+ template <typename... Args>
484
+ decltype(auto) torchCheckMsgImpl(const char* /*msg*/, const Args&... args) {
485
+ return ::c10::str(args...);
486
+ }
487
+ inline C10_API const char* torchCheckMsgImpl(const char* msg) {
488
+ return msg;
489
+ }
490
+ // If there is just 1 user-provided C-string argument, use it.
491
+ inline C10_API const char* torchCheckMsgImpl(
492
+ const char* /*msg*/,
493
+ const char* args) {
494
+ return args;
495
+ }
496
+ } // namespace c10::detail
497
+
498
+ #define TORCH_CHECK_MSG(cond, type, ...) \
499
+ (::c10::detail::torchCheckMsgImpl( \
500
+ "Expected " #cond \
501
+ " to be true, but got false. " \
502
+ "(Could this error message be improved? If so, " \
503
+ "please report an enhancement request to PyTorch.)", \
504
+ ##__VA_ARGS__))
505
+ #define TORCH_CHECK_WITH_MSG(error_t, cond, type, ...) \
506
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
507
+ C10_THROW_ERROR(error_t, TORCH_CHECK_MSG(cond, type, __VA_ARGS__)); \
508
+ }
509
+ #endif
510
+
511
+ namespace c10::detail {
512
+
513
+ [[noreturn]] C10_API void torchCheckFail(
514
+ const char* func,
515
+ const char* file,
516
+ uint32_t line,
517
+ const std::string& msg);
518
+ [[noreturn]] C10_API void torchCheckFail(
519
+ const char* func,
520
+ const char* file,
521
+ uint32_t line,
522
+ const char* msg);
523
+
524
+ // The c10::str() call that creates userMsg can have 1 of 3 return
525
+ // types depending on the number and types of arguments passed to
526
+ // TORCH_INTERNAL_ASSERT. 0 arguments will get a
527
+ // CompileTimeEmptyString, 1 const char * will be passed straight
528
+ // through, and anything else will get converted to std::string.
529
+ [[noreturn]] C10_API void torchInternalAssertFail(
530
+ const char* func,
531
+ const char* file,
532
+ uint32_t line,
533
+ const char* condMsg,
534
+ const char* userMsg);
535
+ [[noreturn]] inline C10_API void torchInternalAssertFail(
536
+ const char* func,
537
+ const char* file,
538
+ uint32_t line,
539
+ const char* condMsg,
540
+ ::c10::detail::CompileTimeEmptyString /*userMsg*/) {
541
+ torchCheckFail(func, file, line, condMsg);
542
+ }
543
+ [[noreturn]] C10_API void torchInternalAssertFail(
544
+ const char* func,
545
+ const char* file,
546
+ uint32_t line,
547
+ const char* condMsg,
548
+ const std::string& userMsg);
549
+
550
+ } // namespace c10::detail
551
+
552
+ #ifdef STANDALONE_TORCH_HEADER
553
+
554
+ // TORCH_CHECK throws std::runtime_error instead of c10::Error which is
555
+ // useful when certain headers are used in a libtorch-independent way,
556
+ // e.g. when Vectorized<T> is used in AOTInductor generated code.
557
+ #ifdef STRIP_ERROR_MESSAGES
558
+ #define TORCH_CHECK(cond, ...) \
559
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
560
+ throw std::runtime_error(TORCH_CHECK_MSG( \
561
+ cond, \
562
+ "", \
563
+ __func__, \
564
+ ", ", \
565
+ __FILE__, \
566
+ ":", \
567
+ __LINE__, \
568
+ ", ", \
569
+ __VA_ARGS__)); \
570
+ }
571
+ #else
572
+ #define TORCH_CHECK(cond, ...) \
573
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
574
+ throw std::runtime_error(TORCH_CHECK_MSG( \
575
+ cond, \
576
+ "", \
577
+ __func__, \
578
+ ", ", \
579
+ __FILE__, \
580
+ ":", \
581
+ __LINE__, \
582
+ ", ", \
583
+ ##__VA_ARGS__)); \
584
+ }
585
+ #endif
586
+
587
+ #else
588
+
589
+ #ifdef STRIP_ERROR_MESSAGES
590
+ #define TORCH_CHECK(cond, ...) \
591
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
592
+ ::c10::detail::torchCheckFail( \
593
+ __func__, \
594
+ __FILE__, \
595
+ static_cast<uint32_t>(__LINE__), \
596
+ TORCH_CHECK_MSG(cond, "", __VA_ARGS__)); \
597
+ }
598
+ #else
599
+ #define TORCH_CHECK(cond, ...) \
600
+ if (C10_UNLIKELY_OR_CONST(!(cond))) { \
601
+ ::c10::detail::torchCheckFail( \
602
+ __func__, \
603
+ __FILE__, \
604
+ static_cast<uint32_t>(__LINE__), \
605
+ TORCH_CHECK_MSG(cond, "", ##__VA_ARGS__)); \
606
+ }
607
+ #endif
608
+
609
+ #endif
610
+
611
+ // An utility macro that does what `TORCH_CHECK` does if compiled in the host
612
+ // code, otherwise does nothing. Supposed to be used in the code shared between
613
+ // host and device code as an alternative for `TORCH_CHECK`.
614
+ #if defined(__CUDACC__) || defined(__HIPCC__)
615
+ #define TORCH_CHECK_IF_NOT_ON_CUDA(cond, ...)
616
+ #else
617
+ #define TORCH_CHECK_IF_NOT_ON_CUDA(cond, ...) TORCH_CHECK(cond, ##__VA_ARGS__)
618
+ #endif
619
+
620
+ // Debug only version of TORCH_INTERNAL_ASSERT. This macro only checks in debug
621
+ // build, and does nothing in release build. It is appropriate to use
622
+ // in situations where you want to add an assert to a hotpath, but it is
623
+ // too expensive to run this assert on production builds.
624
+ #ifdef NDEBUG
625
+ // Optimized version - generates no code.
626
+ #define TORCH_INTERNAL_ASSERT_DEBUG_ONLY(...) \
627
+ while (false) \
628
+ C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__))
629
+ #else
630
+ #define TORCH_INTERNAL_ASSERT_DEBUG_ONLY(...) \
631
+ C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__))
632
+ #endif
633
+
634
+ // TODO: We're going to get a lot of similar looking string literals
635
+ // this way; check if this actually affects binary size.
636
+
637
+ // Like TORCH_CHECK, but raises LinAlgError instead of Error.
638
+ #define TORCH_CHECK_LINALG(cond, ...) \
639
+ TORCH_CHECK_WITH_MSG(LinAlgError, cond, "LINALG", __VA_ARGS__)
640
+
641
+ // Like TORCH_CHECK, but raises IndexErrors instead of Errors.
642
+ #define TORCH_CHECK_INDEX(cond, ...) \
643
+ TORCH_CHECK_WITH_MSG(IndexError, cond, "INDEX", __VA_ARGS__)
644
+
645
+ // Like TORCH_CHECK, but raises ValueErrors instead of Errors.
646
+ #define TORCH_CHECK_VALUE(cond, ...) \
647
+ TORCH_CHECK_WITH_MSG(ValueError, cond, "VALUE", __VA_ARGS__)
648
+
649
+ // Like TORCH_CHECK, but raises TypeErrors instead of Errors.
650
+ #define TORCH_CHECK_TYPE(cond, ...) \
651
+ TORCH_CHECK_WITH_MSG(TypeError, cond, "TYPE", __VA_ARGS__)
652
+
653
+ // Like TORCH_CHECK, but raises NotImplementedErrors instead of Errors.
654
+ #define TORCH_CHECK_NOT_IMPLEMENTED(cond, ...) \
655
+ TORCH_CHECK_WITH_MSG(NotImplementedError, cond, "TYPE", __VA_ARGS__)
656
+
657
+ #define TORCH_CHECK_ALWAYS_SHOW_CPP_STACKTRACE(cond, ...) \
658
+ TORCH_CHECK_WITH_MSG( \
659
+ ErrorAlwaysShowCppStacktrace, cond, "TYPE", ##__VA_ARGS__)
660
+
661
+ #ifdef STRIP_ERROR_MESSAGES
662
+ #define WARNING_MESSAGE_STRING(...) \
663
+ ::c10::detail::CompileTimeEmptyString {}
664
+ #else
665
+ #define WARNING_MESSAGE_STRING(...) ::c10::str(__VA_ARGS__)
666
+ #endif
667
+
668
+ // Report a warning to the user. Accepts an arbitrary number of extra
669
+ // arguments which are concatenated into the warning message using operator<<
670
+ //
671
+ #ifdef DISABLE_WARN
672
+ #define _TORCH_WARN_WITH(...) ((void)0);
673
+ #else
674
+ #define _TORCH_WARN_WITH(warning_t, ...) \
675
+ ::c10::warn(::c10::Warning( \
676
+ warning_t(), \
677
+ {__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, \
678
+ WARNING_MESSAGE_STRING(__VA_ARGS__), \
679
+ false));
680
+ #endif
681
+
682
+ #define TORCH_WARN(...) _TORCH_WARN_WITH(::c10::UserWarning, __VA_ARGS__);
683
+
684
+ #define TORCH_WARN_DEPRECATION(...) \
685
+ _TORCH_WARN_WITH(::c10::DeprecationWarning, __VA_ARGS__);
686
+
687
+ // Report a warning to the user only once. Accepts an arbitrary number of extra
688
+ // arguments which are concatenated into the warning message using operator<<
689
+ //
690
+ #define _TORCH_WARN_ONCE(...) \
691
+ [[maybe_unused]] static const auto C10_ANONYMOUS_VARIABLE( \
692
+ torch_warn_once_) = [&] { \
693
+ TORCH_WARN(__VA_ARGS__); \
694
+ return true; \
695
+ }()
696
+
697
+ #ifdef DISABLE_WARN
698
+ #define TORCH_WARN_ONCE(...) ((void)0);
699
+ #else
700
+ #define TORCH_WARN_ONCE(...) \
701
+ if (::c10::WarningUtils::get_warnAlways()) { \
702
+ TORCH_WARN(__VA_ARGS__); \
703
+ } else { \
704
+ _TORCH_WARN_ONCE(__VA_ARGS__); \
705
+ }
706
+ #endif
707
+
708
+ // Report an error with a specific argument
709
+ // NOTE: using the argument name in TORCH_CHECK's message is preferred
710
+ #define TORCH_CHECK_ARG(cond, argN, ...) \
711
+ TORCH_CHECK(cond, "invalid argument ", argN, ": ", __VA_ARGS__)
712
+
713
+ // ----------------------------------------------------------------------------
714
+ // Deprecated macros
715
+ // ----------------------------------------------------------------------------
716
+
717
+ namespace c10::detail {
718
+
719
+ /*
720
+ // Deprecation disabled until we fix sites in our codebase
721
+ [[deprecated("AT_ERROR(msg) is deprecated, use TORCH_CHECK(false, msg)
722
+ instead.")]]
723
+ */
724
+ inline void deprecated_AT_ERROR() {}
725
+
726
+ /*
727
+ // Deprecation disabled until we fix sites in our codebase
728
+ [[deprecated("AT_ASSERT is deprecated, if you mean to indicate an
729
+ internal invariant failure, use " \
730
+ "TORCH_INTERNAL_ASSERT instead; if you mean to do user
731
+ error checking, use " \ "TORCH_CHECK. See
732
+ https://github.com/pytorch/pytorch/issues/20287 for more details.")]]
733
+ */
734
+ inline void deprecated_AT_ASSERT() {}
735
+
736
+ /*
737
+ // Deprecation disabled until we fix sites in our codebase
738
+ [[deprecated("AT_ASSERTM is deprecated, if you mean to indicate an
739
+ internal invariant failure, use " \
740
+ "TORCH_INTERNAL_ASSERT instead; if you mean to do user
741
+ error checking, use " \ "TORCH_CHECK. See
742
+ https://github.com/pytorch/pytorch/issues/20287 for more details.")]]
743
+ */
744
+ inline void deprecated_AT_ASSERTM() {}
745
+
746
+ } // namespace c10::detail
747
+
748
+ // Deprecated alias; this alias was deprecated because people kept mistakenly
749
+ // using it for user error checking. Use TORCH_INTERNAL_ASSERT or TORCH_CHECK
750
+ // instead. See https://github.com/pytorch/pytorch/issues/20287 for more
751
+ // details.
752
+ #define AT_ASSERT(...) \
753
+ do { \
754
+ ::c10::detail::deprecated_AT_ASSERT(); \
755
+ C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(__VA_ARGS__)); \
756
+ } while (false)
757
+
758
+ // Deprecated alias, like AT_ASSERT. The new TORCH_INTERNAL_ASSERT macro
759
+ // supports both 0-ary and variadic calls, so having a separate
760
+ // message-accepting macro is not necessary.
761
+ //
762
+ // NB: we MUST include cond explicitly here, as MSVC will miscompile the macro
763
+ // expansion, shunting all of __VA_ARGS__ to cond. An alternate workaround
764
+ // can be seen at
765
+ // https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly
766
+ #define AT_ASSERTM(cond, ...) \
767
+ do { \
768
+ ::c10::detail::deprecated_AT_ASSERTM(); \
769
+ C10_EXPAND_MSVC_WORKAROUND(TORCH_INTERNAL_ASSERT(cond, __VA_ARGS__)); \
770
+ } while (false)
771
+
772
+ // Deprecated alias; this alias was deprecated because it represents extra API
773
+ // surface that makes it hard for people to understand what macro to use.
774
+ // Use TORCH_CHECK(false, ...) or TORCH_INTERNAL_ASSERT(false, ...) to
775
+ // unconditionally fail at a line of code.
776
+ #define AT_ERROR(...) \
777
+ do { \
778
+ ::c10::detail::deprecated_AT_ERROR(); \
779
+ C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
780
+ } while (false)
781
+
782
+ #endif // C10_UTIL_EXCEPTION_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ExclusivelyOwned.h ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <utility>
4
+
5
+ namespace c10 {
6
+
7
+ // See example implementation in TensorBase.h and TensorBody.h.
8
+ // Synopsis:
9
+ //
10
+ // repr_type -- type to use to store an owned T in ExclusivelyOwned.
11
+ //
12
+ // pointer_type -- pointer-esque type to return from
13
+ // ExclusivelyOwned's get() and operator*() methods.
14
+ //
15
+ // const_pointer_type -- similar to pointer_type, used for the const methods.
16
+ //
17
+ // static repr_type nullRepr() -- return a null instance of repr_type.
18
+ //
19
+ // template <class... Args>
20
+ // static repr_type createInPlace(Args&&... args) -- used by the in-place
21
+ // ExclusivelyOwned constructor.
22
+ //
23
+ // static repr_type moveToRepr(T&& x) -- move the given x into an
24
+ // instance of repr_type. used by the ExclusivelyOwned(T&&)
25
+ // constructor.
26
+ //
27
+ // static void destroyOwned(repr_type x) -- free memory for a
28
+ // known-exclusively-owned instance of x. Replaces calling repr_type's
29
+ // destructor. Being able to implement this more efficiently than
30
+ // repr_type's destructor is the main reason to use ExclusivelyOwned
31
+ // for a type.
32
+ //
33
+ // static T take(repr_type&) -- move out of the given repr_type into an owned T.
34
+ //
35
+ // static pointer_type getImpl(const repr_type&) -- return a pointer
36
+ // to the given repr_type. May take repr_type by value if that is more
37
+ // efficient.
38
+ template <typename T>
39
+ struct ExclusivelyOwnedTraits;
40
+
41
+ /// ExclusivelyOwned is a smart-pointer-like wrapper around an
42
+ /// exclusively-owned instance of some type T that normally has
43
+ /// mandatory reference counting (currently just Tensor). If you have
44
+ /// an isolated piece of code that knows that it has sole ownership of
45
+ /// an object of one of these types (i.e., because you created it
46
+ /// directly or using a factory function) and that object will not
47
+ /// escape from that isolated piece of code, then moving the object
48
+ /// into an ExclusivelyOwned will avoid an atomic reference count
49
+ /// decrement at destruction time.
50
+ ///
51
+ /// If you directly create the Tensor in the first
52
+ /// place, you can use the in_place constructor of ExclusivelyOwned to
53
+ /// additionally avoid doing any stores to initialize the refcount &
54
+ /// weakcount.
55
+ template <typename T>
56
+ class ExclusivelyOwned {
57
+ using EOT = ExclusivelyOwnedTraits<T>;
58
+ typename ExclusivelyOwnedTraits<T>::repr_type repr_;
59
+
60
+ public:
61
+ ExclusivelyOwned() : repr_(EOT::nullRepr()) {}
62
+
63
+ explicit ExclusivelyOwned(T&& t) : repr_(EOT::moveToRepr(std::move(t))) {}
64
+
65
+ template <class... Args>
66
+ explicit ExclusivelyOwned(std::in_place_t, Args&&... args)
67
+ : repr_(EOT::createInPlace(std::forward<Args>(args)...)) {}
68
+
69
+ ExclusivelyOwned(const ExclusivelyOwned&) = delete;
70
+
71
+ ExclusivelyOwned(ExclusivelyOwned&& rhs) noexcept
72
+ : repr_(std::move(rhs.repr_)) {
73
+ rhs.repr_ = EOT::nullRepr();
74
+ }
75
+
76
+ ExclusivelyOwned& operator=(const ExclusivelyOwned&) = delete;
77
+
78
+ ExclusivelyOwned& operator=(ExclusivelyOwned&& rhs) noexcept {
79
+ EOT::destroyOwned(repr_);
80
+ repr_ = std::move(rhs.repr_);
81
+ rhs.repr_ = EOT::nullRepr();
82
+ return *this;
83
+ }
84
+
85
+ ExclusivelyOwned& operator=(T&& rhs) noexcept {
86
+ EOT::destroyOwned(repr_);
87
+ repr_ = EOT::moveToRepr(std::move(rhs));
88
+ return *this;
89
+ }
90
+
91
+ ~ExclusivelyOwned() {
92
+ EOT::destroyOwned(repr_);
93
+ // Don't bother to call the destructor of repr_, since we already
94
+ // did specialized destruction for the exclusively-owned case in
95
+ // destroyOwned!
96
+ }
97
+
98
+ // We don't provide this because it would require us to be able to
99
+ // differentiate an owned-but-empty T from a lack of T. This is
100
+ // particularly problematic for Tensor, which wants to use an
101
+ // undefined Tensor as its null state.
102
+ explicit operator bool() const noexcept = delete;
103
+
104
+ operator T() && {
105
+ return take();
106
+ }
107
+
108
+ // NOTE: the equivalent operation on MaybeOwned is a moving
109
+ // operator*. For ExclusivelyOwned, take() and operator*() may well
110
+ // have different return types, so they are different functions.
111
+ T take() && {
112
+ return EOT::take(repr_);
113
+ }
114
+
115
+ typename EOT::const_pointer_type operator->() const {
116
+ return get();
117
+ }
118
+
119
+ typename EOT::const_pointer_type get() const {
120
+ return EOT::getImpl(repr_);
121
+ }
122
+
123
+ typename EOT::pointer_type operator->() {
124
+ return get();
125
+ }
126
+
127
+ typename EOT::pointer_type get() {
128
+ return EOT::getImpl(repr_);
129
+ }
130
+
131
+ std::remove_pointer_t<typename EOT::const_pointer_type>& operator*() const {
132
+ return *get();
133
+ }
134
+
135
+ std::remove_pointer_t<typename EOT::pointer_type>& operator*() {
136
+ return *get();
137
+ }
138
+ };
139
+
140
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ExclusivelyOwnedTensorTraits.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/TensorImpl.h>
4
+ #include <c10/core/UndefinedTensorImpl.h>
5
+
6
+ #include <utility>
7
+
8
+ namespace c10 {
9
+ // Shared ExclusivelyOwnedTraits implementation between caffe2::Tensor and
10
+ // at::TensorBase.
11
+ template <typename TensorType>
12
+ struct ExclusivelyOwnedTensorTraits {
13
+ using repr_type = TensorType;
14
+ using pointer_type = TensorType*;
15
+ using const_pointer_type = const TensorType*;
16
+
17
+ static repr_type nullRepr() {
18
+ return TensorType();
19
+ }
20
+
21
+ template <class... Args>
22
+ static repr_type createInPlace(Args&&... args) {
23
+ return TensorType(std::forward<Args>(args)...);
24
+ }
25
+
26
+ static repr_type moveToRepr(TensorType&& x) {
27
+ return std::move(x);
28
+ }
29
+
30
+ static void destroyOwned(TensorType& x) {
31
+ TensorImpl* const toDestroy = x.unsafeReleaseTensorImpl();
32
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
33
+ toDestroy != nullptr, "Tensor somehow got null TensorImpl?");
34
+ // May be 0 because UndefinedTensorImpl doesn't get its refcount
35
+ // incremented.
36
+ const bool isUndefined = toDestroy == UndefinedTensorImpl::singleton();
37
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
38
+ toDestroy->refcount_ == 1 || (toDestroy->refcount_ == 0 && isUndefined),
39
+ "ExclusivelyOwned<Tensor> destroyed with isUndefined ",
40
+ isUndefined,
41
+ " and refcount ",
42
+ toDestroy->refcount_,
43
+ ", expected 1 or, if isUndefined, 0!");
44
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
45
+ toDestroy->weakcount_ == 1 ||
46
+ (toDestroy->weakcount_ == 0 &&
47
+ toDestroy == UndefinedTensorImpl::singleton()),
48
+ "ExclusivelyOwned<Tensor> destroyed with isUndefined ",
49
+ isUndefined,
50
+ " and weakcount ",
51
+ toDestroy->weakcount_,
52
+ ", expected 1 or, if isUndefined, 0!");
53
+ if (!isUndefined) {
54
+ #ifndef NDEBUG
55
+ // Needed to pass the debug assertions in ~intrusive_ptr_target.
56
+ toDestroy->refcount_ = 0;
57
+ toDestroy->weakcount_ = 0;
58
+ #endif
59
+ delete toDestroy;
60
+ }
61
+ }
62
+
63
+ static TensorType take(TensorType& x) {
64
+ return std::move(x);
65
+ }
66
+
67
+ static pointer_type getImpl(repr_type& x) {
68
+ return &x;
69
+ }
70
+
71
+ static const_pointer_type getImpl(const repr_type& x) {
72
+ return &x;
73
+ }
74
+ };
75
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/FbcodeMaps.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_FBCODEMAPS_H_
2
+ #define C10_UTIL_FBCODEMAPS_H_
3
+
4
+ // Map typedefs so that we can use folly's F14 maps in fbcode without
5
+ // taking a folly dependency.
6
+
7
+ #ifdef FBCODE_CAFFE2
8
+ #include <folly/container/F14Map.h>
9
+ #include <folly/container/F14Set.h>
10
+ #else
11
+ #include <unordered_map>
12
+ #include <unordered_set>
13
+ #endif
14
+
15
+ namespace c10 {
16
+ #ifdef FBCODE_CAFFE2
17
+ template <typename Key, typename Value>
18
+ using FastMap = folly::F14FastMap<Key, Value>;
19
+ template <typename Key>
20
+ using FastSet = folly::F14FastSet<Key>;
21
+ #else
22
+ template <typename Key, typename Value>
23
+ using FastMap = std::unordered_map<Key, Value>;
24
+ template <typename Key>
25
+ using FastSet = std::unordered_set<Key>;
26
+ #endif
27
+ } // namespace c10
28
+
29
+ #endif // C10_UTIL_FBCODEMAPS_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Flags.h ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_FLAGS_H_
2
+ #define C10_UTIL_FLAGS_H_
3
+
4
+ /* Commandline flags support for C10.
5
+ *
6
+ * This is a portable commandline flags tool for c10, so we can optionally
7
+ * choose to use gflags or a lightweight custom implementation if gflags is
8
+ * not possible on a certain platform. If you have gflags installed, set the
9
+ * macro C10_USE_GFLAGS will seamlessly route everything to gflags.
10
+ *
11
+ * To define a flag foo of type bool default to true, do the following in the
12
+ * *global* namespace:
13
+ * C10_DEFINE_bool(foo, true, "An example.");
14
+ *
15
+ * To use it in another .cc file, you can use C10_DECLARE_* as follows:
16
+ * C10_DECLARE_bool(foo);
17
+ *
18
+ * In both cases, you can then access the flag via FLAGS_foo.
19
+ *
20
+ * It is recommended that you build with gflags. To learn more about the flags
21
+ * usage, refer to the gflags page here:
22
+ *
23
+ * https://gflags.github.io/gflags/
24
+ *
25
+ * Note about Python users / devs: gflags is initiated from a C++ function
26
+ * ParseCommandLineFlags, and is usually done in native binaries in the main
27
+ * function. As Python does not have a modifiable main function, it is usually
28
+ * difficult to change the flags after Python starts. Hence, it is recommended
29
+ * that one sets the default value of the flags to one that's acceptable in
30
+ * general - that will allow Python to run without wrong flags.
31
+ */
32
+
33
+ #include <c10/macros/Export.h>
34
+ #include <string>
35
+
36
+ #include <c10/util/Registry.h>
37
+
38
+ namespace c10 {
39
+ /**
40
+ * Sets the usage message when a commandline tool is called with "--help".
41
+ */
42
+ C10_API void SetUsageMessage(const std::string& str);
43
+
44
+ /**
45
+ * Returns the usage message for the commandline tool set by SetUsageMessage.
46
+ */
47
+ C10_API const char* UsageMessage();
48
+
49
+ /**
50
+ * Parses the commandline flags.
51
+ *
52
+ * This command parses all the commandline arguments passed in via pargc
53
+ * and argv. Once it is finished, partc and argv will contain the remaining
54
+ * commandline args that c10 does not deal with. Note that following
55
+ * convention, argv[0] contains the binary name and is not parsed.
56
+ */
57
+ C10_API bool ParseCommandLineFlags(int* pargc, char*** pargv);
58
+
59
+ /**
60
+ * Checks if the commandline flags has already been passed.
61
+ */
62
+ C10_API bool CommandLineFlagsHasBeenParsed();
63
+
64
+ } // namespace c10
65
+
66
+ ////////////////////////////////////////////////////////////////////////////////
67
+ // Below are gflags and non-gflags specific implementations.
68
+ // In general, they define the following macros for one to declare (use
69
+ // C10_DECLARE) or define (use C10_DEFINE) flags:
70
+ // C10_{DECLARE,DEFINE}_{int,int64,double,bool,string}
71
+ ////////////////////////////////////////////////////////////////////////////////
72
+
73
+ #ifdef C10_USE_GFLAGS
74
+
75
+ ////////////////////////////////////////////////////////////////////////////////
76
+ // Begin gflags section: most functions are basically rerouted to gflags.
77
+ ////////////////////////////////////////////////////////////////////////////////
78
+ #include <gflags/gflags.h>
79
+
80
+ // C10 uses hidden visibility by default. However, in gflags, it only uses
81
+ // export on Windows platform (with dllexport) but not on linux/mac (with
82
+ // default visibility). As a result, to ensure that we are always exporting
83
+ // global variables, we will redefine the GFLAGS_DLL_DEFINE_FLAG macro if we
84
+ // are building C10 as a shared library.
85
+ // This has to be done after the inclusion of gflags, because some early
86
+ // versions of gflags.h (e.g. 2.0 on ubuntu 14.04) directly defines the
87
+ // macros, so we need to do definition after gflags is done.
88
+ #ifdef GFLAGS_DLL_DEFINE_FLAG
89
+ #undef GFLAGS_DLL_DEFINE_FLAG
90
+ #endif // GFLAGS_DLL_DEFINE_FLAG
91
+ #ifdef GFLAGS_DLL_DECLARE_FLAG
92
+ #undef GFLAGS_DLL_DECLARE_FLAG
93
+ #endif // GFLAGS_DLL_DECLARE_FLAG
94
+ #define GFLAGS_DLL_DEFINE_FLAG C10_EXPORT
95
+ #define GFLAGS_DLL_DECLARE_FLAG C10_IMPORT
96
+
97
+ // gflags before 2.0 uses namespace google and after 2.1 uses namespace gflags.
98
+ // Using GFLAGS_GFLAGS_H_ to capture this change.
99
+ #ifndef GFLAGS_GFLAGS_H_
100
+ namespace gflags = google;
101
+ #endif // GFLAGS_GFLAGS_H_
102
+
103
+ // Motivation about the gflags wrapper:
104
+ // (1) We would need to make sure that the gflags version and the non-gflags
105
+ // version of C10 are going to expose the same flags abstraction. One should
106
+ // explicitly use FLAGS_flag_name to access the flags.
107
+ // (2) For flag names, it is recommended to start with c10_ to distinguish it
108
+ // from regular gflags flags. For example, do
109
+ // C10_DEFINE_BOOL(c10_my_flag, true, "An example");
110
+ // to allow one to use FLAGS_c10_my_flag.
111
+ // (3) Gflags has a design issue that does not properly expose the global flags,
112
+ // if one builds the library with -fvisibility=hidden. The current gflags (as of
113
+ // Aug 2018) only deals with the Windows case using dllexport, and not the Linux
114
+ // counterparts. As a result, we will explicitly use C10_EXPORT to export the
115
+ // flags defined in C10. This is done via a global reference, so the flag
116
+ // itself is not duplicated - under the hood it is the same global gflags flag.
117
+ #define C10_GFLAGS_DEF_WRAPPER(type, real_type, name, default_value, help_str) \
118
+ DEFINE_##type(name, default_value, help_str);
119
+
120
+ #define C10_DEFINE_int(name, default_value, help_str) \
121
+ C10_GFLAGS_DEF_WRAPPER(int32, gflags::int32, name, default_value, help_str)
122
+ #define C10_DEFINE_int32(name, default_value, help_str) \
123
+ C10_DEFINE_int(name, default_value, help_str)
124
+ #define C10_DEFINE_int64(name, default_value, help_str) \
125
+ C10_GFLAGS_DEF_WRAPPER(int64, gflags::int64, name, default_value, help_str)
126
+ #define C10_DEFINE_double(name, default_value, help_str) \
127
+ C10_GFLAGS_DEF_WRAPPER(double, double, name, default_value, help_str)
128
+ #define C10_DEFINE_bool(name, default_value, help_str) \
129
+ C10_GFLAGS_DEF_WRAPPER(bool, bool, name, default_value, help_str)
130
+ #define C10_DEFINE_string(name, default_value, help_str) \
131
+ C10_GFLAGS_DEF_WRAPPER(string, ::fLS::clstring, name, default_value, help_str)
132
+
133
+ // DECLARE_typed_var should be used in header files and in the global namespace.
134
+ #define C10_GFLAGS_DECLARE_WRAPPER(type, real_type, name) DECLARE_##type(name);
135
+
136
+ #define C10_DECLARE_int(name) \
137
+ C10_GFLAGS_DECLARE_WRAPPER(int32, gflags::int32, name)
138
+ #define C10_DECLARE_int32(name) C10_DECLARE_int(name)
139
+ #define C10_DECLARE_int64(name) \
140
+ C10_GFLAGS_DECLARE_WRAPPER(int64, gflags::int64, name)
141
+ #define C10_DECLARE_double(name) \
142
+ C10_GFLAGS_DECLARE_WRAPPER(double, double, name)
143
+ #define C10_DECLARE_bool(name) C10_GFLAGS_DECLARE_WRAPPER(bool, bool, name)
144
+ #define C10_DECLARE_string(name) \
145
+ C10_GFLAGS_DECLARE_WRAPPER(string, ::fLS::clstring, name)
146
+
147
+ #define TORCH_DECLARE_int(name) C10_DECLARE_int(name)
148
+ #define TORCH_DECLARE_int32(name) C10_DECLARE_int32(name)
149
+ #define TORCH_DECLARE_int64(name) C10_DECLARE_int64(name)
150
+ #define TORCH_DECLARE_double(name) C10_DECLARE_double(name)
151
+ #define TORCH_DECLARE_bool(name) C10_DECLARE_bool(name)
152
+ #define TORCH_DECLARE_string(name) C10_DECLARE_string(name)
153
+
154
+ ////////////////////////////////////////////////////////////////////////////////
155
+ // End gflags section.
156
+ ////////////////////////////////////////////////////////////////////////////////
157
+
158
+ #else // C10_USE_GFLAGS
159
+
160
+ ////////////////////////////////////////////////////////////////////////////////
161
+ // Begin non-gflags section: providing equivalent functionality.
162
+ ////////////////////////////////////////////////////////////////////////////////
163
+
164
+ namespace c10 {
165
+
166
+ class C10_API C10FlagParser {
167
+ public:
168
+ bool success() {
169
+ return success_;
170
+ }
171
+
172
+ protected:
173
+ template <typename T>
174
+ bool Parse(const std::string& content, T* value);
175
+ bool success_{false};
176
+ };
177
+
178
+ C10_DECLARE_REGISTRY(C10FlagsRegistry, C10FlagParser, const std::string&);
179
+
180
+ } // namespace c10
181
+
182
+ // The macros are defined outside the c10 namespace. In your code, you should
183
+ // write the C10_DEFINE_* and C10_DECLARE_* macros outside any namespace
184
+ // as well.
185
+
186
+ #define C10_DEFINE_typed_var(type, name, default_value, help_str) \
187
+ C10_EXPORT type FLAGS_##name = default_value; \
188
+ namespace c10 { \
189
+ namespace { \
190
+ class C10FlagParser_##name : public C10FlagParser { \
191
+ public: \
192
+ explicit C10FlagParser_##name(const std::string& content) { \
193
+ success_ = C10FlagParser::Parse<type>(content, &FLAGS_##name); \
194
+ } \
195
+ }; \
196
+ RegistererC10FlagsRegistry g_C10FlagsRegistry_##name( \
197
+ #name, \
198
+ C10FlagsRegistry(), \
199
+ RegistererC10FlagsRegistry::DefaultCreator<C10FlagParser_##name>, \
200
+ "(" #type ", default " #default_value ") " help_str); \
201
+ } \
202
+ }
203
+
204
+ #define C10_DEFINE_int(name, default_value, help_str) \
205
+ C10_DEFINE_typed_var(int, name, default_value, help_str)
206
+ #define C10_DEFINE_int32(name, default_value, help_str) \
207
+ C10_DEFINE_int(name, default_value, help_str)
208
+ #define C10_DEFINE_int64(name, default_value, help_str) \
209
+ C10_DEFINE_typed_var(int64_t, name, default_value, help_str)
210
+ #define C10_DEFINE_double(name, default_value, help_str) \
211
+ C10_DEFINE_typed_var(double, name, default_value, help_str)
212
+ #define C10_DEFINE_bool(name, default_value, help_str) \
213
+ C10_DEFINE_typed_var(bool, name, default_value, help_str)
214
+ #define C10_DEFINE_string(name, default_value, help_str) \
215
+ C10_DEFINE_typed_var(std::string, name, default_value, help_str)
216
+
217
+ // DECLARE_typed_var should be used in header files and in the global namespace.
218
+ #define C10_DECLARE_typed_var(type, name) C10_API extern type FLAGS_##name
219
+
220
+ #define C10_DECLARE_int(name) C10_DECLARE_typed_var(int, name)
221
+ #define C10_DECLARE_int32(name) C10_DECLARE_int(name)
222
+ #define C10_DECLARE_int64(name) C10_DECLARE_typed_var(int64_t, name)
223
+ #define C10_DECLARE_double(name) C10_DECLARE_typed_var(double, name)
224
+ #define C10_DECLARE_bool(name) C10_DECLARE_typed_var(bool, name)
225
+ #define C10_DECLARE_string(name) C10_DECLARE_typed_var(std::string, name)
226
+
227
+ #define TORCH_DECLARE_typed_var(type, name) TORCH_API extern type FLAGS_##name
228
+
229
+ #define TORCH_DECLARE_int(name) TORCH_DECLARE_typed_var(int, name)
230
+ #define TORCH_DECLARE_int32(name) TORCH_DECLARE_int(name)
231
+ #define TORCH_DECLARE_int64(name) TORCH_DECLARE_typed_var(int64_t, name)
232
+ #define TORCH_DECLARE_double(name) TORCH_DECLARE_typed_var(double, name)
233
+ #define TORCH_DECLARE_bool(name) TORCH_DECLARE_typed_var(bool, name)
234
+ #define TORCH_DECLARE_string(name) TORCH_DECLARE_typed_var(std::string, name)
235
+
236
+ ////////////////////////////////////////////////////////////////////////////////
237
+ // End non-gflags section.
238
+ ////////////////////////////////////////////////////////////////////////////////
239
+
240
+ #endif // C10_USE_GFLAGS
241
+
242
+ #endif // C10_UTIL_FLAGS_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float4_e2m1fn_x2.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstdint>
3
+
4
+ #include <c10/macros/Macros.h>
5
+
6
+ /// Defines the Float4_e2m1fn_x2 type (4-bit floating-point, two elements packed
7
+ /// into one byte). This is the FP4 dtype from the OCP MX format spec
8
+ /// (https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf,
9
+ /// Section 5.3.3)
10
+ ///
11
+ /// Given two high precision values val0 and val1, here is the
12
+ /// binary configuration of their packed representation, from MSB to LSB:
13
+ ///
14
+ /// original value | val1 : val0
15
+ /// ========================================
16
+ /// bit index (MSB==7, LSB==0) | 7654 : 3210
17
+ /// sign/exponent/mantissa | seem : seem
18
+ ///
19
+
20
+ namespace c10 {
21
+
22
+ struct alignas(1) Float4_e2m1fn_x2 {
23
+ uint8_t val_;
24
+ Float4_e2m1fn_x2() = default;
25
+ C10_HOST_DEVICE explicit Float4_e2m1fn_x2(uint8_t val) : val_(val) {}
26
+ };
27
+
28
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fn-inl.h ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <cstdint>
5
+ #include <limits>
6
+
7
+ C10_CLANG_DIAGNOSTIC_PUSH()
8
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
9
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
10
+ #endif
11
+
12
+ namespace c10 {
13
+
14
+ /// Constructors
15
+
16
+ inline C10_HOST_DEVICE Float8_e4m3fn::Float8_e4m3fn(float value)
17
+ : x(detail::fp8e4m3fn_from_fp32_value(value)) {}
18
+
19
+ /// Implicit conversions
20
+
21
+ inline C10_HOST_DEVICE Float8_e4m3fn::operator float() const {
22
+ return detail::fp8e4m3fn_to_fp32_value(x);
23
+ }
24
+
25
+ /// Special values helper
26
+
27
+ inline C10_HOST_DEVICE bool Float8_e4m3fn::isnan() const {
28
+ return (x & 0b01111111) == 0b01111111;
29
+ }
30
+
31
+ /// Arithmetic
32
+
33
+ inline C10_HOST_DEVICE Float8_e4m3fn
34
+ operator+(const Float8_e4m3fn& a, const Float8_e4m3fn& b) {
35
+ return static_cast<float>(a) + static_cast<float>(b);
36
+ }
37
+
38
+ inline C10_HOST_DEVICE Float8_e4m3fn
39
+ operator-(const Float8_e4m3fn& a, const Float8_e4m3fn& b) {
40
+ return static_cast<float>(a) - static_cast<float>(b);
41
+ }
42
+
43
+ inline C10_HOST_DEVICE Float8_e4m3fn
44
+ operator*(const Float8_e4m3fn& a, const Float8_e4m3fn& b) {
45
+ return static_cast<float>(a) * static_cast<float>(b);
46
+ }
47
+
48
+ inline C10_HOST_DEVICE Float8_e4m3fn operator/(
49
+ const Float8_e4m3fn& a,
50
+ const Float8_e4m3fn& b) __ubsan_ignore_float_divide_by_zero__ {
51
+ return static_cast<float>(a) / static_cast<float>(b);
52
+ }
53
+
54
+ inline C10_HOST_DEVICE Float8_e4m3fn operator-(const Float8_e4m3fn& a) {
55
+ return -static_cast<float>(a);
56
+ }
57
+
58
+ inline C10_HOST_DEVICE Float8_e4m3fn& operator+=(
59
+ Float8_e4m3fn& a,
60
+ const Float8_e4m3fn& b) {
61
+ a = a + b;
62
+ return a;
63
+ }
64
+
65
+ inline C10_HOST_DEVICE Float8_e4m3fn& operator-=(
66
+ Float8_e4m3fn& a,
67
+ const Float8_e4m3fn& b) {
68
+ a = a - b;
69
+ return a;
70
+ }
71
+
72
+ inline C10_HOST_DEVICE Float8_e4m3fn& operator*=(
73
+ Float8_e4m3fn& a,
74
+ const Float8_e4m3fn& b) {
75
+ a = a * b;
76
+ return a;
77
+ }
78
+
79
+ inline C10_HOST_DEVICE Float8_e4m3fn& operator/=(
80
+ Float8_e4m3fn& a,
81
+ const Float8_e4m3fn& b) {
82
+ a = a / b;
83
+ return a;
84
+ }
85
+
86
+ /// Arithmetic with floats
87
+
88
+ inline C10_HOST_DEVICE float operator+(Float8_e4m3fn a, float b) {
89
+ return static_cast<float>(a) + b;
90
+ }
91
+ inline C10_HOST_DEVICE float operator-(Float8_e4m3fn a, float b) {
92
+ return static_cast<float>(a) - b;
93
+ }
94
+ inline C10_HOST_DEVICE float operator*(Float8_e4m3fn a, float b) {
95
+ return static_cast<float>(a) * b;
96
+ }
97
+ inline C10_HOST_DEVICE float operator/(Float8_e4m3fn a, float b)
98
+ __ubsan_ignore_float_divide_by_zero__ {
99
+ return static_cast<float>(a) / b;
100
+ }
101
+
102
+ inline C10_HOST_DEVICE float operator+(float a, Float8_e4m3fn b) {
103
+ return a + static_cast<float>(b);
104
+ }
105
+ inline C10_HOST_DEVICE float operator-(float a, Float8_e4m3fn b) {
106
+ return a - static_cast<float>(b);
107
+ }
108
+ inline C10_HOST_DEVICE float operator*(float a, Float8_e4m3fn b) {
109
+ return a * static_cast<float>(b);
110
+ }
111
+ inline C10_HOST_DEVICE float operator/(float a, Float8_e4m3fn b)
112
+ __ubsan_ignore_float_divide_by_zero__ {
113
+ return a / static_cast<float>(b);
114
+ }
115
+
116
+ inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e4m3fn& b) {
117
+ return a += static_cast<float>(b);
118
+ }
119
+ inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e4m3fn& b) {
120
+ return a -= static_cast<float>(b);
121
+ }
122
+ inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e4m3fn& b) {
123
+ return a *= static_cast<float>(b);
124
+ }
125
+ inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e4m3fn& b) {
126
+ return a /= static_cast<float>(b);
127
+ }
128
+
129
+ /// Arithmetic with doubles
130
+
131
+ inline C10_HOST_DEVICE double operator+(Float8_e4m3fn a, double b) {
132
+ return static_cast<double>(a) + b;
133
+ }
134
+ inline C10_HOST_DEVICE double operator-(Float8_e4m3fn a, double b) {
135
+ return static_cast<double>(a) - b;
136
+ }
137
+ inline C10_HOST_DEVICE double operator*(Float8_e4m3fn a, double b) {
138
+ return static_cast<double>(a) * b;
139
+ }
140
+ inline C10_HOST_DEVICE double operator/(Float8_e4m3fn a, double b)
141
+ __ubsan_ignore_float_divide_by_zero__ {
142
+ return static_cast<double>(a) / b;
143
+ }
144
+
145
+ inline C10_HOST_DEVICE double operator+(double a, Float8_e4m3fn b) {
146
+ return a + static_cast<double>(b);
147
+ }
148
+ inline C10_HOST_DEVICE double operator-(double a, Float8_e4m3fn b) {
149
+ return a - static_cast<double>(b);
150
+ }
151
+ inline C10_HOST_DEVICE double operator*(double a, Float8_e4m3fn b) {
152
+ return a * static_cast<double>(b);
153
+ }
154
+ inline C10_HOST_DEVICE double operator/(double a, Float8_e4m3fn b)
155
+ __ubsan_ignore_float_divide_by_zero__ {
156
+ return a / static_cast<double>(b);
157
+ }
158
+
159
+ /// Arithmetic with ints
160
+
161
+ inline C10_HOST_DEVICE Float8_e4m3fn operator+(Float8_e4m3fn a, int b) {
162
+ return a + static_cast<Float8_e4m3fn>(b);
163
+ }
164
+ inline C10_HOST_DEVICE Float8_e4m3fn operator-(Float8_e4m3fn a, int b) {
165
+ return a - static_cast<Float8_e4m3fn>(b);
166
+ }
167
+ inline C10_HOST_DEVICE Float8_e4m3fn operator*(Float8_e4m3fn a, int b) {
168
+ return a * static_cast<Float8_e4m3fn>(b);
169
+ }
170
+ inline C10_HOST_DEVICE Float8_e4m3fn operator/(Float8_e4m3fn a, int b) {
171
+ return a / static_cast<Float8_e4m3fn>(b);
172
+ }
173
+
174
+ inline C10_HOST_DEVICE Float8_e4m3fn operator+(int a, Float8_e4m3fn b) {
175
+ return static_cast<Float8_e4m3fn>(a) + b;
176
+ }
177
+ inline C10_HOST_DEVICE Float8_e4m3fn operator-(int a, Float8_e4m3fn b) {
178
+ return static_cast<Float8_e4m3fn>(a) - b;
179
+ }
180
+ inline C10_HOST_DEVICE Float8_e4m3fn operator*(int a, Float8_e4m3fn b) {
181
+ return static_cast<Float8_e4m3fn>(a) * b;
182
+ }
183
+ inline C10_HOST_DEVICE Float8_e4m3fn operator/(int a, Float8_e4m3fn b) {
184
+ return static_cast<Float8_e4m3fn>(a) / b;
185
+ }
186
+
187
+ //// Arithmetic with int64_t
188
+
189
+ inline C10_HOST_DEVICE Float8_e4m3fn operator+(Float8_e4m3fn a, int64_t b) {
190
+ return a + static_cast<Float8_e4m3fn>(b);
191
+ }
192
+ inline C10_HOST_DEVICE Float8_e4m3fn operator-(Float8_e4m3fn a, int64_t b) {
193
+ return a - static_cast<Float8_e4m3fn>(b);
194
+ }
195
+ inline C10_HOST_DEVICE Float8_e4m3fn operator*(Float8_e4m3fn a, int64_t b) {
196
+ return a * static_cast<Float8_e4m3fn>(b);
197
+ }
198
+ inline C10_HOST_DEVICE Float8_e4m3fn operator/(Float8_e4m3fn a, int64_t b) {
199
+ return a / static_cast<Float8_e4m3fn>(b);
200
+ }
201
+
202
+ inline C10_HOST_DEVICE Float8_e4m3fn operator+(int64_t a, Float8_e4m3fn b) {
203
+ return static_cast<Float8_e4m3fn>(a) + b;
204
+ }
205
+ inline C10_HOST_DEVICE Float8_e4m3fn operator-(int64_t a, Float8_e4m3fn b) {
206
+ return static_cast<Float8_e4m3fn>(a) - b;
207
+ }
208
+ inline C10_HOST_DEVICE Float8_e4m3fn operator*(int64_t a, Float8_e4m3fn b) {
209
+ return static_cast<Float8_e4m3fn>(a) * b;
210
+ }
211
+ inline C10_HOST_DEVICE Float8_e4m3fn operator/(int64_t a, Float8_e4m3fn b) {
212
+ return static_cast<Float8_e4m3fn>(a) / b;
213
+ }
214
+
215
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
216
+ /// conversion from c10::Float8_e4m3fn to float.
217
+
218
+ } // namespace c10
219
+
220
+ namespace std {
221
+
222
+ template <>
223
+ class numeric_limits<c10::Float8_e4m3fn> {
224
+ public:
225
+ static constexpr bool is_specialized = true;
226
+ static constexpr bool is_signed = true;
227
+ static constexpr bool is_integer = false;
228
+ static constexpr bool is_exact = false;
229
+ static constexpr bool has_infinity = false;
230
+ static constexpr bool has_quiet_NaN = true;
231
+ static constexpr bool has_signaling_NaN = false;
232
+ static constexpr auto has_denorm = true;
233
+ static constexpr auto has_denorm_loss = true;
234
+ static constexpr auto round_style = numeric_limits<float>::round_style;
235
+ static constexpr bool is_iec559 = false;
236
+ static constexpr bool is_bounded = true;
237
+ static constexpr bool is_modulo = false;
238
+ static constexpr int digits = 4;
239
+ static constexpr int digits10 = 0;
240
+ static constexpr int max_digits10 = 3;
241
+ static constexpr int radix = 2;
242
+ static constexpr int min_exponent = -5;
243
+ static constexpr int min_exponent10 = -1;
244
+ static constexpr int max_exponent = 8;
245
+ static constexpr int max_exponent10 = 2;
246
+ static constexpr auto traps = numeric_limits<float>::traps;
247
+ static constexpr auto tinyness_before = false;
248
+
249
+ static constexpr c10::Float8_e4m3fn min() {
250
+ return c10::Float8_e4m3fn(0x08, c10::Float8_e4m3fn::from_bits());
251
+ }
252
+ static constexpr c10::Float8_e4m3fn lowest() {
253
+ return c10::Float8_e4m3fn(0xFE, c10::Float8_e4m3fn::from_bits());
254
+ }
255
+ static constexpr c10::Float8_e4m3fn max() {
256
+ return c10::Float8_e4m3fn(0x7E, c10::Float8_e4m3fn::from_bits());
257
+ }
258
+ static constexpr c10::Float8_e4m3fn epsilon() {
259
+ return c10::Float8_e4m3fn(0x20, c10::Float8_e4m3fn::from_bits());
260
+ }
261
+ static constexpr c10::Float8_e4m3fn round_error() {
262
+ return c10::Float8_e4m3fn(0x30, c10::Float8_e4m3fn::from_bits());
263
+ }
264
+ static constexpr c10::Float8_e4m3fn quiet_NaN() {
265
+ return c10::Float8_e4m3fn(0x7F, c10::Float8_e4m3fn::from_bits());
266
+ }
267
+ static constexpr c10::Float8_e4m3fn denorm_min() {
268
+ return c10::Float8_e4m3fn(0x01, c10::Float8_e4m3fn::from_bits());
269
+ }
270
+ };
271
+
272
+ } // namespace std
273
+
274
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fn.h ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Float8_e4m3fn type (8-bit floating-point) including conversions
4
+ /// to standard C types and basic arithmetic operations. Note that arithmetic
5
+ /// operations are implemented by converting to floating point and
6
+ /// performing the operation in float32.
7
+ /// Binary configuration:
8
+ /// s eeee mmm
9
+ /// 1 sign bit
10
+ /// 4 exponent bits
11
+ /// 3 mantissa bits
12
+ /// bias = 7
13
+ ///
14
+ /// Implementation based on the paper https://arxiv.org/pdf/2209.05433.pdf
15
+ /// and inspired by Half implementation from pytorch/c10/util/Half.h
16
+
17
+ #include <c10/macros/Macros.h>
18
+ #include <c10/util/floating_point_utils.h>
19
+
20
+ #if defined(__cplusplus)
21
+ #include <cmath>
22
+ #include <cstdint>
23
+ #elif !defined(__OPENCL_VERSION__)
24
+ #include <math.h>
25
+ #include <stdint.h>
26
+ #endif
27
+
28
+ #ifdef _MSC_VER
29
+ #include <intrin.h>
30
+ #endif
31
+
32
+ #include <climits>
33
+ #include <iostream>
34
+
35
+ namespace c10 {
36
+
37
+ namespace detail {
38
+
39
+ /*
40
+ * Convert a 8-bit floating-point number in fp8 E4M3FN format, in bit
41
+ * representation, to a 32-bit floating-point number in IEEE single-precision
42
+ * format, in bit representation.
43
+ *
44
+ * @note The implementation doesn't use any floating-point operations.
45
+ */
46
+ inline C10_HOST_DEVICE float fp8e4m3fn_to_fp32_value(uint8_t input) {
47
+ /*
48
+ * Extend the fp8 E4M3FN number to 32 bits and shift to the
49
+ * upper part of the 32-bit word:
50
+ * +---+----+---+-----------------------------+
51
+ * | S |EEEE|MMM|0000 0000 0000 0000 0000 0000|
52
+ * +---+----+---+-----------------------------+
53
+ * Bits 31 27-30 24-26 0-23
54
+ *
55
+ * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
56
+ * - zero bits.
57
+ */
58
+ const uint32_t w = (uint32_t)input << 24;
59
+ /*
60
+ * Extract the sign of the input number into the high bit of the 32-bit word:
61
+ *
62
+ * +---+----------------------------------+
63
+ * | S |0000000 00000000 00000000 00000000|
64
+ * +---+----------------------------------+
65
+ * Bits 31 0-31
66
+ */
67
+ const uint32_t sign = w & UINT32_C(0x80000000);
68
+ /*
69
+ * Extract mantissa and biased exponent of the input number into the bits 0-30
70
+ * of the 32-bit word:
71
+ *
72
+ * +---+----+---+-----------------------------+
73
+ * | S |EEEE|MMM|0000 0000 0000 0000 0000 0000|
74
+ * +---+----+---+-----------------------------+
75
+ * Bits 31 27-30 24-26 0-23
76
+ */
77
+ const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF);
78
+ /*
79
+ * Renorm shift is the number of bits to shift mantissa left to make the
80
+ * half-precision number normalized. If the initial number is normalized, some
81
+ * of its high 5 bits (sign == 0 and 4-bit exponent) equals one. In this case
82
+ * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note
83
+ * that if we shift denormalized nonsign by renorm_shift, the unit bit of
84
+ * mantissa will shift into exponent, turning the biased exponent into 1, and
85
+ * making mantissa normalized (i.e. without leading 1).
86
+ */
87
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
88
+ uint32_t renorm_shift = __clz(nonsign);
89
+ #elif defined(__SYCL_DEVICE_ONLY__)
90
+ // Note: zero is not a supported input into `__builtin_clz`
91
+ uint32_t renorm_shift =
92
+ nonsign != 0 ? __builtin_clz(nonsign) : sizeof(uint32_t) * CHAR_BIT;
93
+ #elif defined(_MSC_VER) && !defined(__clang__)
94
+ unsigned long nonsign_bsr;
95
+ _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign);
96
+ uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31;
97
+ #else
98
+ // Note: zero is not a supported input into `__builtin_clz`
99
+ uint32_t renorm_shift =
100
+ nonsign != 0 ? __builtin_clz(nonsign) : sizeof(uint32_t) * CHAR_BIT;
101
+ #endif
102
+ renorm_shift = renorm_shift > 4 ? renorm_shift - 4 : 0;
103
+ /*
104
+ * Iff fp8e4m3fn number has all exponent and mantissa bits set to 1,
105
+ * the addition overflows it into bit 31, and the subsequent shift turns the
106
+ * high 9 bits into 1. Thus inf_nan_mask == 0x7F800000 if the fp8e4m3fn number
107
+ * is Nan, 0x00000000 otherwise
108
+ */
109
+ const int32_t inf_nan_mask =
110
+ ((int32_t)(nonsign + 0x01000000) >> 8) & INT32_C(0x7F800000);
111
+ /*
112
+ * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31
113
+ * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31
114
+ * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask ==
115
+ * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h)
116
+ * 0x00000000 otherwise
117
+ */
118
+ const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31;
119
+ /*
120
+ * 1. Shift nonsign left by renorm_shift to normalize it (if the input
121
+ * was denormal)
122
+ * 2. Shift nonsign right by 4 so the exponent (4 bits originally)
123
+ * becomes an 8-bit field and 3-bit mantissa shifts into the 3 high
124
+ * bits of the 23-bit mantissa of IEEE single-precision number.
125
+ * 3. Add 0x78 to the exponent (starting at bit 23) to compensate the
126
+ * different in exponent bias (0x7F for single-precision number less 0x07
127
+ * for fp8e4m3fn number).
128
+ * 4. Subtract renorm_shift from the exponent (starting at bit 23) to
129
+ * account for renormalization. As renorm_shift is less than 0x78, this
130
+ * can be combined with step 3.
131
+ * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the
132
+ * input was NaN or infinity.
133
+ * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent
134
+ * into zero if the input was zero.
135
+ * 7. Combine with the sign of the input number.
136
+ */
137
+ uint32_t result = sign |
138
+ ((((nonsign << renorm_shift >> 4) + ((0x78 - renorm_shift) << 23)) |
139
+ inf_nan_mask) &
140
+ ~zero_mask);
141
+ return fp32_from_bits(result);
142
+ }
143
+
144
+ /*
145
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
146
+ * 8-bit floating-point number in fp8 E4M3FN format, in bit representation.
147
+ */
148
+ inline C10_HOST_DEVICE uint8_t fp8e4m3fn_from_fp32_value(float f) {
149
+ /*
150
+ * Binary representation of 480.0f, which is the first value
151
+ * not representable in fp8e4m3fn range:
152
+ * 0 1111 111 - fp8e4m3fn
153
+ * 0 10000111 11100000000000000000000 - fp32
154
+ */
155
+ constexpr uint32_t fp8_max = UINT32_C(1087) << 20;
156
+
157
+ /*
158
+ * A mask for converting fp32 numbers lower than fp8e4m3fn normal range
159
+ * into denorm representation
160
+ * magic number: ((127 - 7) + (23 - 3) + 1)
161
+ */
162
+ constexpr uint32_t denorm_mask = UINT32_C(141) << 23;
163
+
164
+ uint32_t f_bits = fp32_to_bits(f);
165
+
166
+ uint8_t result = 0u;
167
+
168
+ /*
169
+ * Extract the sign of the input number into the high bit of the 32-bit word:
170
+ *
171
+ * +---+----------------------------------+
172
+ * | S |0000000 00000000 00000000 00000000|
173
+ * +---+----------------------------------+
174
+ * Bits 31 0-31
175
+ */
176
+ const uint32_t sign = f_bits & UINT32_C(0x80000000);
177
+
178
+ /*
179
+ * Set sign bit to 0
180
+ */
181
+ f_bits ^= sign;
182
+
183
+ if (f_bits >= fp8_max) {
184
+ // NaN - all exponent and mantissa bits set to 1
185
+ result = 0x7f;
186
+ } else {
187
+ if (f_bits < (UINT32_C(121) << 23)) {
188
+ // Input number is smaller than 2^(-6), which is the smallest
189
+ // fp8e4m3fn normal number
190
+ f_bits =
191
+ fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask));
192
+ result = static_cast<uint8_t>(f_bits - denorm_mask);
193
+ } else {
194
+ // resulting mantissa is odd
195
+ uint8_t mant_odd = (f_bits >> 20) & 1;
196
+
197
+ // update exponent, rounding bias part 1
198
+ f_bits += ((uint32_t)(7 - 127) << 23) + 0x7FFFF;
199
+
200
+ // rounding bias part 2
201
+ f_bits += mant_odd;
202
+
203
+ // take the bits!
204
+ result = static_cast<uint8_t>(f_bits >> 20);
205
+ }
206
+ }
207
+
208
+ result |= static_cast<uint8_t>(sign >> 24);
209
+ return result;
210
+ }
211
+
212
+ } // namespace detail
213
+
214
+ struct alignas(1) Float8_e4m3fn {
215
+ uint8_t x;
216
+
217
+ struct from_bits_t {};
218
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
219
+ return from_bits_t();
220
+ }
221
+
222
+ Float8_e4m3fn() = default;
223
+
224
+ constexpr C10_HOST_DEVICE Float8_e4m3fn(uint8_t bits, from_bits_t)
225
+ : x(bits) {}
226
+ inline C10_HOST_DEVICE Float8_e4m3fn(float value);
227
+ inline C10_HOST_DEVICE operator float() const;
228
+ inline C10_HOST_DEVICE bool isnan() const;
229
+ };
230
+
231
+ C10_API inline std::ostream& operator<<(
232
+ std::ostream& out,
233
+ const Float8_e4m3fn& value) {
234
+ out << (float)value;
235
+ return out;
236
+ }
237
+
238
+ } // namespace c10
239
+
240
+ #include <c10/util/Float8_e4m3fn-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fnuz-inl.h ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/Float8_fnuz_cvt.h>
5
+ #include <cstring>
6
+ #include <limits>
7
+
8
+ C10_CLANG_DIAGNOSTIC_PUSH()
9
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
10
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
11
+ #endif
12
+
13
+ namespace c10 {
14
+
15
+ /// Constructors
16
+
17
+ inline C10_HOST_DEVICE Float8_e4m3fnuz::Float8_e4m3fnuz(float value)
18
+ : x(detail::fp8e4m3fnuz_from_fp32_value(value)) {}
19
+
20
+ /// Implicit conversions
21
+
22
+ inline C10_HOST_DEVICE Float8_e4m3fnuz::operator float() const {
23
+ return detail::fp8_fnuz_to_fp32_value<4, 3>(x);
24
+ }
25
+
26
+ /// Special values helper
27
+
28
+ inline C10_HOST_DEVICE bool Float8_e4m3fnuz::isnan() const {
29
+ return x == 0b10000000;
30
+ }
31
+
32
+ /// Arithmetic
33
+
34
+ inline C10_HOST_DEVICE Float8_e4m3fnuz
35
+ operator+(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) {
36
+ return static_cast<float>(a) + static_cast<float>(b);
37
+ }
38
+
39
+ inline C10_HOST_DEVICE Float8_e4m3fnuz
40
+ operator-(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) {
41
+ return static_cast<float>(a) - static_cast<float>(b);
42
+ }
43
+
44
+ inline C10_HOST_DEVICE Float8_e4m3fnuz
45
+ operator*(const Float8_e4m3fnuz& a, const Float8_e4m3fnuz& b) {
46
+ return static_cast<float>(a) * static_cast<float>(b);
47
+ }
48
+
49
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(
50
+ const Float8_e4m3fnuz& a,
51
+ const Float8_e4m3fnuz& b) __ubsan_ignore_float_divide_by_zero__ {
52
+ return static_cast<float>(a) / static_cast<float>(b);
53
+ }
54
+
55
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(const Float8_e4m3fnuz& a) {
56
+ return -static_cast<float>(a);
57
+ }
58
+
59
+ inline C10_HOST_DEVICE Float8_e4m3fnuz& operator+=(
60
+ Float8_e4m3fnuz& a,
61
+ const Float8_e4m3fnuz& b) {
62
+ a = a + b;
63
+ return a;
64
+ }
65
+
66
+ inline C10_HOST_DEVICE Float8_e4m3fnuz& operator-=(
67
+ Float8_e4m3fnuz& a,
68
+ const Float8_e4m3fnuz& b) {
69
+ a = a - b;
70
+ return a;
71
+ }
72
+
73
+ inline C10_HOST_DEVICE Float8_e4m3fnuz& operator*=(
74
+ Float8_e4m3fnuz& a,
75
+ const Float8_e4m3fnuz& b) {
76
+ a = a * b;
77
+ return a;
78
+ }
79
+
80
+ inline C10_HOST_DEVICE Float8_e4m3fnuz& operator/=(
81
+ Float8_e4m3fnuz& a,
82
+ const Float8_e4m3fnuz& b) {
83
+ a = a / b;
84
+ return a;
85
+ }
86
+
87
+ /// Arithmetic with floats
88
+
89
+ inline C10_HOST_DEVICE float operator+(Float8_e4m3fnuz a, float b) {
90
+ return static_cast<float>(a) + b;
91
+ }
92
+ inline C10_HOST_DEVICE float operator-(Float8_e4m3fnuz a, float b) {
93
+ return static_cast<float>(a) - b;
94
+ }
95
+ inline C10_HOST_DEVICE float operator*(Float8_e4m3fnuz a, float b) {
96
+ return static_cast<float>(a) * b;
97
+ }
98
+ inline C10_HOST_DEVICE float operator/(Float8_e4m3fnuz a, float b)
99
+ __ubsan_ignore_float_divide_by_zero__ {
100
+ return static_cast<float>(a) / b;
101
+ }
102
+
103
+ inline C10_HOST_DEVICE float operator+(float a, Float8_e4m3fnuz b) {
104
+ return a + static_cast<float>(b);
105
+ }
106
+ inline C10_HOST_DEVICE float operator-(float a, Float8_e4m3fnuz b) {
107
+ return a - static_cast<float>(b);
108
+ }
109
+ inline C10_HOST_DEVICE float operator*(float a, Float8_e4m3fnuz b) {
110
+ return a * static_cast<float>(b);
111
+ }
112
+ inline C10_HOST_DEVICE float operator/(float a, Float8_e4m3fnuz b)
113
+ __ubsan_ignore_float_divide_by_zero__ {
114
+ return a / static_cast<float>(b);
115
+ }
116
+
117
+ inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e4m3fnuz& b) {
118
+ return a += static_cast<float>(b);
119
+ }
120
+ inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e4m3fnuz& b) {
121
+ return a -= static_cast<float>(b);
122
+ }
123
+ inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e4m3fnuz& b) {
124
+ return a *= static_cast<float>(b);
125
+ }
126
+ inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e4m3fnuz& b) {
127
+ return a /= static_cast<float>(b);
128
+ }
129
+
130
+ /// Arithmetic with doubles
131
+
132
+ inline C10_HOST_DEVICE double operator+(Float8_e4m3fnuz a, double b) {
133
+ return static_cast<double>(a) + b;
134
+ }
135
+ inline C10_HOST_DEVICE double operator-(Float8_e4m3fnuz a, double b) {
136
+ return static_cast<double>(a) - b;
137
+ }
138
+ inline C10_HOST_DEVICE double operator*(Float8_e4m3fnuz a, double b) {
139
+ return static_cast<double>(a) * b;
140
+ }
141
+ inline C10_HOST_DEVICE double operator/(Float8_e4m3fnuz a, double b)
142
+ __ubsan_ignore_float_divide_by_zero__ {
143
+ return static_cast<double>(a) / b;
144
+ }
145
+
146
+ inline C10_HOST_DEVICE double operator+(double a, Float8_e4m3fnuz b) {
147
+ return a + static_cast<double>(b);
148
+ }
149
+ inline C10_HOST_DEVICE double operator-(double a, Float8_e4m3fnuz b) {
150
+ return a - static_cast<double>(b);
151
+ }
152
+ inline C10_HOST_DEVICE double operator*(double a, Float8_e4m3fnuz b) {
153
+ return a * static_cast<double>(b);
154
+ }
155
+ inline C10_HOST_DEVICE double operator/(double a, Float8_e4m3fnuz b)
156
+ __ubsan_ignore_float_divide_by_zero__ {
157
+ return a / static_cast<double>(b);
158
+ }
159
+
160
+ /// Arithmetic with ints
161
+
162
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(Float8_e4m3fnuz a, int b) {
163
+ return a + static_cast<Float8_e4m3fnuz>(b);
164
+ }
165
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(Float8_e4m3fnuz a, int b) {
166
+ return a - static_cast<Float8_e4m3fnuz>(b);
167
+ }
168
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(Float8_e4m3fnuz a, int b) {
169
+ return a * static_cast<Float8_e4m3fnuz>(b);
170
+ }
171
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(Float8_e4m3fnuz a, int b) {
172
+ return a / static_cast<Float8_e4m3fnuz>(b);
173
+ }
174
+
175
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(int a, Float8_e4m3fnuz b) {
176
+ return static_cast<Float8_e4m3fnuz>(a) + b;
177
+ }
178
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(int a, Float8_e4m3fnuz b) {
179
+ return static_cast<Float8_e4m3fnuz>(a) - b;
180
+ }
181
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(int a, Float8_e4m3fnuz b) {
182
+ return static_cast<Float8_e4m3fnuz>(a) * b;
183
+ }
184
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(int a, Float8_e4m3fnuz b) {
185
+ return static_cast<Float8_e4m3fnuz>(a) / b;
186
+ }
187
+
188
+ //// Arithmetic with int64_t
189
+
190
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(Float8_e4m3fnuz a, int64_t b) {
191
+ return a + static_cast<Float8_e4m3fnuz>(b);
192
+ }
193
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(Float8_e4m3fnuz a, int64_t b) {
194
+ return a - static_cast<Float8_e4m3fnuz>(b);
195
+ }
196
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(Float8_e4m3fnuz a, int64_t b) {
197
+ return a * static_cast<Float8_e4m3fnuz>(b);
198
+ }
199
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(Float8_e4m3fnuz a, int64_t b) {
200
+ return a / static_cast<Float8_e4m3fnuz>(b);
201
+ }
202
+
203
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator+(int64_t a, Float8_e4m3fnuz b) {
204
+ return static_cast<Float8_e4m3fnuz>(a) + b;
205
+ }
206
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator-(int64_t a, Float8_e4m3fnuz b) {
207
+ return static_cast<Float8_e4m3fnuz>(a) - b;
208
+ }
209
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator*(int64_t a, Float8_e4m3fnuz b) {
210
+ return static_cast<Float8_e4m3fnuz>(a) * b;
211
+ }
212
+ inline C10_HOST_DEVICE Float8_e4m3fnuz operator/(int64_t a, Float8_e4m3fnuz b) {
213
+ return static_cast<Float8_e4m3fnuz>(a) / b;
214
+ }
215
+
216
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
217
+ /// conversion from c10::Float8_e4m3fnuz to float.
218
+
219
+ } // namespace c10
220
+
221
+ namespace std {
222
+
223
+ template <>
224
+ class numeric_limits<c10::Float8_e4m3fnuz> {
225
+ public:
226
+ static constexpr bool is_specialized = true;
227
+ static constexpr bool is_signed = true;
228
+ static constexpr bool is_integer = false;
229
+ static constexpr bool is_exact = false;
230
+ static constexpr bool has_infinity = false;
231
+ static constexpr bool has_quiet_NaN = true;
232
+ static constexpr bool has_signaling_NaN = false;
233
+ static constexpr auto has_denorm = true;
234
+ static constexpr auto has_denorm_loss = true;
235
+ static constexpr auto round_style = numeric_limits<float>::round_style;
236
+ static constexpr bool is_iec559 = false;
237
+ static constexpr bool is_bounded = true;
238
+ static constexpr bool is_modulo = false;
239
+ static constexpr int digits = 4;
240
+ static constexpr int digits10 = 0;
241
+ static constexpr int max_digits10 = 3;
242
+ static constexpr int radix = 2;
243
+ static constexpr int min_exponent = -6;
244
+ static constexpr int min_exponent10 = -1;
245
+ static constexpr int max_exponent = 8;
246
+ static constexpr int max_exponent10 = 2;
247
+ static constexpr auto traps = numeric_limits<float>::traps;
248
+ static constexpr auto tinyness_before = false;
249
+
250
+ static constexpr c10::Float8_e4m3fnuz min() {
251
+ return c10::Float8_e4m3fnuz(0x08, c10::Float8_e4m3fnuz::from_bits());
252
+ }
253
+ static constexpr c10::Float8_e4m3fnuz lowest() {
254
+ return c10::Float8_e4m3fnuz(0xFF, c10::Float8_e4m3fnuz::from_bits());
255
+ }
256
+ static constexpr c10::Float8_e4m3fnuz max() {
257
+ return c10::Float8_e4m3fnuz(0x7F, c10::Float8_e4m3fnuz::from_bits());
258
+ }
259
+ static constexpr c10::Float8_e4m3fnuz epsilon() {
260
+ return c10::Float8_e4m3fnuz(0x28, c10::Float8_e4m3fnuz::from_bits());
261
+ }
262
+ static constexpr c10::Float8_e4m3fnuz round_error() {
263
+ return c10::Float8_e4m3fnuz(0x38, c10::Float8_e4m3fnuz::from_bits());
264
+ }
265
+ static constexpr c10::Float8_e4m3fnuz infinity() {
266
+ // NaN (no infinities)
267
+ return c10::Float8_e4m3fnuz(0x80, c10::Float8_e4m3fnuz::from_bits());
268
+ }
269
+ static constexpr c10::Float8_e4m3fnuz quiet_NaN() {
270
+ return c10::Float8_e4m3fnuz(0x80, c10::Float8_e4m3fnuz::from_bits());
271
+ }
272
+ static constexpr c10::Float8_e4m3fnuz denorm_min() {
273
+ return c10::Float8_e4m3fnuz(0x01, c10::Float8_e4m3fnuz::from_bits());
274
+ }
275
+ };
276
+
277
+ } // namespace std
278
+
279
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e4m3fnuz.h ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Float8_e4m3fnuz type (8-bit floating-point) including
4
+ /// conversions to standard C types and basic arithmetic operations. Note that
5
+ /// arithmetic operations are implemented by converting to floating point and
6
+ /// performing the operation in float32.
7
+ /// Binary configuration remains the same as Float8_e4m3fn:
8
+ /// s eeee mmm
9
+ /// 1 sign bit
10
+ /// 4 exponent bits
11
+ /// 3 mantissa bits
12
+ /// The key differences versus Float8_e4m3fn are:
13
+ /// bias = 8
14
+ /// no infinities or negative zero
15
+ /// NaN only when sign bit is 1, rest all 0s
16
+ ///
17
+ /// Implementation based on the paper https://arxiv.org/pdf/2206.02915.pdf and
18
+ /// the existing Float8_e4m3fn implementation.
19
+
20
+ #include <c10/macros/Export.h>
21
+ #include <c10/macros/Macros.h>
22
+ #include <c10/util/floating_point_utils.h>
23
+ #include <type_traits>
24
+
25
+ #if defined(__cplusplus)
26
+ #include <cstdint>
27
+ #elif !defined(__OPENCL_VERSION__)
28
+ #include <math.h>
29
+ #include <stdint.h>
30
+ #endif
31
+
32
+ #include <iosfwd>
33
+ #include <ostream>
34
+
35
+ namespace c10 {
36
+
37
+ namespace detail {
38
+
39
+ /*
40
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
41
+ * 8-bit floating-point number in fp8 E4M3FNUZ format, in bit representation.
42
+ */
43
+ inline C10_HOST_DEVICE uint8_t fp8e4m3fnuz_from_fp32_value(float f) {
44
+ /*
45
+ * Binary representation of 256.0f, which is the first value not representable
46
+ * (i.e. the first value which would overflow in to the sign bit, resulting in
47
+ * a NaN) in fp8e4m3fnuz range:
48
+ * 1 0000 000 - fp8e4m3fnuz
49
+ * 0 10000111 00000000000000000000000 - fp32
50
+ */
51
+ constexpr uint32_t fnuz_max = UINT32_C(0x87) << 23;
52
+
53
+ /*
54
+ * A mask for converting fp32 numbers lower than fp8e4m3fnuz normal range
55
+ * into denorm representation
56
+ * magic number: ((127 - 8) + (23 - 3) + 1)
57
+ */
58
+ constexpr uint32_t denorm_mask = UINT32_C(0x8C) << 23;
59
+
60
+ uint32_t f_bits = fp32_to_bits(f);
61
+
62
+ uint32_t result = 0u;
63
+
64
+ /*
65
+ * Extract the sign of the input number into the high bit of the 32-bit word:
66
+ *
67
+ * +---+----------------------------------+
68
+ * | S |0000000 00000000 00000000 00000000|
69
+ * +---+----------------------------------+
70
+ * Bits 31 0-31
71
+ */
72
+ const uint32_t sign = f_bits & UINT32_C(0x80000000);
73
+
74
+ /*
75
+ * Set sign bit to 0
76
+ */
77
+ f_bits ^= sign;
78
+
79
+ if (f_bits >= fnuz_max) {
80
+ // NaN -- sign bit set to 1, rest 0s.
81
+ return 0x80;
82
+ }
83
+
84
+ if (f_bits < (UINT32_C(0x78) << 23) /* 2^-7 in float32 */) {
85
+ // Input exponent is less than -7, the smallest e4m3fnuz exponent, so the
86
+ // number will become subnormal.
87
+ f_bits = fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask));
88
+ result = static_cast<uint8_t>(f_bits - denorm_mask);
89
+ if (result == 0) {
90
+ // fnuz types don't have negative zero.
91
+ return 0;
92
+ }
93
+ } else {
94
+ // resulting mantissa is odd
95
+ uint8_t mant_odd = (f_bits >> 20) & 1;
96
+
97
+ // update exponent, rounding bias part 1
98
+ f_bits += ((uint32_t)(8 - 127) << 23) + 0x7FFFF;
99
+
100
+ // rounding bias part 2
101
+ f_bits += mant_odd;
102
+
103
+ // take the bits!
104
+ result = static_cast<uint8_t>(f_bits >> 20);
105
+ }
106
+
107
+ result |= sign >> 24;
108
+ return result;
109
+ }
110
+
111
+ } // namespace detail
112
+
113
+ struct alignas(1) Float8_e4m3fnuz {
114
+ uint8_t x;
115
+
116
+ struct from_bits_t {};
117
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
118
+ return from_bits_t();
119
+ }
120
+
121
+ Float8_e4m3fnuz() = default;
122
+
123
+ constexpr C10_HOST_DEVICE Float8_e4m3fnuz(uint8_t bits, from_bits_t)
124
+ : x(bits) {}
125
+ inline C10_HOST_DEVICE Float8_e4m3fnuz(float value);
126
+ inline C10_HOST_DEVICE operator float() const;
127
+ inline C10_HOST_DEVICE bool isnan() const;
128
+ };
129
+
130
+ C10_API inline std::ostream& operator<<(
131
+ std::ostream& out,
132
+ const Float8_e4m3fnuz& value) {
133
+ out << (float)value;
134
+ return out;
135
+ }
136
+
137
+ } // namespace c10
138
+
139
+ #include <c10/util/Float8_e4m3fnuz-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2-inl.h ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <cstring>
5
+ #include <limits>
6
+
7
+ C10_CLANG_DIAGNOSTIC_PUSH()
8
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
9
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
10
+ #endif
11
+
12
+ #define EXP_WIDTH_FP8 5
13
+ #define MAN_WIDTH_FP8 2
14
+ #define EXP_BIAS_FP8 15
15
+
16
+ namespace c10 {
17
+
18
+ /// Constructors
19
+
20
+ inline C10_HOST_DEVICE Float8_e5m2::Float8_e5m2(float value)
21
+ : x(detail::fp8e5m2_from_fp32_value(value)) {}
22
+
23
+ /// Implicit conversions
24
+
25
+ inline C10_HOST_DEVICE Float8_e5m2::operator float() const {
26
+ return detail::fp8e5m2_to_fp32_value(x);
27
+ }
28
+
29
+ /// Special values helpers
30
+
31
+ inline C10_HOST_DEVICE bool Float8_e5m2::isnan() const {
32
+ return (x & 0b01111111) > 0b01111100;
33
+ }
34
+
35
+ inline C10_HOST_DEVICE bool Float8_e5m2::isinf() const {
36
+ return (x & 0b01111111) == 0b01111100;
37
+ }
38
+
39
+ /// Arithmetic
40
+
41
+ inline C10_HOST_DEVICE Float8_e5m2
42
+ operator+(const Float8_e5m2& a, const Float8_e5m2& b) {
43
+ return static_cast<float>(a) + static_cast<float>(b);
44
+ }
45
+
46
+ inline C10_HOST_DEVICE Float8_e5m2
47
+ operator-(const Float8_e5m2& a, const Float8_e5m2& b) {
48
+ return static_cast<float>(a) - static_cast<float>(b);
49
+ }
50
+
51
+ inline C10_HOST_DEVICE Float8_e5m2
52
+ operator*(const Float8_e5m2& a, const Float8_e5m2& b) {
53
+ return static_cast<float>(a) * static_cast<float>(b);
54
+ }
55
+
56
+ inline C10_HOST_DEVICE Float8_e5m2 operator/(
57
+ const Float8_e5m2& a,
58
+ const Float8_e5m2& b) __ubsan_ignore_float_divide_by_zero__ {
59
+ return static_cast<float>(a) / static_cast<float>(b);
60
+ }
61
+
62
+ inline C10_HOST_DEVICE Float8_e5m2 operator-(const Float8_e5m2& a) {
63
+ return -static_cast<float>(a);
64
+ }
65
+
66
+ inline C10_HOST_DEVICE Float8_e5m2& operator+=(
67
+ Float8_e5m2& a,
68
+ const Float8_e5m2& b) {
69
+ a = a + b;
70
+ return a;
71
+ }
72
+
73
+ inline C10_HOST_DEVICE Float8_e5m2& operator-=(
74
+ Float8_e5m2& a,
75
+ const Float8_e5m2& b) {
76
+ a = a - b;
77
+ return a;
78
+ }
79
+
80
+ inline C10_HOST_DEVICE Float8_e5m2& operator*=(
81
+ Float8_e5m2& a,
82
+ const Float8_e5m2& b) {
83
+ a = a * b;
84
+ return a;
85
+ }
86
+
87
+ inline C10_HOST_DEVICE Float8_e5m2& operator/=(
88
+ Float8_e5m2& a,
89
+ const Float8_e5m2& b) {
90
+ a = a / b;
91
+ return a;
92
+ }
93
+
94
+ /// Arithmetic with floats
95
+
96
+ inline C10_HOST_DEVICE float operator+(Float8_e5m2 a, float b) {
97
+ return static_cast<float>(a) + b;
98
+ }
99
+ inline C10_HOST_DEVICE float operator-(Float8_e5m2 a, float b) {
100
+ return static_cast<float>(a) - b;
101
+ }
102
+ inline C10_HOST_DEVICE float operator*(Float8_e5m2 a, float b) {
103
+ return static_cast<float>(a) * b;
104
+ }
105
+ inline C10_HOST_DEVICE float operator/(Float8_e5m2 a, float b)
106
+ __ubsan_ignore_float_divide_by_zero__ {
107
+ return static_cast<float>(a) / b;
108
+ }
109
+
110
+ inline C10_HOST_DEVICE float operator+(float a, Float8_e5m2 b) {
111
+ return a + static_cast<float>(b);
112
+ }
113
+ inline C10_HOST_DEVICE float operator-(float a, Float8_e5m2 b) {
114
+ return a - static_cast<float>(b);
115
+ }
116
+ inline C10_HOST_DEVICE float operator*(float a, Float8_e5m2 b) {
117
+ return a * static_cast<float>(b);
118
+ }
119
+ inline C10_HOST_DEVICE float operator/(float a, Float8_e5m2 b)
120
+ __ubsan_ignore_float_divide_by_zero__ {
121
+ return a / static_cast<float>(b);
122
+ }
123
+
124
+ inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e5m2& b) {
125
+ return a += static_cast<float>(b);
126
+ }
127
+ inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e5m2& b) {
128
+ return a -= static_cast<float>(b);
129
+ }
130
+ inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e5m2& b) {
131
+ return a *= static_cast<float>(b);
132
+ }
133
+ inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e5m2& b) {
134
+ return a /= static_cast<float>(b);
135
+ }
136
+
137
+ /// Arithmetic with doubles
138
+
139
+ inline C10_HOST_DEVICE double operator+(Float8_e5m2 a, double b) {
140
+ return static_cast<double>(a) + b;
141
+ }
142
+ inline C10_HOST_DEVICE double operator-(Float8_e5m2 a, double b) {
143
+ return static_cast<double>(a) - b;
144
+ }
145
+ inline C10_HOST_DEVICE double operator*(Float8_e5m2 a, double b) {
146
+ return static_cast<double>(a) * b;
147
+ }
148
+ inline C10_HOST_DEVICE double operator/(Float8_e5m2 a, double b)
149
+ __ubsan_ignore_float_divide_by_zero__ {
150
+ return static_cast<double>(a) / b;
151
+ }
152
+
153
+ inline C10_HOST_DEVICE double operator+(double a, Float8_e5m2 b) {
154
+ return a + static_cast<double>(b);
155
+ }
156
+ inline C10_HOST_DEVICE double operator-(double a, Float8_e5m2 b) {
157
+ return a - static_cast<double>(b);
158
+ }
159
+ inline C10_HOST_DEVICE double operator*(double a, Float8_e5m2 b) {
160
+ return a * static_cast<double>(b);
161
+ }
162
+ inline C10_HOST_DEVICE double operator/(double a, Float8_e5m2 b)
163
+ __ubsan_ignore_float_divide_by_zero__ {
164
+ return a / static_cast<double>(b);
165
+ }
166
+
167
+ /// Arithmetic with ints
168
+
169
+ inline C10_HOST_DEVICE Float8_e5m2 operator+(Float8_e5m2 a, int b) {
170
+ return a + static_cast<Float8_e5m2>(b);
171
+ }
172
+ inline C10_HOST_DEVICE Float8_e5m2 operator-(Float8_e5m2 a, int b) {
173
+ return a - static_cast<Float8_e5m2>(b);
174
+ }
175
+ inline C10_HOST_DEVICE Float8_e5m2 operator*(Float8_e5m2 a, int b) {
176
+ return a * static_cast<Float8_e5m2>(b);
177
+ }
178
+ inline C10_HOST_DEVICE Float8_e5m2 operator/(Float8_e5m2 a, int b) {
179
+ return a / static_cast<Float8_e5m2>(b);
180
+ }
181
+
182
+ inline C10_HOST_DEVICE Float8_e5m2 operator+(int a, Float8_e5m2 b) {
183
+ return static_cast<Float8_e5m2>(a) + b;
184
+ }
185
+ inline C10_HOST_DEVICE Float8_e5m2 operator-(int a, Float8_e5m2 b) {
186
+ return static_cast<Float8_e5m2>(a) - b;
187
+ }
188
+ inline C10_HOST_DEVICE Float8_e5m2 operator*(int a, Float8_e5m2 b) {
189
+ return static_cast<Float8_e5m2>(a) * b;
190
+ }
191
+ inline C10_HOST_DEVICE Float8_e5m2 operator/(int a, Float8_e5m2 b) {
192
+ return static_cast<Float8_e5m2>(a) / b;
193
+ }
194
+
195
+ //// Arithmetic with int64_t
196
+
197
+ inline C10_HOST_DEVICE Float8_e5m2 operator+(Float8_e5m2 a, int64_t b) {
198
+ return a + static_cast<Float8_e5m2>(b);
199
+ }
200
+ inline C10_HOST_DEVICE Float8_e5m2 operator-(Float8_e5m2 a, int64_t b) {
201
+ return a - static_cast<Float8_e5m2>(b);
202
+ }
203
+ inline C10_HOST_DEVICE Float8_e5m2 operator*(Float8_e5m2 a, int64_t b) {
204
+ return a * static_cast<Float8_e5m2>(b);
205
+ }
206
+ inline C10_HOST_DEVICE Float8_e5m2 operator/(Float8_e5m2 a, int64_t b) {
207
+ return a / static_cast<Float8_e5m2>(b);
208
+ }
209
+
210
+ inline C10_HOST_DEVICE Float8_e5m2 operator+(int64_t a, Float8_e5m2 b) {
211
+ return static_cast<Float8_e5m2>(a) + b;
212
+ }
213
+ inline C10_HOST_DEVICE Float8_e5m2 operator-(int64_t a, Float8_e5m2 b) {
214
+ return static_cast<Float8_e5m2>(a) - b;
215
+ }
216
+ inline C10_HOST_DEVICE Float8_e5m2 operator*(int64_t a, Float8_e5m2 b) {
217
+ return static_cast<Float8_e5m2>(a) * b;
218
+ }
219
+ inline C10_HOST_DEVICE Float8_e5m2 operator/(int64_t a, Float8_e5m2 b) {
220
+ return static_cast<Float8_e5m2>(a) / b;
221
+ }
222
+
223
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
224
+ /// conversion from c10::Float8_e5m2 to float.
225
+
226
+ } // namespace c10
227
+
228
+ namespace std {
229
+
230
+ template <>
231
+ class numeric_limits<c10::Float8_e5m2> {
232
+ public:
233
+ static constexpr bool is_signed = true;
234
+ static constexpr bool is_integer = false;
235
+ static constexpr bool is_specialized = true;
236
+ static constexpr bool is_exact = false;
237
+ static constexpr bool has_infinity = true;
238
+ static constexpr bool has_quiet_NaN = true;
239
+ static constexpr bool has_signaling_NaN = false;
240
+ static constexpr auto has_denorm = true;
241
+ static constexpr auto has_denorm_loss = true;
242
+ static constexpr auto round_style = numeric_limits<float>::round_style;
243
+ static constexpr bool is_iec559 = false;
244
+ static constexpr bool is_bounded = true;
245
+ static constexpr bool is_modulo = false;
246
+ static constexpr int digits = 3;
247
+ static constexpr int digits10 = 0;
248
+ static constexpr int max_digits10 = 2;
249
+ static constexpr int radix = 2;
250
+ static constexpr int min_exponent = -13;
251
+ static constexpr int min_exponent10 = -4;
252
+ static constexpr int max_exponent = 16;
253
+ static constexpr int max_exponent10 = 4;
254
+ static constexpr auto traps = numeric_limits<float>::traps;
255
+ static constexpr auto tinyness_before =
256
+ numeric_limits<float>::tinyness_before;
257
+
258
+ static constexpr c10::Float8_e5m2 min() {
259
+ return c10::Float8_e5m2(0x4, c10::Float8_e5m2::from_bits());
260
+ }
261
+ static constexpr c10::Float8_e5m2 max() {
262
+ return c10::Float8_e5m2(0x7B, c10::Float8_e5m2::from_bits());
263
+ }
264
+ static constexpr c10::Float8_e5m2 lowest() {
265
+ return c10::Float8_e5m2(0xFB, c10::Float8_e5m2::from_bits());
266
+ }
267
+ static constexpr c10::Float8_e5m2 epsilon() {
268
+ return c10::Float8_e5m2(0x34, c10::Float8_e5m2::from_bits());
269
+ }
270
+ static constexpr c10::Float8_e5m2 round_error() {
271
+ return c10::Float8_e5m2(0x38, c10::Float8_e5m2::from_bits());
272
+ }
273
+ static constexpr c10::Float8_e5m2 infinity() {
274
+ return c10::Float8_e5m2(0x7C, c10::Float8_e5m2::from_bits());
275
+ }
276
+ static constexpr c10::Float8_e5m2 quiet_NaN() {
277
+ return c10::Float8_e5m2(0x7F, c10::Float8_e5m2::from_bits());
278
+ }
279
+ static constexpr c10::Float8_e5m2 denorm_min() {
280
+ return c10::Float8_e5m2(0x01, c10::Float8_e5m2::from_bits());
281
+ }
282
+ };
283
+
284
+ } // namespace std
285
+
286
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2.h ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Float8_e5m2 type (8-bit floating-point) including conversions
4
+ /// to standard C types and basic arithmetic operations. Note that arithmetic
5
+ /// operations are implemented by converting to floating point and
6
+ /// performing the operation in float32.
7
+ /// Binary configuration:
8
+ /// s eeeee mm
9
+ /// 1 sign bit
10
+ /// 5 exponent bits
11
+ /// 2 mantissa bits
12
+ /// bias = 15
13
+ ///
14
+ /// Implementation based on the paper https://arxiv.org/pdf/2209.05433.pdf
15
+ /// and inspired by Half implementation from pytorch/c10/util/Half.h
16
+
17
+ #include <c10/util/Half.h>
18
+
19
+ namespace c10 {
20
+
21
+ namespace detail {
22
+
23
+ /*
24
+ * Convert a 8-bit floating-point number in fp8 E5M2 format, in bit
25
+ * representation, to a 32-bit floating-point number in IEEE single-precision
26
+ * format, in bit representation.
27
+ *
28
+ * @note The implementation doesn't use any floating-point operations.
29
+ */
30
+ inline C10_HOST_DEVICE float fp8e5m2_to_fp32_value(uint8_t input) {
31
+ /*
32
+ * Extend the fp8 E5M2 number to 32 bits and shift to the
33
+ * upper part of the 32-bit word:
34
+ * +---+----+---+-----------------------------+
35
+ * | S |EEEEE|MM|0000 0000 0000 0000 0000 0000|
36
+ * +---+----+---+-----------------------------+
37
+ * Bits 31 26-30 24-25 0-23
38
+ *
39
+ * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
40
+ * - zero bits.
41
+ */
42
+ uint16_t half_representation = input;
43
+ half_representation <<= 8;
44
+ return fp16_ieee_to_fp32_value(half_representation);
45
+ }
46
+
47
+ /*
48
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
49
+ * 8-bit floating-point number in fp8 E5M2 format, in bit representation.
50
+ */
51
+ inline C10_HOST_DEVICE uint8_t fp8e5m2_from_fp32_value(float f) {
52
+ /*
53
+ * Binary representation of fp32 infinity
54
+ * 0 11111111 00000000000000000000000
55
+ */
56
+ constexpr uint32_t fp32_inf = UINT32_C(255) << 23;
57
+
58
+ /*
59
+ * Binary representation of 65536.0f, which is the first value
60
+ * not representable in fp8e5m2 range:
61
+ * 0 11111 00 - fp8e5m2
62
+ * 0 10001111 00000000000000000000000 - fp32
63
+ */
64
+ constexpr uint32_t fp8_max = UINT32_C(143) << 23;
65
+
66
+ /*
67
+ * A mask for converting fp32 numbers lower than fp8e5m2 normal range
68
+ * into denorm representation
69
+ * magic number: ((127 - 15) + (23 - 2) + 1)
70
+ */
71
+ constexpr uint32_t denorm_mask = UINT32_C(134) << 23;
72
+
73
+ uint32_t f_bits = fp32_to_bits(f);
74
+ uint8_t result = 0u;
75
+
76
+ /*
77
+ * Extract the sign of the input number into the high bit of the 32-bit word:
78
+ *
79
+ * +---+----------------------------------+
80
+ * | S |0000000 00000000 00000000 00000000|
81
+ * +---+----------------------------------+
82
+ * Bits 31 0-31
83
+ */
84
+ const uint32_t sign = f_bits & UINT32_C(0x80000000);
85
+
86
+ /*
87
+ * Set sign bit to 0
88
+ */
89
+ f_bits ^= sign;
90
+
91
+ if (f_bits >= fp8_max) {
92
+ // NaN - all exponent and mantissa bits set to 1
93
+ result = f_bits > fp32_inf ? UINT8_C(0x7F) : UINT8_C(0x7C);
94
+ } else {
95
+ if (f_bits < (UINT32_C(113) << 23)) {
96
+ // Input number is smaller than 2^(-14), which is the smallest
97
+ // fp8e5m2 normal number
98
+ f_bits =
99
+ fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask));
100
+ result = static_cast<uint8_t>(f_bits - denorm_mask);
101
+ } else {
102
+ // resulting mantissa is odd
103
+ uint32_t mant_odd = (f_bits >> 21) & 1;
104
+
105
+ // update exponent, rounding bias part 1
106
+ f_bits += ((uint32_t)(15 - 127) << 23) + 0xFFFFF;
107
+
108
+ // rounding bias part 2
109
+ f_bits += mant_odd;
110
+
111
+ // take the bits!
112
+ result = static_cast<uint8_t>(f_bits >> 21);
113
+ }
114
+ }
115
+
116
+ result |= static_cast<uint8_t>(sign >> 24);
117
+ return result;
118
+ }
119
+
120
+ } // namespace detail
121
+
122
+ struct alignas(1) Float8_e5m2 {
123
+ uint8_t x;
124
+
125
+ struct from_bits_t {};
126
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
127
+ return from_bits_t();
128
+ }
129
+
130
+ Float8_e5m2() = default;
131
+
132
+ constexpr C10_HOST_DEVICE Float8_e5m2(uint8_t bits, from_bits_t) : x(bits) {}
133
+ inline C10_HOST_DEVICE Float8_e5m2(float value);
134
+ inline C10_HOST_DEVICE operator float() const;
135
+ inline C10_HOST_DEVICE bool isnan() const;
136
+ inline C10_HOST_DEVICE bool isinf() const;
137
+ };
138
+
139
+ C10_API inline std::ostream& operator<<(
140
+ std::ostream& out,
141
+ const Float8_e5m2& value) {
142
+ out << (float)value;
143
+ return out;
144
+ }
145
+
146
+ } // namespace c10
147
+
148
+ #include <c10/util/Float8_e5m2-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2fnuz-inl.h ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/Float8_fnuz_cvt.h>
5
+ #include <cstring>
6
+ #include <limits>
7
+
8
+ C10_CLANG_DIAGNOSTIC_PUSH()
9
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
10
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
11
+ #endif
12
+
13
+ namespace c10 {
14
+
15
+ /// Constructors
16
+
17
+ inline C10_HOST_DEVICE Float8_e5m2fnuz::Float8_e5m2fnuz(float value)
18
+ : x(detail::fp8e5m2fnuz_from_fp32_value(value)) {}
19
+
20
+ /// Implicit conversions
21
+
22
+ inline C10_HOST_DEVICE Float8_e5m2fnuz::operator float() const {
23
+ return detail::fp8_fnuz_to_fp32_value<5, 2>(x);
24
+ }
25
+
26
+ /// Special values helpers
27
+
28
+ inline C10_HOST_DEVICE bool Float8_e5m2fnuz::isnan() const {
29
+ return x == 0b10000000;
30
+ }
31
+
32
+ inline C10_HOST_DEVICE bool Float8_e5m2fnuz::isinf() const {
33
+ return false;
34
+ }
35
+
36
+ /// Arithmetic
37
+
38
+ inline C10_HOST_DEVICE Float8_e5m2fnuz
39
+ operator+(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) {
40
+ return static_cast<float>(a) + static_cast<float>(b);
41
+ }
42
+
43
+ inline C10_HOST_DEVICE Float8_e5m2fnuz
44
+ operator-(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) {
45
+ return static_cast<float>(a) - static_cast<float>(b);
46
+ }
47
+
48
+ inline C10_HOST_DEVICE Float8_e5m2fnuz
49
+ operator*(const Float8_e5m2fnuz& a, const Float8_e5m2fnuz& b) {
50
+ return static_cast<float>(a) * static_cast<float>(b);
51
+ }
52
+
53
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(
54
+ const Float8_e5m2fnuz& a,
55
+ const Float8_e5m2fnuz& b) __ubsan_ignore_float_divide_by_zero__ {
56
+ return static_cast<float>(a) / static_cast<float>(b);
57
+ }
58
+
59
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(const Float8_e5m2fnuz& a) {
60
+ return -static_cast<float>(a);
61
+ }
62
+
63
+ inline C10_HOST_DEVICE Float8_e5m2fnuz& operator+=(
64
+ Float8_e5m2fnuz& a,
65
+ const Float8_e5m2fnuz& b) {
66
+ a = a + b;
67
+ return a;
68
+ }
69
+
70
+ inline C10_HOST_DEVICE Float8_e5m2fnuz& operator-=(
71
+ Float8_e5m2fnuz& a,
72
+ const Float8_e5m2fnuz& b) {
73
+ a = a - b;
74
+ return a;
75
+ }
76
+
77
+ inline C10_HOST_DEVICE Float8_e5m2fnuz& operator*=(
78
+ Float8_e5m2fnuz& a,
79
+ const Float8_e5m2fnuz& b) {
80
+ a = a * b;
81
+ return a;
82
+ }
83
+
84
+ inline C10_HOST_DEVICE Float8_e5m2fnuz& operator/=(
85
+ Float8_e5m2fnuz& a,
86
+ const Float8_e5m2fnuz& b) {
87
+ a = a / b;
88
+ return a;
89
+ }
90
+
91
+ /// Arithmetic with floats
92
+
93
+ inline C10_HOST_DEVICE float operator+(Float8_e5m2fnuz a, float b) {
94
+ return static_cast<float>(a) + b;
95
+ }
96
+ inline C10_HOST_DEVICE float operator-(Float8_e5m2fnuz a, float b) {
97
+ return static_cast<float>(a) - b;
98
+ }
99
+ inline C10_HOST_DEVICE float operator*(Float8_e5m2fnuz a, float b) {
100
+ return static_cast<float>(a) * b;
101
+ }
102
+ inline C10_HOST_DEVICE float operator/(Float8_e5m2fnuz a, float b)
103
+ __ubsan_ignore_float_divide_by_zero__ {
104
+ return static_cast<float>(a) / b;
105
+ }
106
+
107
+ inline C10_HOST_DEVICE float operator+(float a, Float8_e5m2fnuz b) {
108
+ return a + static_cast<float>(b);
109
+ }
110
+ inline C10_HOST_DEVICE float operator-(float a, Float8_e5m2fnuz b) {
111
+ return a - static_cast<float>(b);
112
+ }
113
+ inline C10_HOST_DEVICE float operator*(float a, Float8_e5m2fnuz b) {
114
+ return a * static_cast<float>(b);
115
+ }
116
+ inline C10_HOST_DEVICE float operator/(float a, Float8_e5m2fnuz b)
117
+ __ubsan_ignore_float_divide_by_zero__ {
118
+ return a / static_cast<float>(b);
119
+ }
120
+
121
+ inline C10_HOST_DEVICE float& operator+=(float& a, const Float8_e5m2fnuz& b) {
122
+ return a += static_cast<float>(b);
123
+ }
124
+ inline C10_HOST_DEVICE float& operator-=(float& a, const Float8_e5m2fnuz& b) {
125
+ return a -= static_cast<float>(b);
126
+ }
127
+ inline C10_HOST_DEVICE float& operator*=(float& a, const Float8_e5m2fnuz& b) {
128
+ return a *= static_cast<float>(b);
129
+ }
130
+ inline C10_HOST_DEVICE float& operator/=(float& a, const Float8_e5m2fnuz& b) {
131
+ return a /= static_cast<float>(b);
132
+ }
133
+
134
+ /// Arithmetic with doubles
135
+
136
+ inline C10_HOST_DEVICE double operator+(Float8_e5m2fnuz a, double b) {
137
+ return static_cast<double>(a) + b;
138
+ }
139
+ inline C10_HOST_DEVICE double operator-(Float8_e5m2fnuz a, double b) {
140
+ return static_cast<double>(a) - b;
141
+ }
142
+ inline C10_HOST_DEVICE double operator*(Float8_e5m2fnuz a, double b) {
143
+ return static_cast<double>(a) * b;
144
+ }
145
+ inline C10_HOST_DEVICE double operator/(Float8_e5m2fnuz a, double b)
146
+ __ubsan_ignore_float_divide_by_zero__ {
147
+ return static_cast<double>(a) / b;
148
+ }
149
+
150
+ inline C10_HOST_DEVICE double operator+(double a, Float8_e5m2fnuz b) {
151
+ return a + static_cast<double>(b);
152
+ }
153
+ inline C10_HOST_DEVICE double operator-(double a, Float8_e5m2fnuz b) {
154
+ return a - static_cast<double>(b);
155
+ }
156
+ inline C10_HOST_DEVICE double operator*(double a, Float8_e5m2fnuz b) {
157
+ return a * static_cast<double>(b);
158
+ }
159
+ inline C10_HOST_DEVICE double operator/(double a, Float8_e5m2fnuz b)
160
+ __ubsan_ignore_float_divide_by_zero__ {
161
+ return a / static_cast<double>(b);
162
+ }
163
+
164
+ /// Arithmetic with ints
165
+
166
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(Float8_e5m2fnuz a, int b) {
167
+ return a + static_cast<Float8_e5m2fnuz>(b);
168
+ }
169
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(Float8_e5m2fnuz a, int b) {
170
+ return a - static_cast<Float8_e5m2fnuz>(b);
171
+ }
172
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(Float8_e5m2fnuz a, int b) {
173
+ return a * static_cast<Float8_e5m2fnuz>(b);
174
+ }
175
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(Float8_e5m2fnuz a, int b) {
176
+ return a / static_cast<Float8_e5m2fnuz>(b);
177
+ }
178
+
179
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(int a, Float8_e5m2fnuz b) {
180
+ return static_cast<Float8_e5m2fnuz>(a) + b;
181
+ }
182
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(int a, Float8_e5m2fnuz b) {
183
+ return static_cast<Float8_e5m2fnuz>(a) - b;
184
+ }
185
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(int a, Float8_e5m2fnuz b) {
186
+ return static_cast<Float8_e5m2fnuz>(a) * b;
187
+ }
188
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(int a, Float8_e5m2fnuz b) {
189
+ return static_cast<Float8_e5m2fnuz>(a) / b;
190
+ }
191
+
192
+ //// Arithmetic with int64_t
193
+
194
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(Float8_e5m2fnuz a, int64_t b) {
195
+ return a + static_cast<Float8_e5m2fnuz>(b);
196
+ }
197
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(Float8_e5m2fnuz a, int64_t b) {
198
+ return a - static_cast<Float8_e5m2fnuz>(b);
199
+ }
200
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(Float8_e5m2fnuz a, int64_t b) {
201
+ return a * static_cast<Float8_e5m2fnuz>(b);
202
+ }
203
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(Float8_e5m2fnuz a, int64_t b) {
204
+ return a / static_cast<Float8_e5m2fnuz>(b);
205
+ }
206
+
207
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator+(int64_t a, Float8_e5m2fnuz b) {
208
+ return static_cast<Float8_e5m2fnuz>(a) + b;
209
+ }
210
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator-(int64_t a, Float8_e5m2fnuz b) {
211
+ return static_cast<Float8_e5m2fnuz>(a) - b;
212
+ }
213
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator*(int64_t a, Float8_e5m2fnuz b) {
214
+ return static_cast<Float8_e5m2fnuz>(a) * b;
215
+ }
216
+ inline C10_HOST_DEVICE Float8_e5m2fnuz operator/(int64_t a, Float8_e5m2fnuz b) {
217
+ return static_cast<Float8_e5m2fnuz>(a) / b;
218
+ }
219
+
220
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
221
+ /// conversion from c10::Float8_e5m2fnuz to float.
222
+
223
+ } // namespace c10
224
+
225
+ namespace std {
226
+
227
+ template <>
228
+ class numeric_limits<c10::Float8_e5m2fnuz> {
229
+ public:
230
+ static constexpr bool is_signed = true;
231
+ static constexpr bool is_integer = false;
232
+ static constexpr bool is_specialized = true;
233
+ static constexpr bool is_exact = false;
234
+ static constexpr bool has_infinity = false;
235
+ static constexpr bool has_quiet_NaN = true;
236
+ static constexpr bool has_signaling_NaN = false;
237
+ static constexpr auto has_denorm = true;
238
+ static constexpr auto has_denorm_loss = true;
239
+ static constexpr auto round_style = numeric_limits<float>::round_style;
240
+ static constexpr bool is_iec559 = false;
241
+ static constexpr bool is_bounded = true;
242
+ static constexpr bool is_modulo = false;
243
+ static constexpr int digits = 3;
244
+ static constexpr int digits10 = 0;
245
+ static constexpr int max_digits10 = 2;
246
+ static constexpr int radix = 2;
247
+ static constexpr int min_exponent = -14;
248
+ static constexpr int min_exponent10 = -4;
249
+ static constexpr int max_exponent = 16;
250
+ static constexpr int max_exponent10 = 4;
251
+ static constexpr auto traps = numeric_limits<float>::traps;
252
+ static constexpr auto tinyness_before =
253
+ numeric_limits<float>::tinyness_before;
254
+
255
+ static constexpr c10::Float8_e5m2fnuz min() {
256
+ return c10::Float8_e5m2fnuz(0x04, c10::Float8_e5m2fnuz::from_bits());
257
+ }
258
+ static constexpr c10::Float8_e5m2fnuz max() {
259
+ return c10::Float8_e5m2fnuz(0x7F, c10::Float8_e5m2fnuz::from_bits());
260
+ }
261
+ static constexpr c10::Float8_e5m2fnuz lowest() {
262
+ return c10::Float8_e5m2fnuz(0xFF, c10::Float8_e5m2fnuz::from_bits());
263
+ }
264
+ static constexpr c10::Float8_e5m2fnuz epsilon() {
265
+ return c10::Float8_e5m2fnuz(0x34, c10::Float8_e5m2fnuz::from_bits());
266
+ }
267
+ static constexpr c10::Float8_e5m2fnuz round_error() {
268
+ return c10::Float8_e5m2fnuz(0x38, c10::Float8_e5m2fnuz::from_bits());
269
+ }
270
+ static constexpr c10::Float8_e5m2fnuz infinity() {
271
+ return c10::Float8_e5m2fnuz(0x80, c10::Float8_e5m2fnuz::from_bits());
272
+ }
273
+ // TODO(future): we are mapping neg_zero to both inf and NaN, this is
274
+ // surprising and we should figure out what to do about it.
275
+ static constexpr c10::Float8_e5m2fnuz quiet_NaN() {
276
+ return c10::Float8_e5m2fnuz(0x80, c10::Float8_e5m2fnuz::from_bits());
277
+ }
278
+ static constexpr c10::Float8_e5m2fnuz denorm_min() {
279
+ return c10::Float8_e5m2fnuz(0x01, c10::Float8_e5m2fnuz::from_bits());
280
+ }
281
+ };
282
+
283
+ } // namespace std
284
+
285
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e5m2fnuz.h ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Float8_e5m2fnuz type (8-bit floating-point) including
4
+ /// conversions to standard C types and basic arithmetic operations. Note that
5
+ /// arithmetic operations are implemented by converting to floating point and
6
+ /// performing the operation in float32.
7
+ /// Binary configuration remains the same as e5m2:
8
+ /// s eeeee mm
9
+ /// 1 sign bit
10
+ /// 5 exponent bits
11
+ /// 2 mantissa bits
12
+ /// The key differences that e5m2fnuz brings are:
13
+ /// bias = 16
14
+ /// no infinities or negative zero
15
+ /// NaN only when sign bit is 1, rest all 0s
16
+ ///
17
+ /// Implementation based on the paper https://arxiv.org/pdf/2206.02915.pdf and
18
+ /// the existing Float8_e4m3fn implementation.
19
+
20
+ #include <c10/macros/Macros.h>
21
+ #include <c10/util/TypeSafeSignMath.h>
22
+ #include <c10/util/floating_point_utils.h>
23
+
24
+ #if defined(__cplusplus)
25
+ #include <cstdint>
26
+ #elif !defined(__OPENCL_VERSION__)
27
+ #include <math.h>
28
+ #include <stdint.h>
29
+ #endif
30
+
31
+ #include <iosfwd>
32
+ #include <ostream>
33
+
34
+ namespace c10 {
35
+
36
+ namespace detail {
37
+
38
+ /*
39
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
40
+ * 8-bit floating-point number in fp8 E5M2 format, in bit representation.
41
+ */
42
+ inline C10_HOST_DEVICE uint8_t fp8e5m2fnuz_from_fp32_value(float f) {
43
+ /*
44
+ * Binary representation of 65536.0f, which is the first value not
45
+ * representable (i.e. the first value which would overflow in to the sign
46
+ * bit, resulting in a NaN) in fp8e4m3fnuz range:
47
+ * 1 00000 00 - fp8e5m2fnuz
48
+ * 0 10001111 00000000000000000000000 - fp32
49
+ */
50
+ constexpr uint32_t fnuz_max = UINT32_C(0x8F) << 23;
51
+
52
+ /*
53
+ * A mask for converting fp32 numbers lower than fp8e5m2fnuz normal range
54
+ * into denormalized representation.
55
+ * magic number: ((127 - 16) + (23 - 2) + 1)
56
+ */
57
+ constexpr uint32_t denorm_mask = UINT32_C(0x85) << 23;
58
+
59
+ uint32_t f_bits = fp32_to_bits(f);
60
+ uint32_t result = 0u;
61
+
62
+ /*
63
+ * Extract the sign of the input number into the high bit of the 32-bit word:
64
+ *
65
+ * +---+----------------------------------+
66
+ * | S |0000000 00000000 00000000 00000000|
67
+ * +---+----------------------------------+
68
+ * Bits 31 0-31
69
+ */
70
+ const uint32_t sign = f_bits & UINT32_C(0x80000000);
71
+
72
+ /*
73
+ * Set sign bit to 0
74
+ */
75
+ f_bits ^= sign;
76
+
77
+ if (f_bits >= fnuz_max) {
78
+ // NaN -- sign bit set to 1, rest 0s
79
+ return 0x80;
80
+ }
81
+
82
+ if (f_bits < (UINT32_C(0x70) << 23) /* 2^-15 in float32 */) {
83
+ // Input exponent is less than -15, the smallest e5m2fnuz exponent, so the
84
+ // number will become subnormal.
85
+ f_bits = fp32_to_bits(fp32_from_bits(f_bits) + fp32_from_bits(denorm_mask));
86
+ result = static_cast<uint8_t>(f_bits - denorm_mask);
87
+ if (result == 0) {
88
+ // fnuz types don't have negative zero.
89
+ return 0;
90
+ }
91
+ } else {
92
+ // resulting mantissa is odd
93
+ uint8_t mant_odd = (f_bits >> 21) & 1;
94
+
95
+ // update exponent, rounding bias part 1
96
+ f_bits += ((uint32_t)(16 - 127) << 23) + 0xFFFFF;
97
+
98
+ // rounding bias part 2
99
+ f_bits += mant_odd;
100
+
101
+ // take the bits!
102
+ result = static_cast<uint8_t>(f_bits >> 21);
103
+ }
104
+
105
+ result |= sign >> 24;
106
+ return result;
107
+ }
108
+
109
+ } // namespace detail
110
+
111
+ struct alignas(1) Float8_e5m2fnuz {
112
+ uint8_t x;
113
+
114
+ struct from_bits_t {};
115
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
116
+ return from_bits_t();
117
+ }
118
+
119
+ Float8_e5m2fnuz() = default;
120
+
121
+ constexpr C10_HOST_DEVICE Float8_e5m2fnuz(uint8_t bits, from_bits_t)
122
+ : x(bits) {}
123
+ inline C10_HOST_DEVICE Float8_e5m2fnuz(float value);
124
+ inline C10_HOST_DEVICE operator float() const;
125
+ inline C10_HOST_DEVICE bool isnan() const;
126
+ inline C10_HOST_DEVICE bool isinf() const;
127
+ };
128
+
129
+ C10_API inline std::ostream& operator<<(
130
+ std::ostream& out,
131
+ const Float8_e5m2fnuz& value) {
132
+ out << (float)value;
133
+ return out;
134
+ }
135
+
136
+ } // namespace c10
137
+
138
+ #include <c10/util/Float8_e5m2fnuz-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e8m0fnu-inl.h ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/floating_point_utils.h>
5
+ #include <cstring>
6
+ #include <limits>
7
+
8
+ // TODO(#146647): Can we remove the below warning?
9
+ C10_CLANG_DIAGNOSTIC_PUSH()
10
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
11
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
12
+ #endif
13
+
14
+ namespace c10 {
15
+
16
+ /// Constructors
17
+
18
+ inline C10_HOST_DEVICE Float8_e8m0fnu::Float8_e8m0fnu(float value)
19
+ : x(detail::fp8e8m0fnu_from_fp32_value(value)) {}
20
+
21
+ /// Implicit conversions
22
+
23
+ inline C10_HOST_DEVICE Float8_e8m0fnu::operator float() const {
24
+ // TODO(#146647): maybe rewrite without control flow
25
+
26
+ // if exponent is zero, need to special case to return 2^-127 instead of zero
27
+ if (x == 0) {
28
+ return c10::detail::fp32_from_bits(0x00400000);
29
+ }
30
+
31
+ // if exponent is NaN, need to special case to return properly encoded NaN
32
+ if (isnan()) {
33
+ return c10::detail::fp32_from_bits(0x7f800001);
34
+ }
35
+
36
+ // leave sign at 0, set the exponent bits, leave stored mantissa at 0
37
+ uint32_t res = x << 23;
38
+
39
+ return c10::detail::fp32_from_bits(res);
40
+ }
41
+
42
+ /// Special values helper
43
+
44
+ inline C10_HOST_DEVICE bool Float8_e8m0fnu::isnan() const {
45
+ return x == 0b11111111;
46
+ }
47
+
48
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
49
+ /// conversion from c10::Float8_e8m0fnu to float.
50
+
51
+ } // namespace c10
52
+
53
+ namespace std {
54
+
55
+ template <>
56
+ class numeric_limits<c10::Float8_e8m0fnu> {
57
+ public:
58
+ static constexpr bool is_specialized = true;
59
+ static constexpr bool is_signed = false;
60
+ static constexpr bool is_integer = false;
61
+ static constexpr bool is_exact = false;
62
+ static constexpr bool has_infinity = false;
63
+ static constexpr bool has_quiet_NaN = true;
64
+ static constexpr bool has_signaling_NaN = false;
65
+ static constexpr auto has_denorm = false;
66
+ static constexpr auto has_denorm_loss = false;
67
+ static constexpr auto round_style = numeric_limits<float>::round_style;
68
+ static constexpr bool is_iec559 = false;
69
+ static constexpr bool is_bounded = true;
70
+ static constexpr bool is_modulo = false;
71
+ static constexpr int digits = 1;
72
+ static constexpr int digits10 = 0;
73
+ static constexpr int max_digits10 = 1; // just a 2!
74
+ static constexpr int radix = 2;
75
+ static constexpr int min_exponent = -126;
76
+ static constexpr int min_exponent10 = -38;
77
+ static constexpr int max_exponent = 128;
78
+ static constexpr int max_exponent10 = 38;
79
+ static constexpr auto traps = numeric_limits<float>::traps;
80
+ static constexpr auto tinyness_before = false;
81
+
82
+ static constexpr c10::Float8_e8m0fnu min() {
83
+ // 2^-127
84
+ return c10::Float8_e8m0fnu(0b00000000, c10::Float8_e8m0fnu::from_bits());
85
+ }
86
+ static constexpr c10::Float8_e8m0fnu lowest() {
87
+ // 2^-127
88
+ return c10::Float8_e8m0fnu(0b00000000, c10::Float8_e8m0fnu::from_bits());
89
+ }
90
+ static constexpr c10::Float8_e8m0fnu max() {
91
+ // 254 biased, which is 127 unbiased, so 2^127
92
+ return c10::Float8_e8m0fnu(0b11111110, c10::Float8_e8m0fnu::from_bits());
93
+ }
94
+ static constexpr c10::Float8_e8m0fnu epsilon() {
95
+ // according to https://en.cppreference.com/w/cpp/types/numeric_limits, this
96
+ // is "the difference between 1.0 and the next representable value of the
97
+ // given floating-point type". The next representable value is 2.0, so the
98
+ // difference is 1.0 which is 2^0. 0 unbiased is 127 biased.
99
+ return c10::Float8_e8m0fnu(0b01111111, c10::Float8_e8m0fnu::from_bits());
100
+ }
101
+ static constexpr c10::Float8_e8m0fnu round_error() {
102
+ // 0.5 in float, which is 2^-1, and -1 + 127 = 126
103
+ return c10::Float8_e8m0fnu(0b01111110, c10::Float8_e8m0fnu::from_bits());
104
+ }
105
+ static constexpr c10::Float8_e8m0fnu quiet_NaN() {
106
+ return c10::Float8_e8m0fnu(0b11111111, c10::Float8_e8m0fnu::from_bits());
107
+ }
108
+ };
109
+
110
+ } // namespace std
111
+
112
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_e8m0fnu.h ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Float8_e8m0fnu type (8-bit floating-point) including
4
+ /// conversions to standard C types
5
+ /// Binary configuration :
6
+ /// eeeeeeee
7
+ /// no sign bits
8
+ /// 8 exponent bits
9
+ /// no mantissa bits
10
+ ///
11
+ /// This is the E8M0 dtype from the OCP MX format spec
12
+ /// (https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf,
13
+ /// Section 5.4.1)
14
+
15
+ #include <c10/macros/Export.h>
16
+ #include <c10/macros/Macros.h>
17
+ #include <c10/util/floating_point_utils.h>
18
+ #include <type_traits>
19
+
20
+ // TODO(#146647): do we need to special case OPENCL?
21
+ #if defined(__cplusplus)
22
+ #include <cstdint>
23
+ #elif !defined(__OPENCL_VERSION__)
24
+ #include <math.h>
25
+ #include <stdint.h>
26
+ #endif
27
+
28
+ #include <iosfwd>
29
+ #include <ostream>
30
+
31
+ namespace c10 {
32
+
33
+ namespace detail {
34
+
35
+ /*
36
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
37
+ * 8-bit floating-point number in fp8 e8m0fnu format, in bit representation.
38
+ */
39
+ inline C10_HOST_DEVICE uint8_t fp8e8m0fnu_from_fp32_value(float f) {
40
+ // TODO(#146647): maybe rewrite without control flow
41
+
42
+ uint32_t f_bits = c10::detail::fp32_to_bits(f);
43
+
44
+ // extract the exponent
45
+ uint32_t exponent = (f_bits >> 23) & 0b11111111;
46
+
47
+ // special case float32 NaN and +-inf to map to e8m0 nan
48
+ if (exponent == 0b11111111) {
49
+ return exponent;
50
+ }
51
+
52
+ // next, we use guard, round, sticky bits and the LSB to implement round to
53
+ // nearest, with ties to even
54
+
55
+ // guard bit - bit 23, or 22 zero-indexed
56
+ uint8_t g = (f_bits & 0x400000) > 0;
57
+ // round bit - bit 22, or 21 zero-indexed
58
+ uint8_t r = (f_bits & 0x200000) > 0;
59
+ // sticky bit - bits 21 to 1, or 20 to 0 zero-indexed
60
+ uint8_t s = (f_bits & 0x1FFFFF) > 0;
61
+ // in casting to e8m0, LSB is the implied mantissa bit. It equals to 0 if the
62
+ // original float32 is denormal, and to 1 if the original float32 is normal.
63
+ uint8_t lsb = exponent > 0;
64
+
65
+ // implement the RNE logic
66
+ bool round_up = false;
67
+
68
+ // if g == 0, round down (no-op)
69
+ if (g == 1) {
70
+ if ((r == 1) || (s == 1)) {
71
+ // round up
72
+ round_up = true;
73
+ } else {
74
+ if (lsb == 1) {
75
+ // round up
76
+ round_up = true;
77
+ }
78
+ // if lsb == 0, round down (no-op)
79
+ }
80
+ }
81
+
82
+ if (round_up) {
83
+ // adjust exponent
84
+ // note that if exponent was 255 we would have already returned earlier, so
85
+ // we know we can add one safely without running out of bounds
86
+ exponent++;
87
+ }
88
+
89
+ return exponent;
90
+ }
91
+
92
+ } // namespace detail
93
+
94
+ struct alignas(1) Float8_e8m0fnu {
95
+ uint8_t x;
96
+
97
+ struct from_bits_t {};
98
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
99
+ return from_bits_t();
100
+ }
101
+
102
+ Float8_e8m0fnu() = default;
103
+
104
+ constexpr C10_HOST_DEVICE Float8_e8m0fnu(uint8_t bits, from_bits_t)
105
+ : x(bits) {}
106
+ inline C10_HOST_DEVICE Float8_e8m0fnu(float value);
107
+ inline C10_HOST_DEVICE operator float() const;
108
+ inline C10_HOST_DEVICE bool isnan() const;
109
+ };
110
+
111
+ C10_API inline std::ostream& operator<<(
112
+ std::ostream& out,
113
+ const Float8_e8m0fnu& value) {
114
+ out << (float)value;
115
+ return out;
116
+ }
117
+
118
+ } // namespace c10
119
+
120
+ #include <c10/util/Float8_e8m0fnu-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Float8_fnuz_cvt.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/floating_point_utils.h>
4
+
5
+ #include <cstdint>
6
+
7
+ #if defined(SYCL_LANGUAGE_VERSION)
8
+ #include <sycl/sycl.hpp>
9
+ #endif
10
+
11
+ namespace c10::detail {
12
+
13
+ /*
14
+ * Convert a 8-bit floating-point number in either f8 E4M3FNUZ or bf8 E5M2FNUZ
15
+ * format, in bit representation, to a 32-bit floating-point number.
16
+ */
17
+ template <uint32_t we, uint32_t wm>
18
+ inline C10_HOST_DEVICE float fp8_fnuz_to_fp32_value(uint8_t x) {
19
+ static_assert((we == 4 && wm == 3) || (we == 5 && wm == 2));
20
+ constexpr uint32_t weo = 8;
21
+ constexpr uint32_t wmo = 23;
22
+
23
+ if (x == 0) {
24
+ return 0;
25
+ }
26
+
27
+ if (x == 0x80) {
28
+ constexpr uint32_t ifNaN = 0x7F800001;
29
+ return fp32_from_bits(ifNaN);
30
+ }
31
+
32
+ uint32_t mantissa = x & ((1 << wm) - 1);
33
+ uint32_t exponent = (x & 0x7F) >> wm;
34
+
35
+ // subnormal input
36
+ if (exponent == 0) {
37
+ // guaranteed mantissa!=0 since cases 0x0 and 0x80 are handled above
38
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
39
+ uint32_t renorm_shift = __clz(mantissa);
40
+ #elif defined(__SYCL_DEVICE_ONLY__)
41
+ uint32_t renorm_shift = sycl::clz(mantissa);
42
+ #elif defined(_MSC_VER)
43
+ unsigned long nonsign_bsr;
44
+ _BitScanReverse(&nonsign_bsr, (unsigned long)mantissa);
45
+ uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31;
46
+ #else
47
+ uint32_t renorm_shift = __builtin_clz(mantissa);
48
+ #endif
49
+ uint32_t sh = 1 + renorm_shift - (32 - wm);
50
+ mantissa <<= sh;
51
+ exponent += 1 - sh;
52
+ mantissa &= ((1 << wm) - 1);
53
+ }
54
+
55
+ const uint32_t exp_low_cutoff = (1 << (weo - 1)) - (1 << (we - 1));
56
+ exponent += exp_low_cutoff - 1;
57
+ mantissa <<= wmo - wm;
58
+
59
+ uint32_t sign = x >> 7;
60
+ uint32_t retval = (sign << 31) | (exponent << 23) | mantissa;
61
+ return fp32_from_bits(retval);
62
+ }
63
+
64
+ } // namespace c10::detail
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/FunctionRef.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file contains some templates that are useful if you are working with the
10
+ // STL at all.
11
+ //
12
+ // No library is required when using these functions.
13
+ //
14
+ //===----------------------------------------------------------------------===//
15
+
16
+ // c10: modified from llvm::function_ref
17
+ // c10: added more SFINAE to enable use in overloaded functions
18
+
19
+ #pragma once
20
+
21
+ #include <cstdint>
22
+ #include <type_traits>
23
+ #include <utility>
24
+
25
+ namespace c10 {
26
+
27
+ /// An efficient, type-erasing, non-owning reference to a callable. This is
28
+ /// intended for use as the type of a function parameter that is not used
29
+ /// after the function in question returns.
30
+ ///
31
+ /// This class does not own the callable, so it is not in general safe to store
32
+ /// a function_ref.
33
+ template <typename Fn>
34
+ class function_ref;
35
+
36
+ template <typename Ret, typename... Params>
37
+ class function_ref<Ret(Params...)> {
38
+ Ret (*callback)(intptr_t callable, Params... params) = nullptr;
39
+ intptr_t callable{};
40
+
41
+ template <typename Callable>
42
+ static Ret callback_fn(intptr_t callable, Params... params) {
43
+ return (*reinterpret_cast<Callable*>(callable))(
44
+ std::forward<Params>(params)...);
45
+ }
46
+
47
+ public:
48
+ function_ref() = default;
49
+ function_ref(std::nullptr_t) {}
50
+
51
+ template <typename Callable>
52
+ function_ref(
53
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
54
+ Callable&& callable,
55
+ std::enable_if_t<
56
+ !std::is_same_v<std::remove_reference_t<Callable>, function_ref>>* =
57
+ nullptr,
58
+ std::enable_if_t<std::is_convertible_v<
59
+ typename std::invoke_result_t<Callable, Params...>,
60
+ Ret>>* = nullptr)
61
+ : callback(callback_fn<std::remove_reference_t<Callable>>),
62
+ callable(reinterpret_cast<intptr_t>(&callable)) {}
63
+
64
+ Ret operator()(Params... params) const {
65
+ return callback(callable, std::forward<Params>(params)...);
66
+ }
67
+
68
+ operator bool() const {
69
+ return callback;
70
+ }
71
+ };
72
+
73
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Gauge.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <memory>
4
+ #include <string_view>
5
+
6
+ #include <c10/macros/Macros.h>
7
+ #include <c10/util/SmallVector.h>
8
+
9
+ namespace c10::monitor {
10
+ namespace detail {
11
+
12
+ class GaugeImpl;
13
+
14
+ class GaugeBackendIf {
15
+ public:
16
+ virtual ~GaugeBackendIf() = default;
17
+ virtual void record(int64_t value) noexcept = 0;
18
+ };
19
+
20
+ class GaugeBackendFactoryIf {
21
+ public:
22
+ virtual ~GaugeBackendFactoryIf() = default;
23
+
24
+ // May return nullptr if the gauge will be ignored by the given backend.
25
+ virtual std::unique_ptr<GaugeBackendIf> create(
26
+ std::string_view key) noexcept = 0;
27
+ };
28
+
29
+ void C10_API registerGaugeBackend(std::unique_ptr<GaugeBackendFactoryIf>);
30
+ } // namespace detail
31
+
32
+ // A handle to a Gauge.
33
+ class C10_API GaugeHandle {
34
+ public:
35
+ explicit GaugeHandle(std::string_view key);
36
+ void record(int64_t value);
37
+
38
+ private:
39
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
40
+ detail::GaugeImpl& impl_;
41
+ };
42
+
43
+ } // namespace c10::monitor
44
+
45
+ #define STATIC_GAUGE(_key) \
46
+ []() -> ::c10::monitor::GaugeHandle& { \
47
+ static ::c10::monitor::GaugeHandle handle(#_key); \
48
+ return handle; \
49
+ }()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Half-inl.h ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/bit_cast.h>
5
+
6
+ #include <cstring>
7
+ #include <limits>
8
+
9
+ #ifdef __CUDACC__
10
+ #include <cuda_fp16.h>
11
+ #endif
12
+
13
+ #ifdef __HIPCC__
14
+ #include <hip/hip_fp16.h>
15
+ #endif
16
+
17
+ #if defined(CL_SYCL_LANGUAGE_VERSION)
18
+ #include <CL/sycl.hpp> // for SYCL 1.2.1
19
+ #elif defined(SYCL_LANGUAGE_VERSION)
20
+ #include <sycl/sycl.hpp> // for SYCL 2020
21
+ #endif
22
+
23
+ #if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \
24
+ !defined(__APPLE__)
25
+ #include <ATen/cpu/vec/vec_half.h>
26
+ #endif
27
+
28
+ C10_CLANG_DIAGNOSTIC_PUSH()
29
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
30
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
31
+ #endif
32
+
33
+ namespace c10 {
34
+
35
+ #if defined(__aarch64__) && !defined(__CUDACC__)
36
+ /// Constructors
37
+ inline Half::Half(float16_t value) : x(detail::fp16_to_bits(value)) {}
38
+ inline Half::operator float16_t() const {
39
+ return detail::fp16_from_bits(x);
40
+ }
41
+ #else
42
+
43
+ inline C10_HOST_DEVICE Half::Half(float value)
44
+ :
45
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
46
+ x(__half_as_short(__float2half(value)))
47
+ #elif defined(__SYCL_DEVICE_ONLY__)
48
+ x(c10::bit_cast<uint16_t>(sycl::half(value)))
49
+ #elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \
50
+ !defined(__APPLE__)
51
+ x(at::vec::float2half_scalar(value))
52
+ #else
53
+ x(detail::fp16_ieee_from_fp32_value(value))
54
+ #endif
55
+ {
56
+ }
57
+
58
+ /// Implicit conversions
59
+
60
+ inline C10_HOST_DEVICE Half::operator float() const {
61
+ #if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__)
62
+ return __half2float(*reinterpret_cast<const __half*>(&x));
63
+ #elif defined(__SYCL_DEVICE_ONLY__)
64
+ return float(c10::bit_cast<sycl::half>(x));
65
+ #elif (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \
66
+ !defined(__APPLE__)
67
+ return at::vec::half2float_scalar(x);
68
+ #elif defined(__aarch64__) && !defined(__CUDACC__)
69
+ return detail::native_fp16_to_fp32_value(x);
70
+ #else
71
+ return detail::fp16_ieee_to_fp32_value(x);
72
+ #endif
73
+ }
74
+
75
+ #endif /* !defined(__aarch64__) || defined(__CUDACC__) \
76
+ */
77
+
78
+ #if defined(__CUDACC__) || defined(__HIPCC__)
79
+ inline C10_HOST_DEVICE Half::Half(const __half& value) {
80
+ x = *reinterpret_cast<const unsigned short*>(&value);
81
+ }
82
+ inline C10_HOST_DEVICE Half::operator __half() const {
83
+ return *reinterpret_cast<const __half*>(&x);
84
+ }
85
+ #endif
86
+
87
+ #ifdef SYCL_LANGUAGE_VERSION
88
+ inline C10_HOST_DEVICE Half::Half(const sycl::half& value) {
89
+ x = *reinterpret_cast<const unsigned short*>(&value);
90
+ }
91
+ inline C10_HOST_DEVICE Half::operator sycl::half() const {
92
+ return *reinterpret_cast<const sycl::half*>(&x);
93
+ }
94
+ #endif
95
+
96
+ // CUDA intrinsics
97
+
98
+ #if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 350)) || \
99
+ (defined(__clang__) && defined(__CUDA__))
100
+ inline __device__ Half __ldg(const Half* ptr) {
101
+ return __ldg(reinterpret_cast<const __half*>(ptr));
102
+ }
103
+ #endif
104
+
105
+ /// Arithmetic
106
+
107
+ inline C10_HOST_DEVICE Half operator+(const Half& a, const Half& b) {
108
+ return static_cast<float>(a) + static_cast<float>(b);
109
+ }
110
+
111
+ inline C10_HOST_DEVICE Half operator-(const Half& a, const Half& b) {
112
+ return static_cast<float>(a) - static_cast<float>(b);
113
+ }
114
+
115
+ inline C10_HOST_DEVICE Half operator*(const Half& a, const Half& b) {
116
+ return static_cast<float>(a) * static_cast<float>(b);
117
+ }
118
+
119
+ inline C10_HOST_DEVICE Half operator/(const Half& a, const Half& b)
120
+ __ubsan_ignore_float_divide_by_zero__ {
121
+ return static_cast<float>(a) / static_cast<float>(b);
122
+ }
123
+
124
+ inline C10_HOST_DEVICE Half operator-(const Half& a) {
125
+ #if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 530) || \
126
+ defined(__HIP_DEVICE_COMPILE__)
127
+ return __hneg(a);
128
+ #elif defined(__SYCL_DEVICE_ONLY__)
129
+ return -c10::bit_cast<sycl::half>(a);
130
+ #else
131
+ return -static_cast<float>(a);
132
+ #endif
133
+ }
134
+
135
+ inline C10_HOST_DEVICE Half& operator+=(Half& a, const Half& b) {
136
+ a = a + b;
137
+ return a;
138
+ }
139
+
140
+ inline C10_HOST_DEVICE Half& operator-=(Half& a, const Half& b) {
141
+ a = a - b;
142
+ return a;
143
+ }
144
+
145
+ inline C10_HOST_DEVICE Half& operator*=(Half& a, const Half& b) {
146
+ a = a * b;
147
+ return a;
148
+ }
149
+
150
+ inline C10_HOST_DEVICE Half& operator/=(Half& a, const Half& b) {
151
+ a = a / b;
152
+ return a;
153
+ }
154
+
155
+ /// Arithmetic with floats
156
+
157
+ inline C10_HOST_DEVICE float operator+(Half a, float b) {
158
+ return static_cast<float>(a) + b;
159
+ }
160
+ inline C10_HOST_DEVICE float operator-(Half a, float b) {
161
+ return static_cast<float>(a) - b;
162
+ }
163
+ inline C10_HOST_DEVICE float operator*(Half a, float b) {
164
+ return static_cast<float>(a) * b;
165
+ }
166
+ inline C10_HOST_DEVICE float operator/(Half a, float b)
167
+ __ubsan_ignore_float_divide_by_zero__ {
168
+ return static_cast<float>(a) / b;
169
+ }
170
+
171
+ inline C10_HOST_DEVICE float operator+(float a, Half b) {
172
+ return a + static_cast<float>(b);
173
+ }
174
+ inline C10_HOST_DEVICE float operator-(float a, Half b) {
175
+ return a - static_cast<float>(b);
176
+ }
177
+ inline C10_HOST_DEVICE float operator*(float a, Half b) {
178
+ return a * static_cast<float>(b);
179
+ }
180
+ inline C10_HOST_DEVICE float operator/(float a, Half b)
181
+ __ubsan_ignore_float_divide_by_zero__ {
182
+ return a / static_cast<float>(b);
183
+ }
184
+
185
+ inline C10_HOST_DEVICE float& operator+=(float& a, const Half& b) {
186
+ return a += static_cast<float>(b);
187
+ }
188
+ inline C10_HOST_DEVICE float& operator-=(float& a, const Half& b) {
189
+ return a -= static_cast<float>(b);
190
+ }
191
+ inline C10_HOST_DEVICE float& operator*=(float& a, const Half& b) {
192
+ return a *= static_cast<float>(b);
193
+ }
194
+ inline C10_HOST_DEVICE float& operator/=(float& a, const Half& b) {
195
+ return a /= static_cast<float>(b);
196
+ }
197
+
198
+ /// Arithmetic with doubles
199
+
200
+ inline C10_HOST_DEVICE double operator+(Half a, double b) {
201
+ return static_cast<double>(a) + b;
202
+ }
203
+ inline C10_HOST_DEVICE double operator-(Half a, double b) {
204
+ return static_cast<double>(a) - b;
205
+ }
206
+ inline C10_HOST_DEVICE double operator*(Half a, double b) {
207
+ return static_cast<double>(a) * b;
208
+ }
209
+ inline C10_HOST_DEVICE double operator/(Half a, double b)
210
+ __ubsan_ignore_float_divide_by_zero__ {
211
+ return static_cast<double>(a) / b;
212
+ }
213
+
214
+ inline C10_HOST_DEVICE double operator+(double a, Half b) {
215
+ return a + static_cast<double>(b);
216
+ }
217
+ inline C10_HOST_DEVICE double operator-(double a, Half b) {
218
+ return a - static_cast<double>(b);
219
+ }
220
+ inline C10_HOST_DEVICE double operator*(double a, Half b) {
221
+ return a * static_cast<double>(b);
222
+ }
223
+ inline C10_HOST_DEVICE double operator/(double a, Half b)
224
+ __ubsan_ignore_float_divide_by_zero__ {
225
+ return a / static_cast<double>(b);
226
+ }
227
+
228
+ /// Arithmetic with ints
229
+
230
+ inline C10_HOST_DEVICE Half operator+(Half a, int b) {
231
+ return a + static_cast<Half>(b);
232
+ }
233
+ inline C10_HOST_DEVICE Half operator-(Half a, int b) {
234
+ return a - static_cast<Half>(b);
235
+ }
236
+ inline C10_HOST_DEVICE Half operator*(Half a, int b) {
237
+ return a * static_cast<Half>(b);
238
+ }
239
+ inline C10_HOST_DEVICE Half operator/(Half a, int b) {
240
+ return a / static_cast<Half>(b);
241
+ }
242
+
243
+ inline C10_HOST_DEVICE Half operator+(int a, Half b) {
244
+ return static_cast<Half>(a) + b;
245
+ }
246
+ inline C10_HOST_DEVICE Half operator-(int a, Half b) {
247
+ return static_cast<Half>(a) - b;
248
+ }
249
+ inline C10_HOST_DEVICE Half operator*(int a, Half b) {
250
+ return static_cast<Half>(a) * b;
251
+ }
252
+ inline C10_HOST_DEVICE Half operator/(int a, Half b) {
253
+ return static_cast<Half>(a) / b;
254
+ }
255
+
256
+ //// Arithmetic with int64_t
257
+
258
+ inline C10_HOST_DEVICE Half operator+(Half a, int64_t b) {
259
+ return a + static_cast<Half>(b);
260
+ }
261
+ inline C10_HOST_DEVICE Half operator-(Half a, int64_t b) {
262
+ return a - static_cast<Half>(b);
263
+ }
264
+ inline C10_HOST_DEVICE Half operator*(Half a, int64_t b) {
265
+ return a * static_cast<Half>(b);
266
+ }
267
+ inline C10_HOST_DEVICE Half operator/(Half a, int64_t b) {
268
+ return a / static_cast<Half>(b);
269
+ }
270
+
271
+ inline C10_HOST_DEVICE Half operator+(int64_t a, Half b) {
272
+ return static_cast<Half>(a) + b;
273
+ }
274
+ inline C10_HOST_DEVICE Half operator-(int64_t a, Half b) {
275
+ return static_cast<Half>(a) - b;
276
+ }
277
+ inline C10_HOST_DEVICE Half operator*(int64_t a, Half b) {
278
+ return static_cast<Half>(a) * b;
279
+ }
280
+ inline C10_HOST_DEVICE Half operator/(int64_t a, Half b) {
281
+ return static_cast<Half>(a) / b;
282
+ }
283
+
284
+ /// NOTE: we do not define comparisons directly and instead rely on the implicit
285
+ /// conversion from c10::Half to float.
286
+
287
+ } // namespace c10
288
+
289
+ namespace std {
290
+
291
+ template <>
292
+ class numeric_limits<c10::Half> {
293
+ public:
294
+ static constexpr bool is_specialized = true;
295
+ static constexpr bool is_signed = true;
296
+ static constexpr bool is_integer = false;
297
+ static constexpr bool is_exact = false;
298
+ static constexpr bool has_infinity = true;
299
+ static constexpr bool has_quiet_NaN = true;
300
+ static constexpr bool has_signaling_NaN = true;
301
+ static constexpr auto has_denorm = numeric_limits<float>::has_denorm;
302
+ static constexpr auto has_denorm_loss =
303
+ numeric_limits<float>::has_denorm_loss;
304
+ static constexpr auto round_style = numeric_limits<float>::round_style;
305
+ static constexpr bool is_iec559 = true;
306
+ static constexpr bool is_bounded = true;
307
+ static constexpr bool is_modulo = false;
308
+ static constexpr int digits = 11;
309
+ static constexpr int digits10 = 3;
310
+ static constexpr int max_digits10 = 5;
311
+ static constexpr int radix = 2;
312
+ static constexpr int min_exponent = -13;
313
+ static constexpr int min_exponent10 = -4;
314
+ static constexpr int max_exponent = 16;
315
+ static constexpr int max_exponent10 = 4;
316
+ static constexpr auto traps = numeric_limits<float>::traps;
317
+ static constexpr auto tinyness_before =
318
+ numeric_limits<float>::tinyness_before;
319
+ static constexpr c10::Half min() {
320
+ return c10::Half(0x0400, c10::Half::from_bits());
321
+ }
322
+ static constexpr c10::Half lowest() {
323
+ return c10::Half(0xFBFF, c10::Half::from_bits());
324
+ }
325
+ static constexpr c10::Half max() {
326
+ return c10::Half(0x7BFF, c10::Half::from_bits());
327
+ }
328
+ static constexpr c10::Half epsilon() {
329
+ return c10::Half(0x1400, c10::Half::from_bits());
330
+ }
331
+ static constexpr c10::Half round_error() {
332
+ return c10::Half(0x3800, c10::Half::from_bits());
333
+ }
334
+ static constexpr c10::Half infinity() {
335
+ return c10::Half(0x7C00, c10::Half::from_bits());
336
+ }
337
+ static constexpr c10::Half quiet_NaN() {
338
+ return c10::Half(0x7E00, c10::Half::from_bits());
339
+ }
340
+ static constexpr c10::Half signaling_NaN() {
341
+ return c10::Half(0x7D00, c10::Half::from_bits());
342
+ }
343
+ static constexpr c10::Half denorm_min() {
344
+ return c10::Half(0x0001, c10::Half::from_bits());
345
+ }
346
+ };
347
+
348
+ } // namespace std
349
+
350
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Half.h ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ /// Defines the Half type (half-precision floating-point) including conversions
4
+ /// to standard C types and basic arithmetic operations. Note that arithmetic
5
+ /// operations are implemented by converting to floating point and
6
+ /// performing the operation in float32, instead of using CUDA half intrinsics.
7
+ /// Most uses of this type within ATen are memory bound, including the
8
+ /// element-wise kernels, and the half intrinsics aren't efficient on all GPUs.
9
+ /// If you are writing a compute bound kernel, you can use the CUDA half
10
+ /// intrinsics directly on the Half type from device code.
11
+
12
+ #include <c10/macros/Export.h>
13
+ #include <c10/macros/Macros.h>
14
+ #include <c10/util/bit_cast.h>
15
+ #include <c10/util/floating_point_utils.h>
16
+ #include <type_traits>
17
+
18
+ #if defined(__cplusplus)
19
+ #include <cmath>
20
+ #elif !defined(__OPENCL_VERSION__)
21
+ #include <math.h>
22
+ #endif
23
+
24
+ #ifdef _MSC_VER
25
+ #include <intrin.h>
26
+ #endif
27
+
28
+ #include <cstdint>
29
+ #include <cstring>
30
+ #include <iosfwd>
31
+ #include <limits>
32
+ #include <ostream>
33
+
34
+ #ifdef __CUDACC__
35
+ #include <cuda_fp16.h>
36
+ #endif
37
+
38
+ #ifdef __HIPCC__
39
+ #include <hip/hip_fp16.h>
40
+ #endif
41
+
42
+ #if defined(CL_SYCL_LANGUAGE_VERSION)
43
+ #include <CL/sycl.hpp> // for SYCL 1.2.1
44
+ #elif defined(SYCL_LANGUAGE_VERSION)
45
+ #include <sycl/sycl.hpp> // for SYCL 2020
46
+ #endif
47
+
48
+ #if defined(__aarch64__) && !defined(__CUDACC__)
49
+ #include <arm_neon.h>
50
+ #endif
51
+
52
+ #if defined(__GNUC__) || defined(__clang__)
53
+ #if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || \
54
+ defined(_M_IX86)
55
+ #if defined(__F16C__) && \
56
+ !(defined(__CUDA_ARCH__) || defined(__CUDACC__) || \
57
+ defined(__HIP_DEVICE_COMPILE__))
58
+ #define C10_X86_F16 1
59
+ #include <immintrin.h> // import conversion ops from f16cintrin.h
60
+ #endif // defined(__F16C__) && !(defined(__CUDA_ARCH__) || defined(__CUDACC__)
61
+ // || defined(__HIP_DEVICE_COMPILE__))
62
+ #endif // __x86_64__ || _M_X64 || __i386 || _M_IX86
63
+ #endif // __GNUC__ || __clang__
64
+
65
+ namespace c10 {
66
+
67
+ namespace detail {
68
+
69
+ /*
70
+ * Convert a 16-bit floating-point number in IEEE half-precision format, in bit
71
+ * representation, to a 32-bit floating-point number in IEEE single-precision
72
+ * format, in bit representation.
73
+ *
74
+ * @note The implementation doesn't use any floating-point operations.
75
+ */
76
+ inline uint32_t fp16_ieee_to_fp32_bits(uint16_t h) {
77
+ /*
78
+ * Extend the half-precision floating-point number to 32 bits and shift to the
79
+ * upper part of the 32-bit word:
80
+ * +---+-----+------------+-------------------+
81
+ * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
82
+ * +---+-----+------------+-------------------+
83
+ * Bits 31 26-30 16-25 0-15
84
+ *
85
+ * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
86
+ * - zero bits.
87
+ */
88
+ const uint32_t w = (uint32_t)h << 16;
89
+ /*
90
+ * Extract the sign of the input number into the high bit of the 32-bit word:
91
+ *
92
+ * +---+----------------------------------+
93
+ * | S |0000000 00000000 00000000 00000000|
94
+ * +---+----------------------------------+
95
+ * Bits 31 0-31
96
+ */
97
+ const uint32_t sign = w & UINT32_C(0x80000000);
98
+ /*
99
+ * Extract mantissa and biased exponent of the input number into the bits 0-30
100
+ * of the 32-bit word:
101
+ *
102
+ * +---+-----+------------+-------------------+
103
+ * | 0 |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
104
+ * +---+-----+------------+-------------------+
105
+ * Bits 30 27-31 17-26 0-16
106
+ */
107
+ const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF);
108
+ /*
109
+ * Renorm shift is the number of bits to shift mantissa left to make the
110
+ * half-precision number normalized. If the initial number is normalized, some
111
+ * of its high 6 bits (sign == 0 and 5-bit exponent) equals one. In this case
112
+ * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note
113
+ * that if we shift denormalized nonsign by renorm_shift, the unit bit of
114
+ * mantissa will shift into exponent, turning the biased exponent into 1, and
115
+ * making mantissa normalized (i.e. without leading 1).
116
+ */
117
+ #ifdef _MSC_VER
118
+ unsigned long nonsign_bsr;
119
+ _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign);
120
+ uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31;
121
+ #else
122
+ uint32_t renorm_shift = __builtin_clz(nonsign);
123
+ #endif
124
+ renorm_shift = renorm_shift > 5 ? renorm_shift - 5 : 0;
125
+ /*
126
+ * Iff half-precision number has exponent of 15, the addition overflows
127
+ * it into bit 31, and the subsequent shift turns the high 9 bits
128
+ * into 1. Thus inf_nan_mask == 0x7F800000 if the half-precision number
129
+ * had exponent of 15 (i.e. was NaN or infinity) 0x00000000 otherwise
130
+ */
131
+ const int32_t inf_nan_mask =
132
+ ((int32_t)(nonsign + 0x04000000) >> 8) & INT32_C(0x7F800000);
133
+ /*
134
+ * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31
135
+ * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31
136
+ * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask ==
137
+ * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h)
138
+ * 0x00000000 otherwise
139
+ */
140
+ const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31;
141
+ /*
142
+ * 1. Shift nonsign left by renorm_shift to normalize it (if the input
143
+ * was denormal)
144
+ * 2. Shift nonsign right by 3 so the exponent (5 bits originally)
145
+ * becomes an 8-bit field and 10-bit mantissa shifts into the 10 high
146
+ * bits of the 23-bit mantissa of IEEE single-precision number.
147
+ * 3. Add 0x70 to the exponent (starting at bit 23) to compensate the
148
+ * different in exponent bias (0x7F for single-precision number less 0xF
149
+ * for half-precision number).
150
+ * 4. Subtract renorm_shift from the exponent (starting at bit 23) to
151
+ * account for renormalization. As renorm_shift is less than 0x70, this
152
+ * can be combined with step 3.
153
+ * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the
154
+ * input was NaN or infinity.
155
+ * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent
156
+ * into zero if the input was zero.
157
+ * 7. Combine with the sign of the input number.
158
+ */
159
+ return sign |
160
+ ((((nonsign << renorm_shift >> 3) + ((0x70 - renorm_shift) << 23)) |
161
+ inf_nan_mask) &
162
+ ~zero_mask);
163
+ }
164
+
165
+ /*
166
+ * Convert a 16-bit floating-point number in IEEE half-precision format, in bit
167
+ * representation, to a 32-bit floating-point number in IEEE single-precision
168
+ * format.
169
+ *
170
+ * @note The implementation relies on IEEE-like (no assumption about rounding
171
+ * mode and no operations on denormals) floating-point operations and bitcasts
172
+ * between integer and floating-point variables.
173
+ */
174
+ C10_HOST_DEVICE inline float fp16_ieee_to_fp32_value(uint16_t h) {
175
+ #ifdef C10_X86_F16
176
+ return _cvtsh_ss(h);
177
+ #else
178
+ /*
179
+ * Extend the half-precision floating-point number to 32 bits and shift to the
180
+ * upper part of the 32-bit word:
181
+ * +---+-----+------------+-------------------+
182
+ * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
183
+ * +---+-----+------------+-------------------+
184
+ * Bits 31 26-30 16-25 0-15
185
+ *
186
+ * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
187
+ * - zero bits.
188
+ */
189
+ const uint32_t w = (uint32_t)h << 16;
190
+ /*
191
+ * Extract the sign of the input number into the high bit of the 32-bit word:
192
+ *
193
+ * +---+----------------------------------+
194
+ * | S |0000000 00000000 00000000 00000000|
195
+ * +---+----------------------------------+
196
+ * Bits 31 0-31
197
+ */
198
+ const uint32_t sign = w & UINT32_C(0x80000000);
199
+ /*
200
+ * Extract mantissa and biased exponent of the input number into the high bits
201
+ * of the 32-bit word:
202
+ *
203
+ * +-----+------------+---------------------+
204
+ * |EEEEE|MM MMMM MMMM|0 0000 0000 0000 0000|
205
+ * +-----+------------+---------------------+
206
+ * Bits 27-31 17-26 0-16
207
+ */
208
+ const uint32_t two_w = w + w;
209
+
210
+ /*
211
+ * Shift mantissa and exponent into bits 23-28 and bits 13-22 so they become
212
+ * mantissa and exponent of a single-precision floating-point number:
213
+ *
214
+ * S|Exponent | Mantissa
215
+ * +-+---+-----+------------+----------------+
216
+ * |0|000|EEEEE|MM MMMM MMMM|0 0000 0000 0000|
217
+ * +-+---+-----+------------+----------------+
218
+ * Bits | 23-31 | 0-22
219
+ *
220
+ * Next, there are some adjustments to the exponent:
221
+ * - The exponent needs to be corrected by the difference in exponent bias
222
+ * between single-precision and half-precision formats (0x7F - 0xF = 0x70)
223
+ * - Inf and NaN values in the inputs should become Inf and NaN values after
224
+ * conversion to the single-precision number. Therefore, if the biased
225
+ * exponent of the half-precision input was 0x1F (max possible value), the
226
+ * biased exponent of the single-precision output must be 0xFF (max possible
227
+ * value). We do this correction in two steps:
228
+ * - First, we adjust the exponent by (0xFF - 0x1F) = 0xE0 (see exp_offset
229
+ * below) rather than by 0x70 suggested by the difference in the exponent bias
230
+ * (see above).
231
+ * - Then we multiply the single-precision result of exponent adjustment by
232
+ * 2**(-112) to reverse the effect of exponent adjustment by 0xE0 less the
233
+ * necessary exponent adjustment by 0x70 due to difference in exponent bias.
234
+ * The floating-point multiplication hardware would ensure than Inf and
235
+ * NaN would retain their value on at least partially IEEE754-compliant
236
+ * implementations.
237
+ *
238
+ * Note that the above operations do not handle denormal inputs (where biased
239
+ * exponent == 0). However, they also do not operate on denormal inputs, and
240
+ * do not produce denormal results.
241
+ */
242
+ constexpr uint32_t exp_offset = UINT32_C(0xE0) << 23;
243
+ // const float exp_scale = 0x1.0p-112f;
244
+ constexpr uint32_t scale_bits = (uint32_t)15 << 23;
245
+ float exp_scale_val = 0;
246
+ #if defined(_MSC_VER) && defined(__clang__)
247
+ __builtin_memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val));
248
+ #else
249
+ std::memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val));
250
+ #endif
251
+
252
+ const float exp_scale = exp_scale_val;
253
+ const float normalized_value =
254
+ fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
255
+
256
+ /*
257
+ * Convert denormalized half-precision inputs into single-precision results
258
+ * (always normalized). Zero inputs are also handled here.
259
+ *
260
+ * In a denormalized number the biased exponent is zero, and mantissa has
261
+ * on-zero bits. First, we shift mantissa into bits 0-9 of the 32-bit word.
262
+ *
263
+ * zeros | mantissa
264
+ * +---------------------------+------------+
265
+ * |0000 0000 0000 0000 0000 00|MM MMMM MMMM|
266
+ * +---------------------------+------------+
267
+ * Bits 10-31 0-9
268
+ *
269
+ * Now, remember that denormalized half-precision numbers are represented as:
270
+ * FP16 = mantissa * 2**(-24).
271
+ * The trick is to construct a normalized single-precision number with the
272
+ * same mantissa and thehalf-precision input and with an exponent which would
273
+ * scale the corresponding mantissa bits to 2**(-24). A normalized
274
+ * single-precision floating-point number is represented as: FP32 = (1 +
275
+ * mantissa * 2**(-23)) * 2**(exponent - 127) Therefore, when the biased
276
+ * exponent is 126, a unit change in the mantissa of the input denormalized
277
+ * half-precision number causes a change of the constructed single-precision
278
+ * number by 2**(-24), i.e. the same amount.
279
+ *
280
+ * The last step is to adjust the bias of the constructed single-precision
281
+ * number. When the input half-precision number is zero, the constructed
282
+ * single-precision number has the value of FP32 = 1 * 2**(126 - 127) =
283
+ * 2**(-1) = 0.5 Therefore, we need to subtract 0.5 from the constructed
284
+ * single-precision number to get the numerical equivalent of the input
285
+ * half-precision number.
286
+ */
287
+ constexpr uint32_t magic_mask = UINT32_C(126) << 23;
288
+ constexpr float magic_bias = 0.5f;
289
+ const float denormalized_value =
290
+ fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
291
+
292
+ /*
293
+ * - Choose either results of conversion of input as a normalized number, or
294
+ * as a denormalized number, depending on the input exponent. The variable
295
+ * two_w contains input exponent in bits 27-31, therefore if its smaller than
296
+ * 2**27, the input is either a denormal number, or zero.
297
+ * - Combine the result of conversion of exponent and mantissa with the sign
298
+ * of the input number.
299
+ */
300
+ constexpr uint32_t denormalized_cutoff = UINT32_C(1) << 27;
301
+ const uint32_t result = sign |
302
+ (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value)
303
+ : fp32_to_bits(normalized_value));
304
+ return fp32_from_bits(result);
305
+ #endif // C10_X86_F16
306
+ }
307
+
308
+ /*
309
+ * Convert a 32-bit floating-point number in IEEE single-precision format to a
310
+ * 16-bit floating-point number in IEEE half-precision format, in bit
311
+ * representation.
312
+ *
313
+ * @note The implementation relies on IEEE-like (no assumption about rounding
314
+ * mode and no operations on denormals) floating-point operations and bitcasts
315
+ * between integer and floating-point variables.
316
+ */
317
+ inline uint16_t fp16_ieee_from_fp32_value(float f) {
318
+ #ifdef C10_X86_F16
319
+ return _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT);
320
+ #else
321
+ // const float scale_to_inf = 0x1.0p+112f;
322
+ // const float scale_to_zero = 0x1.0p-110f;
323
+ constexpr uint32_t scale_to_inf_bits = (uint32_t)239 << 23;
324
+ constexpr uint32_t scale_to_zero_bits = (uint32_t)17 << 23;
325
+ float scale_to_inf_val = 0, scale_to_zero_val = 0;
326
+ std::memcpy(&scale_to_inf_val, &scale_to_inf_bits, sizeof(scale_to_inf_val));
327
+ std::memcpy(
328
+ &scale_to_zero_val, &scale_to_zero_bits, sizeof(scale_to_zero_val));
329
+ const float scale_to_inf = scale_to_inf_val;
330
+ const float scale_to_zero = scale_to_zero_val;
331
+
332
+ #if defined(_MSC_VER) && _MSC_VER == 1916
333
+ float base = ((signbit(f) != 0 ? -f : f) * scale_to_inf) * scale_to_zero;
334
+ #else
335
+ float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
336
+ #endif
337
+
338
+ const uint32_t w = fp32_to_bits(f);
339
+ const uint32_t shl1_w = w + w;
340
+ const uint32_t sign = w & UINT32_C(0x80000000);
341
+ uint32_t bias = shl1_w & UINT32_C(0xFF000000);
342
+ if (bias < UINT32_C(0x71000000)) {
343
+ bias = UINT32_C(0x71000000);
344
+ }
345
+
346
+ base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
347
+ const uint32_t bits = fp32_to_bits(base);
348
+ const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
349
+ const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
350
+ const uint32_t nonsign = exp_bits + mantissa_bits;
351
+ return static_cast<uint16_t>(
352
+ (sign >> 16) |
353
+ (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign));
354
+ #endif // C10_X86_F16
355
+ }
356
+
357
+ #ifdef C10_X86_F16
358
+ #undef C10_X86_F16
359
+ #endif // C10_X86_F16
360
+
361
+ #if defined(__aarch64__) && !defined(__CUDACC__)
362
+ inline float16_t fp16_from_bits(uint16_t h) {
363
+ return c10::bit_cast<float16_t>(h);
364
+ }
365
+
366
+ inline uint16_t fp16_to_bits(float16_t f) {
367
+ return c10::bit_cast<uint16_t>(f);
368
+ }
369
+
370
+ // According to https://godbolt.org/z/frExdbsWG it would translate to single
371
+ // fcvt s0, h0
372
+ inline float native_fp16_to_fp32_value(uint16_t h) {
373
+ return static_cast<float>(fp16_from_bits(h));
374
+ }
375
+
376
+ inline uint16_t native_fp16_from_fp32_value(float f) {
377
+ return fp16_to_bits(static_cast<float16_t>(f));
378
+ }
379
+ #endif
380
+
381
+ } // namespace detail
382
+
383
+ struct alignas(2) Half {
384
+ unsigned short x;
385
+
386
+ struct from_bits_t {};
387
+ C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
388
+ return from_bits_t();
389
+ }
390
+
391
+ // HIP wants __host__ __device__ tag, CUDA does not
392
+ #if defined(USE_ROCM)
393
+ C10_HOST_DEVICE Half() = default;
394
+ #else
395
+ Half() = default;
396
+ #endif
397
+
398
+ constexpr C10_HOST_DEVICE Half(unsigned short bits, from_bits_t) : x(bits) {}
399
+ #if defined(__aarch64__) && !defined(__CUDACC__)
400
+ inline Half(float16_t value);
401
+ inline operator float16_t() const;
402
+ #else
403
+ inline C10_HOST_DEVICE Half(float value);
404
+ inline C10_HOST_DEVICE operator float() const;
405
+ #endif
406
+
407
+ #if defined(__CUDACC__) || defined(__HIPCC__)
408
+ inline C10_HOST_DEVICE Half(const __half& value);
409
+ inline C10_HOST_DEVICE operator __half() const;
410
+ #endif
411
+ #ifdef SYCL_LANGUAGE_VERSION
412
+ inline C10_HOST_DEVICE Half(const sycl::half& value);
413
+ inline C10_HOST_DEVICE operator sycl::half() const;
414
+ #endif
415
+ };
416
+
417
+ C10_API inline std::ostream& operator<<(std::ostream& out, const Half& value) {
418
+ out << (float)value;
419
+ return out;
420
+ }
421
+
422
+ } // namespace c10
423
+
424
+ #include <c10/util/Half-inl.h> // IWYU pragma: keep
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/IdWrapper.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <functional>
5
+ #include <utility>
6
+
7
+ namespace c10 {
8
+
9
+ /**
10
+ * This template simplifies generation of simple classes that wrap an id
11
+ * in a typesafe way. Namely, you can use it to create a very lightweight
12
+ * type that only offers equality comparators and hashing. Example:
13
+ *
14
+ * struct MyIdType final : IdWrapper<MyIdType, uint32_t> {
15
+ * constexpr explicit MyIdType(uint32_t id): IdWrapper(id) {}
16
+ * };
17
+ *
18
+ * Then in the global top level namespace:
19
+ *
20
+ * C10_DEFINE_HASH_FOR_IDWRAPPER(MyIdType);
21
+ *
22
+ * That's it - equality operators and hash functions are automatically defined
23
+ * for you, given the underlying type supports it.
24
+ */
25
+ template <class ConcreteType, class UnderlyingType>
26
+ class IdWrapper {
27
+ public:
28
+ using underlying_type = UnderlyingType;
29
+ using concrete_type = ConcreteType;
30
+
31
+ protected:
32
+ constexpr explicit IdWrapper(underlying_type id) noexcept(
33
+ noexcept(underlying_type(std::declval<underlying_type>())))
34
+ : id_(id) {}
35
+
36
+ constexpr underlying_type underlyingId() const
37
+ noexcept(noexcept(underlying_type(std::declval<underlying_type>()))) {
38
+ return id_;
39
+ }
40
+
41
+ private:
42
+ friend size_t hash_value(const concrete_type& v) {
43
+ return std::hash<underlying_type>()(v.id_);
44
+ }
45
+
46
+ // TODO Making operator== noexcept if underlying type is noexcept equality
47
+ // comparable doesn't work with GCC 4.8.
48
+ // Fix this once we don't need GCC 4.8 anymore.
49
+ friend constexpr bool operator==(
50
+ const concrete_type& lhs,
51
+ const concrete_type& rhs) noexcept {
52
+ return lhs.id_ == rhs.id_;
53
+ }
54
+
55
+ // TODO Making operator!= noexcept if operator== is noexcept doesn't work with
56
+ // GCC 4.8.
57
+ // Fix this once we don't need GCC 4.8 anymore.
58
+ friend constexpr bool operator!=(
59
+ const concrete_type& lhs,
60
+ const concrete_type& rhs) noexcept {
61
+ return !(lhs == rhs);
62
+ }
63
+
64
+ underlying_type id_;
65
+ };
66
+
67
+ } // namespace c10
68
+
69
+ #define C10_DEFINE_HASH_FOR_IDWRAPPER(ClassName) \
70
+ namespace std { \
71
+ template <> \
72
+ struct hash<ClassName> { \
73
+ size_t operator()(ClassName x) const { \
74
+ return hash_value(x); \
75
+ } \
76
+ }; \
77
+ }
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/IntrusiveList.h ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Exception.h>
4
+
5
+ namespace c10 {
6
+
7
+ template <typename T>
8
+ class IntrusiveList;
9
+
10
+ class IntrusiveListHook {
11
+ template <typename P, typename T>
12
+ friend class ListIterator;
13
+
14
+ template <typename T>
15
+ friend class IntrusiveList;
16
+
17
+ IntrusiveListHook* next_{nullptr};
18
+ IntrusiveListHook* prev_{nullptr};
19
+
20
+ void link_before(IntrusiveListHook* next_node) {
21
+ next_ = next_node;
22
+ prev_ = next_node->prev_;
23
+ next_node->prev_ = this;
24
+ prev_->next_ = this;
25
+ }
26
+
27
+ public:
28
+ IntrusiveListHook() : next_(this), prev_(this) {}
29
+
30
+ IntrusiveListHook(const IntrusiveListHook&) = delete;
31
+ IntrusiveListHook& operator=(const IntrusiveListHook&) = delete;
32
+ IntrusiveListHook(IntrusiveListHook&&) = delete;
33
+ IntrusiveListHook& operator=(IntrusiveListHook&&) = delete;
34
+
35
+ void unlink() {
36
+ TORCH_CHECK(is_linked());
37
+ next_->prev_ = prev_;
38
+ prev_->next_ = next_;
39
+ next_ = this;
40
+ prev_ = this;
41
+ }
42
+
43
+ ~IntrusiveListHook() {
44
+ if (is_linked()) {
45
+ unlink();
46
+ }
47
+ }
48
+
49
+ bool is_linked() const {
50
+ return next_ != this;
51
+ }
52
+ };
53
+
54
+ template <typename P, typename T>
55
+ class ListIterator {
56
+ static_assert(std::is_same_v<std::remove_const_t<P>, IntrusiveListHook>);
57
+ static_assert(std::is_base_of_v<IntrusiveListHook, T>);
58
+ P* ptr_;
59
+
60
+ friend class IntrusiveList<T>;
61
+
62
+ public:
63
+ using iterator_category = std::bidirectional_iterator_tag;
64
+ using value_type = std::conditional_t<std::is_const_v<P>, const T, T>;
65
+ using difference_type = std::ptrdiff_t;
66
+ using pointer = value_type*;
67
+ using reference = value_type&;
68
+
69
+ explicit ListIterator(P* ptr) : ptr_(ptr) {}
70
+ ~ListIterator() = default;
71
+
72
+ ListIterator(const ListIterator&) = default;
73
+ ListIterator& operator=(const ListIterator&) = default;
74
+ ListIterator(ListIterator&&) = default;
75
+ ListIterator& operator=(ListIterator&&) = default;
76
+
77
+ template <
78
+ typename Q,
79
+ class = std::enable_if_t<std::is_const_v<P> && !std::is_const_v<Q>>>
80
+ ListIterator(const ListIterator<Q, T>& rhs) : ptr_(rhs.ptr_) {}
81
+
82
+ template <
83
+ typename Q,
84
+ class = std::enable_if_t<std::is_const_v<P> && !std::is_const_v<Q>>>
85
+ ListIterator& operator=(const ListIterator<Q, T>& rhs) {
86
+ ptr_ = rhs.ptr_;
87
+ return *this;
88
+ }
89
+
90
+ template <typename Q>
91
+ bool operator==(const ListIterator<Q, T>& other) const {
92
+ return ptr_ == other.ptr_;
93
+ }
94
+
95
+ template <typename Q>
96
+ bool operator!=(const ListIterator<Q, T>& other) const {
97
+ return !(*this == other);
98
+ }
99
+
100
+ auto& operator*() const {
101
+ return static_cast<reference>(*ptr_);
102
+ }
103
+
104
+ ListIterator& operator++() {
105
+ TORCH_CHECK(ptr_);
106
+ ptr_ = ptr_->next_;
107
+ return *this;
108
+ }
109
+
110
+ ListIterator& operator--() {
111
+ TORCH_CHECK(ptr_);
112
+ ptr_ = ptr_->prev_;
113
+ return *this;
114
+ }
115
+
116
+ auto* operator->() const {
117
+ return static_cast<pointer>(ptr_);
118
+ }
119
+ };
120
+
121
+ template <typename T>
122
+ class IntrusiveList {
123
+ static_assert(std::is_base_of_v<IntrusiveListHook, T>);
124
+
125
+ public:
126
+ IntrusiveList() = default;
127
+ IntrusiveList(const std::initializer_list<std::reference_wrapper<T>>& items) {
128
+ for (auto& item : items) {
129
+ insert(this->end(), item);
130
+ }
131
+ }
132
+ ~IntrusiveList() {
133
+ while (head_.is_linked()) {
134
+ head_.next_->unlink();
135
+ }
136
+ }
137
+ IntrusiveList(const IntrusiveList&) = delete;
138
+ IntrusiveList& operator=(const IntrusiveList&) = delete;
139
+ IntrusiveList(IntrusiveList&&) = delete;
140
+ IntrusiveList& operator=(IntrusiveList&&) = delete;
141
+
142
+ using iterator = ListIterator<IntrusiveListHook, T>;
143
+ using const_iterator = ListIterator<const IntrusiveListHook, T>;
144
+
145
+ auto begin() const {
146
+ return ++const_iterator{&head_};
147
+ }
148
+
149
+ auto begin() {
150
+ return ++iterator{&head_};
151
+ }
152
+
153
+ auto end() const {
154
+ return const_iterator{&head_};
155
+ }
156
+
157
+ auto end() {
158
+ return iterator{&head_};
159
+ }
160
+
161
+ auto rbegin() const {
162
+ return std::reverse_iterator{end()};
163
+ }
164
+
165
+ auto rbegin() {
166
+ return std::reverse_iterator{end()};
167
+ }
168
+
169
+ auto rend() const {
170
+ return std::reverse_iterator{begin()};
171
+ }
172
+
173
+ auto rend() {
174
+ return std::reverse_iterator{begin()};
175
+ }
176
+
177
+ auto iterator_to(const T& n) const {
178
+ return const_iterator{&n};
179
+ }
180
+
181
+ auto iterator_to(T& n) {
182
+ return iterator{&n};
183
+ }
184
+
185
+ iterator insert(iterator pos, T& n) {
186
+ n.link_before(pos.ptr_);
187
+ return iterator{&n};
188
+ }
189
+
190
+ size_t size() const {
191
+ size_t ret = 0;
192
+ for ([[maybe_unused]] auto& _ : *this) {
193
+ ret++;
194
+ }
195
+ return ret;
196
+ }
197
+
198
+ bool empty() const {
199
+ return !head_.is_linked();
200
+ }
201
+
202
+ private:
203
+ IntrusiveListHook head_;
204
+ };
205
+
206
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Lazy.h ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <atomic>
4
+ #include <utility>
5
+
6
+ namespace c10 {
7
+
8
+ /**
9
+ * Thread-safe lazy value with opportunistic concurrency: on concurrent first
10
+ * access, the factory may be called by multiple threads, but only one result is
11
+ * stored and its reference returned to all the callers.
12
+ *
13
+ * Value is heap-allocated; this optimizes for the case in which the value is
14
+ * never actually computed.
15
+ */
16
+ template <class T>
17
+ class OptimisticLazy {
18
+ public:
19
+ OptimisticLazy() = default;
20
+ OptimisticLazy(const OptimisticLazy& other) {
21
+ if (T* value = other.value_.load(std::memory_order_acquire)) {
22
+ value_ = new T(*value);
23
+ }
24
+ }
25
+ OptimisticLazy(OptimisticLazy&& other) noexcept
26
+ : value_(other.value_.exchange(nullptr, std::memory_order_acq_rel)) {}
27
+ ~OptimisticLazy() {
28
+ reset();
29
+ }
30
+
31
+ template <class Factory>
32
+ T& ensure(const Factory& factory) {
33
+ if (T* value = value_.load(std::memory_order_acquire)) {
34
+ return *value;
35
+ }
36
+ T* value = new T(factory());
37
+ T* old = nullptr;
38
+ if (!value_.compare_exchange_strong(
39
+ old, value, std::memory_order_release, std::memory_order_acquire)) {
40
+ delete value;
41
+ value = old;
42
+ }
43
+ return *value;
44
+ }
45
+
46
+ // The following methods are not thread-safe: they should not be called
47
+ // concurrently with any other method.
48
+
49
+ OptimisticLazy& operator=(const OptimisticLazy& other) {
50
+ *this = OptimisticLazy{other};
51
+ return *this;
52
+ }
53
+
54
+ OptimisticLazy& operator=(OptimisticLazy&& other) noexcept {
55
+ if (this != &other) {
56
+ reset();
57
+ value_.store(
58
+ other.value_.exchange(nullptr, std::memory_order_acquire),
59
+ std::memory_order_release);
60
+ }
61
+ return *this;
62
+ }
63
+
64
+ void reset() {
65
+ if (T* old = value_.load(std::memory_order_relaxed)) {
66
+ value_.store(nullptr, std::memory_order_relaxed);
67
+ delete old;
68
+ }
69
+ }
70
+
71
+ private:
72
+ std::atomic<T*> value_{nullptr};
73
+ };
74
+
75
+ /**
76
+ * Interface for a value that is computed on first access.
77
+ */
78
+ template <class T>
79
+ class LazyValue {
80
+ public:
81
+ virtual ~LazyValue() = default;
82
+
83
+ virtual const T& get() const = 0;
84
+ };
85
+
86
+ /**
87
+ * Convenience thread-safe LazyValue implementation with opportunistic
88
+ * concurrency.
89
+ */
90
+ template <class T>
91
+ class OptimisticLazyValue : public LazyValue<T> {
92
+ public:
93
+ const T& get() const override {
94
+ return value_.ensure([this] { return compute(); });
95
+ }
96
+
97
+ private:
98
+ virtual T compute() const = 0;
99
+
100
+ mutable OptimisticLazy<T> value_;
101
+ };
102
+
103
+ /**
104
+ * Convenience immutable (thus thread-safe) LazyValue implementation for cases
105
+ * in which the value is not actually lazy.
106
+ */
107
+ template <class T>
108
+ class PrecomputedLazyValue : public LazyValue<T> {
109
+ public:
110
+ PrecomputedLazyValue(T value) : value_(std::move(value)) {}
111
+
112
+ const T& get() const override {
113
+ return value_;
114
+ }
115
+
116
+ private:
117
+ T value_;
118
+ };
119
+
120
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/LeftRight.h ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/Synchronized.h>
5
+ #include <array>
6
+ #include <atomic>
7
+ #include <mutex>
8
+ #include <thread>
9
+
10
+ namespace c10 {
11
+
12
+ namespace detail {
13
+
14
+ struct IncrementRAII final {
15
+ public:
16
+ explicit IncrementRAII(std::atomic<int32_t>* counter) : _counter(counter) {
17
+ _counter->fetch_add(1);
18
+ }
19
+
20
+ ~IncrementRAII() {
21
+ _counter->fetch_sub(1);
22
+ }
23
+ IncrementRAII(IncrementRAII&&) = delete;
24
+ IncrementRAII& operator=(IncrementRAII&&) = delete;
25
+
26
+ private:
27
+ std::atomic<int32_t>* _counter;
28
+
29
+ C10_DISABLE_COPY_AND_ASSIGN(IncrementRAII);
30
+ };
31
+
32
+ } // namespace detail
33
+
34
+ // LeftRight wait-free readers synchronization primitive
35
+ // https://hal.archives-ouvertes.fr/hal-01207881/document
36
+ //
37
+ // LeftRight is quite easy to use (it can make an arbitrary
38
+ // data structure permit wait-free reads), but it has some
39
+ // particular performance characteristics you should be aware
40
+ // of if you're deciding to use it:
41
+ //
42
+ // - Reads still incur an atomic write (this is how LeftRight
43
+ // keeps track of how long it needs to keep around the old
44
+ // data structure)
45
+ //
46
+ // - Writes get executed twice, to keep both the left and right
47
+ // versions up to date. So if your write is expensive or
48
+ // nondeterministic, this is also an inappropriate structure
49
+ //
50
+ // LeftRight is used fairly rarely in PyTorch's codebase. If you
51
+ // are still not sure if you need it or not, consult your local
52
+ // C++ expert.
53
+ //
54
+ template <class T>
55
+ class LeftRight final {
56
+ public:
57
+ template <class... Args>
58
+ explicit LeftRight(const Args&... args)
59
+ : _counters{{{0}, {0}}},
60
+ _foregroundCounterIndex(0),
61
+ _foregroundDataIndex(0),
62
+ _data{{T{args...}, T{args...}}} {}
63
+
64
+ // Copying and moving would not be threadsafe.
65
+ // Needs more thought and careful design to make that work.
66
+ LeftRight(const LeftRight&) = delete;
67
+ LeftRight(LeftRight&&) noexcept = delete;
68
+ LeftRight& operator=(const LeftRight&) = delete;
69
+ LeftRight& operator=(LeftRight&&) noexcept = delete;
70
+
71
+ ~LeftRight() {
72
+ // wait until any potentially running writers are finished
73
+ {
74
+ std::unique_lock<std::mutex> lock(_writeMutex);
75
+ }
76
+
77
+ // wait until any potentially running readers are finished
78
+ while (_counters[0].load() != 0 || _counters[1].load() != 0) {
79
+ std::this_thread::yield();
80
+ }
81
+ }
82
+
83
+ template <typename F>
84
+ auto read(F&& readFunc) const {
85
+ detail::IncrementRAII _increment_counter(
86
+ &_counters[_foregroundCounterIndex.load()]);
87
+
88
+ return std::forward<F>(readFunc)(_data[_foregroundDataIndex.load()]);
89
+ }
90
+
91
+ // Throwing an exception in writeFunc is ok but causes the state to be either
92
+ // the old or the new state, depending on if the first or the second call to
93
+ // writeFunc threw.
94
+ template <typename F>
95
+ auto write(F&& writeFunc) {
96
+ std::unique_lock<std::mutex> lock(_writeMutex);
97
+
98
+ return _write(std::forward<F>(writeFunc));
99
+ }
100
+
101
+ private:
102
+ template <class F>
103
+ auto _write(const F& writeFunc) {
104
+ /*
105
+ * Assume, A is in background and B in foreground. In simplified terms, we
106
+ * want to do the following:
107
+ * 1. Write to A (old background)
108
+ * 2. Switch A/B
109
+ * 3. Write to B (new background)
110
+ *
111
+ * More detailed algorithm (explanations on why this is important are below
112
+ * in code):
113
+ * 1. Write to A
114
+ * 2. Switch A/B data pointers
115
+ * 3. Wait until A counter is zero
116
+ * 4. Switch A/B counters
117
+ * 5. Wait until B counter is zero
118
+ * 6. Write to B
119
+ */
120
+
121
+ auto localDataIndex = _foregroundDataIndex.load();
122
+
123
+ // 1. Write to A
124
+ _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
125
+
126
+ // 2. Switch A/B data pointers
127
+ localDataIndex = localDataIndex ^ 1;
128
+ _foregroundDataIndex = localDataIndex;
129
+
130
+ /*
131
+ * 3. Wait until A counter is zero
132
+ *
133
+ * In the previous write run, A was foreground and B was background.
134
+ * There was a time after switching _foregroundDataIndex (B to foreground)
135
+ * and before switching _foregroundCounterIndex, in which new readers could
136
+ * have read B but incremented A's counter.
137
+ *
138
+ * In this current run, we just switched _foregroundDataIndex (A back to
139
+ * foreground), but before writing to the new background B, we have to make
140
+ * sure A's counter was zero briefly, so all these old readers are gone.
141
+ */
142
+ auto localCounterIndex = _foregroundCounterIndex.load();
143
+ _waitForBackgroundCounterToBeZero(localCounterIndex);
144
+
145
+ /*
146
+ * 4. Switch A/B counters
147
+ *
148
+ * Now that we know all readers on B are really gone, we can switch the
149
+ * counters and have new readers increment A's counter again, which is the
150
+ * correct counter since they're reading A.
151
+ */
152
+ localCounterIndex = localCounterIndex ^ 1;
153
+ _foregroundCounterIndex = localCounterIndex;
154
+
155
+ /*
156
+ * 5. Wait until B counter is zero
157
+ *
158
+ * This waits for all the readers on B that came in while both data and
159
+ * counter for B was in foreground, i.e. normal readers that happened
160
+ * outside of that brief gap between switching data and counter.
161
+ */
162
+ _waitForBackgroundCounterToBeZero(localCounterIndex);
163
+
164
+ // 6. Write to B
165
+ return _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
166
+ }
167
+
168
+ template <class F>
169
+ auto _callWriteFuncOnBackgroundInstance(
170
+ const F& writeFunc,
171
+ uint8_t localDataIndex) {
172
+ try {
173
+ return writeFunc(_data[localDataIndex ^ 1]);
174
+ } catch (...) {
175
+ // recover invariant by copying from the foreground instance
176
+ _data[localDataIndex ^ 1] = _data[localDataIndex];
177
+ // rethrow
178
+ throw;
179
+ }
180
+ }
181
+
182
+ void _waitForBackgroundCounterToBeZero(uint8_t counterIndex) {
183
+ while (_counters[counterIndex ^ 1].load() != 0) {
184
+ std::this_thread::yield();
185
+ }
186
+ }
187
+
188
+ mutable std::array<std::atomic<int32_t>, 2> _counters;
189
+ std::atomic<uint8_t> _foregroundCounterIndex;
190
+ std::atomic<uint8_t> _foregroundDataIndex;
191
+ std::array<T, 2> _data;
192
+ std::mutex _writeMutex;
193
+ };
194
+
195
+ // RWSafeLeftRightWrapper is API compatible with LeftRight and uses a
196
+ // read-write lock to protect T (data).
197
+ template <class T>
198
+ class RWSafeLeftRightWrapper final {
199
+ public:
200
+ template <class... Args>
201
+ explicit RWSafeLeftRightWrapper(const Args&... args) : data_{args...} {}
202
+
203
+ // RWSafeLeftRightWrapper is not copyable or moveable since LeftRight
204
+ // is not copyable or moveable.
205
+ RWSafeLeftRightWrapper(const RWSafeLeftRightWrapper&) = delete;
206
+ RWSafeLeftRightWrapper(RWSafeLeftRightWrapper&&) noexcept = delete;
207
+ RWSafeLeftRightWrapper& operator=(const RWSafeLeftRightWrapper&) = delete;
208
+ RWSafeLeftRightWrapper& operator=(RWSafeLeftRightWrapper&&) noexcept = delete;
209
+ ~RWSafeLeftRightWrapper() = default;
210
+
211
+ template <typename F>
212
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
213
+ auto read(F&& readFunc) const {
214
+ return data_.withLock(
215
+ [&readFunc](T const& data) { return std::forward<F>(readFunc)(data); });
216
+ }
217
+
218
+ template <typename F>
219
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
220
+ auto write(F&& writeFunc) {
221
+ return data_.withLock(
222
+ [&writeFunc](T& data) { return std::forward<F>(writeFunc)(data); });
223
+ }
224
+
225
+ private:
226
+ c10::Synchronized<T> data_;
227
+ };
228
+
229
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Load.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Macros.h>
3
+ #include <cstring>
4
+
5
+ namespace c10 {
6
+ namespace detail {
7
+
8
+ template <typename T>
9
+ struct LoadImpl {
10
+ C10_HOST_DEVICE static T apply(const void* src) {
11
+ return *reinterpret_cast<const T*>(src);
12
+ }
13
+ };
14
+
15
+ template <>
16
+ struct LoadImpl<bool> {
17
+ C10_HOST_DEVICE static bool apply(const void* src) {
18
+ static_assert(sizeof(bool) == sizeof(char));
19
+ // NOTE: [Loading boolean values]
20
+ // Protect against invalid boolean values by loading as a byte
21
+ // first, then converting to bool (see gh-54789).
22
+ return *reinterpret_cast<const unsigned char*>(src);
23
+ }
24
+ };
25
+
26
+ } // namespace detail
27
+
28
+ template <typename T>
29
+ C10_HOST_DEVICE constexpr T load(const void* src) {
30
+ return c10::detail::LoadImpl<T>::apply(src);
31
+ }
32
+
33
+ template <typename scalar_t>
34
+ C10_HOST_DEVICE constexpr scalar_t load(const scalar_t* src) {
35
+ return c10::detail::LoadImpl<scalar_t>::apply(src);
36
+ }
37
+
38
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Logging.h ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_LOGGING_H_
2
+ #define C10_UTIL_LOGGING_H_
3
+
4
+ #include <climits>
5
+ #include <exception>
6
+ #include <functional>
7
+ #include <limits>
8
+ #include <sstream>
9
+
10
+ #include <c10/macros/Macros.h>
11
+ #include <c10/util/Backtrace.h>
12
+ #include <c10/util/Exception.h>
13
+ #include <c10/util/Flags.h>
14
+ #include <c10/util/StringUtil.h>
15
+
16
+ // CAFFE2_LOG_THRESHOLD is a compile time flag that would allow us to turn off
17
+ // logging at compile time so no logging message below that level is produced
18
+ // at all. The value should be between INT_MIN and CAFFE_FATAL.
19
+ #ifndef CAFFE2_LOG_THRESHOLD
20
+ // If we have not defined the compile time log threshold, we keep all the
21
+ // log cases.
22
+ #define CAFFE2_LOG_THRESHOLD INT_MIN
23
+ #endif // CAFFE2_LOG_THRESHOLD
24
+
25
+ // Below are different implementations for glog and non-glog cases.
26
+ #ifdef C10_USE_GLOG
27
+ #include <c10/util/logging_is_google_glog.h>
28
+ #else // !C10_USE_GLOG
29
+ #include <c10/util/logging_is_not_google_glog.h>
30
+ #endif // C10_USE_GLOG
31
+
32
+ C10_DECLARE_int(caffe2_log_level);
33
+ C10_DECLARE_bool(caffe2_use_fatal_for_enforce);
34
+
35
+ // Some versions of GLOG support less-spammy version of LOG_EVERY_MS. If it's
36
+ // not available - just short-circuit to the always working one one.
37
+ // We define the C10_ name to avoid confusing other files
38
+ #ifdef LOG_EVERY_MS
39
+ #define C10_LOG_EVERY_MS(severity, ms) LOG_EVERY_MS(severity, ms)
40
+ #else
41
+ #define C10_LOG_EVERY_MS(severity, ms) LOG(severity)
42
+ #endif
43
+
44
+ // Same for LOG_FIRST_N
45
+ #ifdef LOG_FIRST_N
46
+ #define C10_LOG_FIRST_N(severity, n) LOG_FIRST_N(severity, n)
47
+ #else
48
+ #define C10_LOG_FIRST_N(severity, n) LOG(severity)
49
+ #endif
50
+
51
+ // Same for LOG_EVERY_N
52
+ #ifdef LOG_EVERY_N
53
+ #define C10_LOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
54
+ #else
55
+ #define C10_LOG_EVERY_N(severity, n) LOG(severity)
56
+ #endif
57
+
58
+ namespace c10 {
59
+
60
+ #if !defined(C10_NODEPRECATED)
61
+ using std::string;
62
+ #endif
63
+
64
+ // Functions that we use for initialization.
65
+ C10_API bool InitCaffeLogging(int* argc, char** argv);
66
+ C10_API void UpdateLoggingLevelsFromFlags();
67
+
68
+ [[noreturn]] C10_API void ThrowEnforceNotMet(
69
+ const char* file,
70
+ const int line,
71
+ const char* condition,
72
+ const std::string& msg,
73
+ const void* caller = nullptr);
74
+
75
+ [[noreturn]] C10_API void ThrowEnforceNotMet(
76
+ const char* file,
77
+ const int line,
78
+ const char* condition,
79
+ const char* msg,
80
+ const void* caller = nullptr);
81
+
82
+ [[noreturn]] C10_API inline void ThrowEnforceNotMet(
83
+ const char* file,
84
+ const int line,
85
+ const char* condition,
86
+ detail::CompileTimeEmptyString /*msg*/,
87
+ const void* caller = nullptr) {
88
+ ThrowEnforceNotMet(file, line, condition, "", caller);
89
+ }
90
+
91
+ [[noreturn]] C10_API void ThrowEnforceFiniteNotMet(
92
+ const char* file,
93
+ const int line,
94
+ const char* condition,
95
+ const std::string& msg,
96
+ const void* caller = nullptr);
97
+
98
+ [[noreturn]] C10_API void ThrowEnforceFiniteNotMet(
99
+ const char* file,
100
+ const int line,
101
+ const char* condition,
102
+ const char* msg,
103
+ const void* caller = nullptr);
104
+
105
+ [[noreturn]] C10_API inline void ThrowEnforceFiniteNotMet(
106
+ const char* file,
107
+ const int line,
108
+ const char* condition,
109
+ detail::CompileTimeEmptyString /*msg*/,
110
+ const void* caller = nullptr) {
111
+ ThrowEnforceFiniteNotMet(file, line, condition, "", caller);
112
+ }
113
+
114
+ constexpr bool IsUsingGoogleLogging() {
115
+ #ifdef C10_USE_GLOG
116
+ return true;
117
+ #else
118
+ return false;
119
+ #endif
120
+ }
121
+
122
+ /**
123
+ * A utility to allow one to show log info to stderr after the program starts.
124
+ *
125
+ * This is similar to calling GLOG's --logtostderr, or setting caffe2_log_level
126
+ * to smaller than INFO. You are recommended to only use this in a few sparse
127
+ * cases, such as when you want to write a tutorial or something. Normally, use
128
+ * the commandline flags to set the log level.
129
+ */
130
+ C10_API void ShowLogInfoToStderr();
131
+
132
+ C10_API void SetStackTraceFetcher(std::function<::c10::Backtrace()> fetcher);
133
+
134
+ /**
135
+ * Convenience function for non-lazy stack trace fetchers. The Backtrace
136
+ * overload should be preferred when stringifying the backtrace is expensive.
137
+ */
138
+ C10_API void SetStackTraceFetcher(std::function<std::string()> fetcher);
139
+
140
+ using EnforceNotMet = ::c10::Error;
141
+
142
+ #define CAFFE_ENFORCE(condition, ...) \
143
+ do { \
144
+ if (C10_UNLIKELY(!(condition))) { \
145
+ ::c10::ThrowEnforceNotMet( \
146
+ __FILE__, __LINE__, #condition, ::c10::str(__VA_ARGS__)); \
147
+ } \
148
+ } while (false)
149
+
150
+ #define CAFFE_ENFORCE_FINITE(condition, ...) \
151
+ do { \
152
+ if (C10_UNLIKELY(!(condition))) { \
153
+ ::c10::ThrowEnforceFiniteNotMet( \
154
+ __FILE__, __LINE__, #condition, ::c10::str(__VA_ARGS__)); \
155
+ } \
156
+ } while (false)
157
+
158
+ #define CAFFE_ENFORCE_WITH_CALLER(condition, ...) \
159
+ do { \
160
+ if (C10_UNLIKELY(!(condition))) { \
161
+ ::c10::ThrowEnforceNotMet( \
162
+ __FILE__, __LINE__, #condition, ::c10::str(__VA_ARGS__), this); \
163
+ } \
164
+ } while (false)
165
+
166
+ #define CAFFE_THROW(...) \
167
+ ::c10::ThrowEnforceNotMet(__FILE__, __LINE__, "", ::c10::str(__VA_ARGS__))
168
+
169
+ /**
170
+ * Rich logging messages
171
+ *
172
+ * CAFFE_ENFORCE_THAT can be used with one of the "checker functions" that
173
+ * capture input argument values and add it to the exception message. E.g.
174
+ * `CAFFE_ENFORCE_THAT(Equals(foo(x), bar(y)), "Optional additional message")`
175
+ * would evaluate both foo and bar only once and if the results are not equal -
176
+ * include them in the exception message.
177
+ *
178
+ * Some of the basic checker functions like Equals or Greater are already
179
+ * defined below. Other header might define customized checkers by adding
180
+ * functions to caffe2::enforce_detail namespace. For example:
181
+ *
182
+ * namespace caffe2 { namespace enforce_detail {
183
+ * inline EnforceFailMessage IsVector(const vector<int64_t>& shape) {
184
+ * if (shape.size() == 1) { return EnforceOK(); }
185
+ * return c10::str("Shape ", shape, " is not a vector");
186
+ * }
187
+ * }}
188
+ *
189
+ * With further usages like `CAFFE_ENFORCE_THAT(IsVector(Input(0).dims()))`
190
+ *
191
+ * Convenient wrappers for binary operations like CAFFE_ENFORCE_EQ are provided
192
+ * too. Please use them instead of TORCH_CHECK_EQ and friends for failures in
193
+ * user-provided input.
194
+ */
195
+
196
+ namespace enforce_detail {
197
+
198
+ template <typename T1, typename T2>
199
+ std::string enforceFailMsgImpl(const T1& x, const T2& y) {
200
+ return c10::str(x, " vs ", y);
201
+ }
202
+
203
+ template <typename T1, typename T2, typename... Args>
204
+ std::string enforceFailMsgImpl(const T1& x, const T2& y, const Args&... args) {
205
+ return c10::str(x, " vs ", y, ". ", args...);
206
+ }
207
+
208
+ template <typename Pred, typename T1, typename T2, typename GetFailMsgFunc>
209
+ void enforceThatImpl(
210
+ Pred p,
211
+ const T1& lhs,
212
+ const T2& rhs,
213
+ const char* file,
214
+ int line,
215
+ const char* expr,
216
+ const void* caller,
217
+ GetFailMsgFunc getFailMsg) {
218
+ if (C10_UNLIKELY(!(p(lhs, rhs)))) {
219
+ ::c10::ThrowEnforceNotMet(file, line, expr, getFailMsg(lhs, rhs), caller);
220
+ }
221
+ }
222
+
223
+ #define CAFFE_ENFORCE_THAT_IMPL(op, lhs, rhs, expr, ...) \
224
+ ::c10::enforce_detail::enforceThatImpl( \
225
+ op, \
226
+ (lhs), \
227
+ (rhs), \
228
+ __FILE__, \
229
+ __LINE__, \
230
+ expr, \
231
+ nullptr, \
232
+ [&](const auto& arg1, const auto& arg2) { \
233
+ return ::c10::enforce_detail::enforceFailMsgImpl( \
234
+ arg1, arg2, ##__VA_ARGS__); \
235
+ })
236
+
237
+ #define CAFFE_ENFORCE_THAT_IMPL_WITH_CALLER(op, lhs, rhs, expr, ...) \
238
+ ::c10::enforce_detail::enforceThatImpl( \
239
+ op, \
240
+ (lhs), \
241
+ (rhs), \
242
+ __FILE__, \
243
+ __LINE__, \
244
+ expr, \
245
+ this, \
246
+ [&](const auto& arg1, const auto& arg2) { \
247
+ return ::c10::enforce_detail::enforceFailMsgImpl( \
248
+ arg1, arg2, ##__VA_ARGS__); \
249
+ })
250
+
251
+ } // namespace enforce_detail
252
+
253
+ #define CAFFE_ENFORCE_THAT(cmp, op, lhs, rhs, ...) \
254
+ CAFFE_ENFORCE_THAT_IMPL(cmp, lhs, rhs, #lhs " " #op " " #rhs, ##__VA_ARGS__)
255
+
256
+ #define CAFFE_ENFORCE_BINARY_OP(cmp, op, x, y, ...) \
257
+ CAFFE_ENFORCE_THAT_IMPL(cmp, x, y, #x " " #op " " #y, ##__VA_ARGS__)
258
+ #define CAFFE_ENFORCE_EQ(x, y, ...) \
259
+ CAFFE_ENFORCE_BINARY_OP(std::equal_to<void>(), ==, x, y, ##__VA_ARGS__)
260
+ #define CAFFE_ENFORCE_NE(x, y, ...) \
261
+ CAFFE_ENFORCE_BINARY_OP(std::not_equal_to<void>(), !=, x, y, ##__VA_ARGS__)
262
+ #define CAFFE_ENFORCE_LE(x, y, ...) \
263
+ CAFFE_ENFORCE_BINARY_OP(std::less_equal<void>(), <=, x, y, ##__VA_ARGS__)
264
+ #define CAFFE_ENFORCE_LT(x, y, ...) \
265
+ CAFFE_ENFORCE_BINARY_OP(std::less<void>(), <, x, y, ##__VA_ARGS__)
266
+ #define CAFFE_ENFORCE_GE(x, y, ...) \
267
+ CAFFE_ENFORCE_BINARY_OP(std::greater_equal<void>(), >=, x, y, ##__VA_ARGS__)
268
+ #define CAFFE_ENFORCE_GT(x, y, ...) \
269
+ CAFFE_ENFORCE_BINARY_OP(std::greater<void>(), >, x, y, ##__VA_ARGS__)
270
+
271
+ #define CAFFE_ENFORCE_BINARY_OP_WITH_CALLER(cmp, op, x, y, ...) \
272
+ CAFFE_ENFORCE_THAT_IMPL_WITH_CALLER( \
273
+ cmp, x, y, #x " " #op " " #y, ##__VA_ARGS__)
274
+ #define CAFFE_ENFORCE_EQ_WITH_CALLER(x, y, ...) \
275
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER( \
276
+ std::equal_to<void>(), ==, x, y, ##__VA_ARGS__)
277
+ #define CAFFE_ENFORCE_NE_WITH_CALLER(x, y, ...) \
278
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER( \
279
+ std::not_equal_to<void>(), !=, x, y, ##__VA_ARGS__)
280
+ #define CAFFE_ENFORCE_LE_WITH_CALLER(x, y, ...) \
281
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER( \
282
+ std::less_equal<void>(), <=, x, y, ##__VA_ARGS__)
283
+ #define CAFFE_ENFORCE_LT_WITH_CALLER(x, y, ...) \
284
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER(std::less<void>(), <, x, y, ##__VA_ARGS__)
285
+ #define CAFFE_ENFORCE_GE_WITH_CALLER(x, y, ...) \
286
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER( \
287
+ std::greater_equal<void>(), >=, x, y, ##__VA_ARGS__)
288
+ #define CAFFE_ENFORCE_GT_WITH_CALLER(x, y, ...) \
289
+ CAFFE_ENFORCE_BINARY_OP_WITH_CALLER( \
290
+ std::greater<void>(), >, x, y, ##__VA_ARGS__)
291
+
292
+ struct IValue;
293
+ class C10_API EventSampledHandler {
294
+ public:
295
+ virtual void log(
296
+ std::string_view model_id,
297
+ const std::vector<c10::IValue>& args) = 0;
298
+ virtual ~EventSampledHandler() = default;
299
+ };
300
+
301
+ #define C10_LOG_EVENT_SAMPLED(event, ...) \
302
+ static const std::unique_ptr<::c10::EventSampledHandler>& \
303
+ _##event##EventSampledHandler = ::c10::GetEventSampledHandler(#event); \
304
+ if (_##event##EventSampledHandler) { \
305
+ _##event##EventSampledHandler->log(__VA_ARGS__); \
306
+ }
307
+
308
+ // Must be called in the main thread before any other threads are spawned.
309
+ C10_API void InitEventSampledHandlers(
310
+ std::vector<
311
+ std::pair<std::string_view, std::unique_ptr<EventSampledHandler>>>);
312
+ C10_API const std::unique_ptr<EventSampledHandler>& GetEventSampledHandler(
313
+ std::string_view);
314
+
315
+ /**
316
+ * Very lightweight logging for the first time API usage. It's beneficial for
317
+ * tracking of individual functionality usage in larger applications.
318
+ *
319
+ * In order to ensure light-weightedness of logging, we utilize static variable
320
+ * trick - LogAPIUsage will be invoked only once and further invocations will
321
+ * just do an atomic check.
322
+ *
323
+ * Example:
324
+ * // Logs caller info with an arbitrary text event, if there is a usage.
325
+ * C10_LOG_API_USAGE_ONCE("my_api");
326
+ */
327
+ #define C10_LOG_API_USAGE_ONCE(...) \
328
+ [[maybe_unused]] static bool C10_ANONYMOUS_VARIABLE(logFlag) = \
329
+ ::c10::detail::LogAPIUsageFakeReturn(__VA_ARGS__);
330
+
331
+ // API usage logging capabilities
332
+ C10_API void SetAPIUsageLogger(std::function<void(const std::string&)> logger);
333
+ C10_API void LogAPIUsage(const std::string& context);
334
+
335
+ C10_API void SetAPIUsageMetadataLogger(
336
+ std::function<void(
337
+ const std::string&,
338
+ const std::map<std::string, std::string>& metadata_map)> logger);
339
+ C10_API void LogAPIUsageMetadata(
340
+ const std::string& context,
341
+ const std::map<std::string, std::string>& metadata_map);
342
+
343
+ // PyTorch ddp usage logging capabilities
344
+ // DDPLoggingData holds data that can be logged in applications
345
+ // for analysis and debugging. Data structure is defined in
346
+ // c10 directory so that it can be easily imported by both c10
347
+ // and torch files.
348
+ struct DDPLoggingData {
349
+ // logging fields that are string types.
350
+ std::map<std::string, std::string> strs_map;
351
+ // logging fields that are int64_t types.
352
+ std::map<std::string, int64_t> ints_map;
353
+ };
354
+
355
+ C10_API void SetPyTorchDDPUsageLogger(
356
+ std::function<void(const DDPLoggingData&)> logger);
357
+ C10_API void LogPyTorchDDPUsage(const DDPLoggingData& ddpData);
358
+
359
+ namespace detail {
360
+ // Return value is needed to do the static variable initialization trick
361
+ C10_API bool LogAPIUsageFakeReturn(const std::string& context);
362
+ } // namespace detail
363
+
364
+ // Initializes the c10 logger.
365
+ C10_API void initLogging();
366
+
367
+ // Sets the rank, which will be included in log messages
368
+ C10_API void SetGlobalRank(int64_t rank);
369
+
370
+ } // namespace c10
371
+
372
+ #endif // C10_UTIL_LOGGING_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/MathConstants.h ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/BFloat16.h>
5
+ #include <c10/util/Half.h>
6
+
7
+ C10_CLANG_DIAGNOSTIC_PUSH()
8
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion")
9
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion")
10
+ #endif
11
+
12
+ namespace c10 {
13
+ // TODO: Replace me with inline constexpr variable when C++17 becomes available
14
+ namespace detail {
15
+ template <typename T>
16
+ C10_HOST_DEVICE inline constexpr T e() {
17
+ return static_cast<T>(2.718281828459045235360287471352662);
18
+ }
19
+
20
+ template <typename T>
21
+ C10_HOST_DEVICE inline constexpr T euler() {
22
+ return static_cast<T>(0.577215664901532860606512090082402);
23
+ }
24
+
25
+ template <typename T>
26
+ C10_HOST_DEVICE inline constexpr T frac_1_pi() {
27
+ return static_cast<T>(0.318309886183790671537767526745028);
28
+ }
29
+
30
+ template <typename T>
31
+ C10_HOST_DEVICE inline constexpr T frac_1_sqrt_pi() {
32
+ return static_cast<T>(0.564189583547756286948079451560772);
33
+ }
34
+
35
+ template <typename T>
36
+ C10_HOST_DEVICE inline constexpr T frac_sqrt_2() {
37
+ return static_cast<T>(0.707106781186547524400844362104849);
38
+ }
39
+
40
+ template <typename T>
41
+ C10_HOST_DEVICE inline constexpr T frac_sqrt_3() {
42
+ return static_cast<T>(0.577350269189625764509148780501957);
43
+ }
44
+
45
+ template <typename T>
46
+ C10_HOST_DEVICE inline constexpr T golden_ratio() {
47
+ return static_cast<T>(1.618033988749894848204586834365638);
48
+ }
49
+
50
+ template <typename T>
51
+ C10_HOST_DEVICE inline constexpr T ln_10() {
52
+ return static_cast<T>(2.302585092994045684017991454684364);
53
+ }
54
+
55
+ template <typename T>
56
+ C10_HOST_DEVICE inline constexpr T ln_2() {
57
+ return static_cast<T>(0.693147180559945309417232121458176);
58
+ }
59
+
60
+ template <typename T>
61
+ C10_HOST_DEVICE inline constexpr T log_10_e() {
62
+ return static_cast<T>(0.434294481903251827651128918916605);
63
+ }
64
+
65
+ template <typename T>
66
+ C10_HOST_DEVICE inline constexpr T log_2_e() {
67
+ return static_cast<T>(1.442695040888963407359924681001892);
68
+ }
69
+
70
+ template <typename T>
71
+ C10_HOST_DEVICE inline constexpr T pi() {
72
+ return static_cast<T>(3.141592653589793238462643383279502);
73
+ }
74
+
75
+ template <typename T>
76
+ C10_HOST_DEVICE inline constexpr T sqrt_2() {
77
+ return static_cast<T>(1.414213562373095048801688724209698);
78
+ }
79
+
80
+ template <typename T>
81
+ C10_HOST_DEVICE inline constexpr T sqrt_3() {
82
+ return static_cast<T>(1.732050807568877293527446341505872);
83
+ }
84
+
85
+ template <>
86
+ C10_HOST_DEVICE inline constexpr BFloat16 pi<BFloat16>() {
87
+ // According to
88
+ // https://en.wikipedia.org/wiki/Bfloat16_floating-point_format#Special_values
89
+ // pi is encoded as 4049
90
+ return BFloat16(0x4049, BFloat16::from_bits());
91
+ }
92
+
93
+ template <>
94
+ C10_HOST_DEVICE inline constexpr Half pi<Half>() {
95
+ return Half(0x4248, Half::from_bits());
96
+ }
97
+ } // namespace detail
98
+
99
+ template <typename T>
100
+ constexpr T e = c10::detail::e<T>();
101
+
102
+ template <typename T>
103
+ constexpr T euler = c10::detail::euler<T>();
104
+
105
+ template <typename T>
106
+ constexpr T frac_1_pi = c10::detail::frac_1_pi<T>();
107
+
108
+ template <typename T>
109
+ constexpr T frac_1_sqrt_pi = c10::detail::frac_1_sqrt_pi<T>();
110
+
111
+ template <typename T>
112
+ constexpr T frac_sqrt_2 = c10::detail::frac_sqrt_2<T>();
113
+
114
+ template <typename T>
115
+ constexpr T frac_sqrt_3 = c10::detail::frac_sqrt_3<T>();
116
+
117
+ template <typename T>
118
+ constexpr T golden_ratio = c10::detail::golden_ratio<T>();
119
+
120
+ template <typename T>
121
+ constexpr T ln_10 = c10::detail::ln_10<T>();
122
+
123
+ template <typename T>
124
+ constexpr T ln_2 = c10::detail::ln_2<T>();
125
+
126
+ template <typename T>
127
+ constexpr T log_10_e = c10::detail::log_10_e<T>();
128
+
129
+ template <typename T>
130
+ constexpr T log_2_e = c10::detail::log_2_e<T>();
131
+
132
+ template <typename T>
133
+ constexpr T pi = c10::detail::pi<T>();
134
+
135
+ template <typename T>
136
+ constexpr T sqrt_2 = c10::detail::sqrt_2<T>();
137
+
138
+ template <typename T>
139
+ constexpr T sqrt_3 = c10::detail::sqrt_3<T>();
140
+ } // namespace c10
141
+
142
+ C10_CLANG_DIAGNOSTIC_POP()
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/MaybeOwned.h ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/Exception.h>
5
+
6
+ #include <memory>
7
+ #include <type_traits>
8
+ #include <utility>
9
+
10
+ namespace c10 {
11
+
12
+ /// MaybeOwnedTraits<T> describes how to borrow from T. Here is how we
13
+ /// can implement borrowing from an arbitrary type T using a raw
14
+ /// pointer to const:
15
+ template <typename T>
16
+ struct MaybeOwnedTraitsGenericImpl {
17
+ using owned_type = T;
18
+ using borrow_type = const T*;
19
+
20
+ static borrow_type createBorrow(const owned_type& from) {
21
+ return &from;
22
+ }
23
+
24
+ static void assignBorrow(borrow_type& lhs, borrow_type rhs) {
25
+ lhs = rhs;
26
+ }
27
+
28
+ static void destroyBorrow(borrow_type& /*toDestroy*/) {}
29
+
30
+ static const owned_type& referenceFromBorrow(const borrow_type& borrow) {
31
+ return *borrow;
32
+ }
33
+
34
+ static const owned_type* pointerFromBorrow(const borrow_type& borrow) {
35
+ return borrow;
36
+ }
37
+
38
+ static bool debugBorrowIsValid(const borrow_type& borrow) {
39
+ return borrow != nullptr;
40
+ }
41
+ };
42
+
43
+ /// It is possible to eliminate the extra layer of indirection for
44
+ /// borrows for some types that we control. For examples, see
45
+ /// intrusive_ptr.h and TensorBody.h.
46
+
47
+ template <typename T>
48
+ struct MaybeOwnedTraits;
49
+
50
+ // Explicitly enable MaybeOwned<shared_ptr<T>>, rather than allowing
51
+ // MaybeOwned to be used for any type right away.
52
+ template <typename T>
53
+ struct MaybeOwnedTraits<std::shared_ptr<T>>
54
+ : public MaybeOwnedTraitsGenericImpl<std::shared_ptr<T>> {};
55
+
56
+ /// A smart pointer around either a borrowed or owned T. When
57
+ /// constructed with borrowed(), the caller MUST ensure that the
58
+ /// borrowed-from argument outlives this MaybeOwned<T>. Compare to
59
+ /// Rust's std::borrow::Cow
60
+ /// (https://doc.rust-lang.org/std/borrow/enum.Cow.html), but note
61
+ /// that it is probably not suitable for general use because C++ has
62
+ /// no borrow checking. Included here to support
63
+ /// Tensor::expect_contiguous.
64
+ template <typename T>
65
+ class MaybeOwned final {
66
+ using borrow_type = typename MaybeOwnedTraits<T>::borrow_type;
67
+ using owned_type = typename MaybeOwnedTraits<T>::owned_type;
68
+
69
+ bool isBorrowed_;
70
+ union {
71
+ borrow_type borrow_;
72
+ owned_type own_;
73
+ };
74
+
75
+ /// Don't use this; use borrowed() instead.
76
+ explicit MaybeOwned(const owned_type& t)
77
+ : isBorrowed_(true), borrow_(MaybeOwnedTraits<T>::createBorrow(t)) {}
78
+
79
+ /// Don't use this; use owned() instead.
80
+ explicit MaybeOwned(T&& t) noexcept(std::is_nothrow_move_constructible_v<T>)
81
+ : isBorrowed_(false), own_(std::move(t)) {}
82
+
83
+ /// Don't use this; use owned() instead.
84
+ template <class... Args>
85
+ explicit MaybeOwned(std::in_place_t, Args&&... args)
86
+ : isBorrowed_(false), own_(std::forward<Args>(args)...) {}
87
+
88
+ public:
89
+ explicit MaybeOwned() : isBorrowed_(true), borrow_() {}
90
+
91
+ // Copying a borrow yields another borrow of the original, as with a
92
+ // T*. Copying an owned T yields another owned T for safety: no
93
+ // chains of borrowing by default! (Note you could get that behavior
94
+ // with MaybeOwned<T>::borrowed(*rhs) if you wanted it.)
95
+ MaybeOwned(const MaybeOwned& rhs) : isBorrowed_(rhs.isBorrowed_) {
96
+ if (C10_LIKELY(rhs.isBorrowed_)) {
97
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
98
+ } else {
99
+ new (&own_) T(rhs.own_);
100
+ }
101
+ }
102
+
103
+ MaybeOwned& operator=(const MaybeOwned& rhs) {
104
+ if (this == &rhs) {
105
+ return *this;
106
+ }
107
+ if (C10_UNLIKELY(!isBorrowed_)) {
108
+ if (rhs.isBorrowed_) {
109
+ own_.~T();
110
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
111
+ isBorrowed_ = true;
112
+ } else {
113
+ own_ = rhs.own_;
114
+ }
115
+ } else {
116
+ if (C10_LIKELY(rhs.isBorrowed_)) {
117
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
118
+ } else {
119
+ MaybeOwnedTraits<T>::destroyBorrow(borrow_);
120
+ new (&own_) T(rhs.own_);
121
+ isBorrowed_ = false;
122
+ }
123
+ }
124
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isBorrowed_ == rhs.isBorrowed_);
125
+ return *this;
126
+ }
127
+
128
+ MaybeOwned(MaybeOwned&& rhs) noexcept(
129
+ // NOLINTNEXTLINE(*-noexcept-move-*)
130
+ std::is_nothrow_move_constructible_v<T> &&
131
+ std::is_nothrow_move_assignable_v<borrow_type>)
132
+ : isBorrowed_(rhs.isBorrowed_) {
133
+ if (C10_LIKELY(rhs.isBorrowed_)) {
134
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
135
+ } else {
136
+ new (&own_) T(std::move(rhs.own_));
137
+ }
138
+ }
139
+
140
+ MaybeOwned& operator=(MaybeOwned&& rhs) noexcept(
141
+ std::is_nothrow_move_assignable_v<T> &&
142
+ std::is_nothrow_move_assignable_v<borrow_type> &&
143
+ std::is_nothrow_move_constructible_v<T> &&
144
+ // NOLINTNEXTLINE(*-noexcept-move-*)
145
+ std::is_nothrow_destructible_v<T> &&
146
+ std::is_nothrow_destructible_v<borrow_type>) {
147
+ if (this == &rhs) {
148
+ return *this;
149
+ }
150
+ if (C10_UNLIKELY(!isBorrowed_)) {
151
+ if (rhs.isBorrowed_) {
152
+ own_.~T();
153
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
154
+ isBorrowed_ = true;
155
+ } else {
156
+ own_ = std::move(rhs.own_);
157
+ }
158
+ } else {
159
+ if (C10_LIKELY(rhs.isBorrowed_)) {
160
+ MaybeOwnedTraits<T>::assignBorrow(borrow_, rhs.borrow_);
161
+ } else {
162
+ MaybeOwnedTraits<T>::destroyBorrow(borrow_);
163
+ new (&own_) T(std::move(rhs.own_));
164
+ isBorrowed_ = false;
165
+ }
166
+ }
167
+ return *this;
168
+ }
169
+
170
+ static MaybeOwned borrowed(const T& t) {
171
+ return MaybeOwned(t);
172
+ }
173
+
174
+ static MaybeOwned owned(T&& t) noexcept(
175
+ std::is_nothrow_move_constructible_v<T>) {
176
+ return MaybeOwned(std::move(t));
177
+ }
178
+
179
+ template <class... Args>
180
+ static MaybeOwned owned(std::in_place_t, Args&&... args) {
181
+ return MaybeOwned(std::in_place, std::forward<Args>(args)...);
182
+ }
183
+
184
+ ~MaybeOwned() noexcept(
185
+ // NOLINTNEXTLINE(*-noexcept-destructor)
186
+ std::is_nothrow_destructible_v<T> &&
187
+ std::is_nothrow_destructible_v<borrow_type>) {
188
+ if (C10_UNLIKELY(!isBorrowed_)) {
189
+ own_.~T();
190
+ } else {
191
+ MaybeOwnedTraits<T>::destroyBorrow(borrow_);
192
+ }
193
+ }
194
+
195
+ // This is an implementation detail! You should know what you're doing
196
+ // if you are testing this. If you just want to guarantee ownership move
197
+ // this into a T
198
+ bool unsafeIsBorrowed() const {
199
+ return isBorrowed_;
200
+ }
201
+
202
+ const T& operator*() const& {
203
+ if (isBorrowed_) {
204
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
205
+ MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
206
+ }
207
+ return C10_LIKELY(isBorrowed_)
208
+ ? MaybeOwnedTraits<T>::referenceFromBorrow(borrow_)
209
+ : own_;
210
+ }
211
+
212
+ const T* operator->() const {
213
+ if (isBorrowed_) {
214
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
215
+ MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
216
+ }
217
+ return C10_LIKELY(isBorrowed_)
218
+ ? MaybeOwnedTraits<T>::pointerFromBorrow(borrow_)
219
+ : &own_;
220
+ }
221
+
222
+ // If borrowed, copy the underlying T. If owned, move from
223
+ // it. borrowed/owned state remains the same, and either we
224
+ // reference the same borrow as before or we are an owned moved-from
225
+ // T.
226
+ T operator*() && {
227
+ if (isBorrowed_) {
228
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
229
+ MaybeOwnedTraits<T>::debugBorrowIsValid(borrow_));
230
+ return MaybeOwnedTraits<T>::referenceFromBorrow(borrow_);
231
+ } else {
232
+ return std::move(own_);
233
+ }
234
+ }
235
+ };
236
+
237
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Metaprogramming.h ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/TypeList.h>
4
+ #include <type_traits>
5
+
6
+ namespace c10::guts {
7
+
8
+ /**
9
+ * Access information about result type or arguments from a function type.
10
+ * Example:
11
+ * using A = function_traits<int (float, double)>::return_type // A == int
12
+ * using A = function_traits<int (float, double)>::parameter_types::tuple_type
13
+ * // A == tuple<float, double>
14
+ */
15
+ template <class Func>
16
+ struct function_traits {
17
+ static_assert(
18
+ !std::is_same_v<Func, Func>,
19
+ "In function_traits<Func>, Func must be a plain function type.");
20
+ };
21
+ template <class Result, class... Args>
22
+ struct function_traits<Result(Args...)> {
23
+ using func_type = Result(Args...);
24
+ using return_type = Result;
25
+ using parameter_types = typelist::typelist<Args...>;
26
+ static constexpr auto number_of_parameters = sizeof...(Args);
27
+ };
28
+
29
+ /**
30
+ * infer_function_traits: creates a `function_traits` type for a simple
31
+ * function (pointer) or functor (lambda/struct). Currently does not support
32
+ * class methods.
33
+ */
34
+
35
+ template <typename Functor>
36
+ struct infer_function_traits {
37
+ using type = function_traits<
38
+ c10::guts::detail::strip_class_t<decltype(&Functor::operator())>>;
39
+ };
40
+
41
+ template <typename Result, typename... Args>
42
+ struct infer_function_traits<Result (*)(Args...)> {
43
+ using type = function_traits<Result(Args...)>;
44
+ };
45
+
46
+ template <typename Result, typename... Args>
47
+ struct infer_function_traits<Result(Args...)> {
48
+ using type = function_traits<Result(Args...)>;
49
+ };
50
+
51
+ template <typename T>
52
+ using infer_function_traits_t = typename infer_function_traits<T>::type;
53
+
54
+ /**
55
+ * make_function_traits: creates a `function_traits` type given a Return type
56
+ * and a typelist of Argument types
57
+ *
58
+ * Example:
59
+ * bool f(int, int);
60
+ *
61
+ * infer_function_traits_t<f> == make_function_traits_t<bool,
62
+ * typelist::typelist<int, int>>
63
+ */
64
+ template <typename Result, typename ArgList>
65
+ struct make_function_traits {
66
+ static_assert(
67
+ false_t<ArgList>::value,
68
+ "In guts::make_function_traits<Result, TypeList>, the ArgList argument must be typelist<...>.");
69
+ };
70
+
71
+ template <typename Result, typename... Args>
72
+ struct make_function_traits<Result, typelist::typelist<Args...>> {
73
+ using type = function_traits<Result(Args...)>;
74
+ };
75
+
76
+ template <typename Result, typename ArgList>
77
+ using make_function_traits_t =
78
+ typename make_function_traits<Result, ArgList>::type;
79
+
80
+ /**
81
+ * make_offset_index_sequence<Start, N>
82
+ * Like make_index_sequence<N>, but starting from Start instead of 0.
83
+ *
84
+ * Example:
85
+ * make_offset_index_sequence<10, 3> == std::index_sequence<10, 11, 12>
86
+ */
87
+ template <size_t Start, size_t N, size_t... Is>
88
+ struct make_offset_index_sequence_impl
89
+ : make_offset_index_sequence_impl<Start, N - 1, Start + N - 1, Is...> {
90
+ static_assert(
91
+ static_cast<int>(Start) >= 0,
92
+ "make_offset_index_sequence: Start < 0");
93
+ static_assert(static_cast<int>(N) >= 0, "make_offset_index_sequence: N < 0");
94
+ };
95
+
96
+ template <size_t Start, size_t... Is>
97
+ struct make_offset_index_sequence_impl<Start, 0, Is...> {
98
+ typedef std::index_sequence<Is...> type;
99
+ };
100
+
101
+ template <size_t Start, size_t N>
102
+ using make_offset_index_sequence =
103
+ typename make_offset_index_sequence_impl<Start, N>::type;
104
+
105
+ /**
106
+ * Use tuple_elements to extract a position-indexed subset of elements
107
+ * from the argument tuple into a result tuple.
108
+ *
109
+ * Example:
110
+ * std::tuple<int, const char*, double> t = std::make_tuple(0, "HEY", 2.0);
111
+ * std::tuple<int, double> result = tuple_elements(t, std::index_sequence<0,
112
+ * 2>());
113
+ */
114
+ template <class Tuple, size_t... Is>
115
+ constexpr auto tuple_elements(Tuple t, std::index_sequence<Is...>) {
116
+ return std::tuple<std::tuple_element_t<Is, Tuple>...>(std::get<Is>(t)...);
117
+ }
118
+
119
+ /**
120
+ * Use tuple_take to extract the first or last n elements from the argument
121
+ * tuple into a result tuple.
122
+ *
123
+ * Example:
124
+ * std::tuple<int, const char*, double> t = std::make_tuple(0, "HEY", 2.0);
125
+ * std::tuple<int, const char*> first_two = tuple_take<decltype(t), 2>(t);
126
+ * std::tuple<const char*, double> last_two = tuple_take<decltype(t), -2>(t);
127
+ */
128
+ template <class Tuple, int N, class Enable = void>
129
+ struct TupleTake {};
130
+
131
+ template <class Tuple, int N>
132
+ struct TupleTake<Tuple, N, std::enable_if_t<N >= 0, void>> {
133
+ static auto call(Tuple t) {
134
+ constexpr size_t size = std::tuple_size<Tuple>();
135
+ static_assert(N <= size, "tuple_take: N > size");
136
+ return tuple_elements(t, std::make_index_sequence<N>{});
137
+ }
138
+ };
139
+
140
+ template <class Tuple, int N>
141
+ struct TupleTake < Tuple,
142
+ N, std::enable_if_t<N<0, void>> {
143
+ static auto call(Tuple t) {
144
+ constexpr size_t size = std::tuple_size<Tuple>();
145
+ static_assert(-N <= size, "tuple_take: -N > size");
146
+ return tuple_elements(t, make_offset_index_sequence<size + N, -N>{});
147
+ }
148
+ };
149
+
150
+ template <class Tuple, int N>
151
+ auto tuple_take(Tuple t) {
152
+ return TupleTake<Tuple, N>::call(t);
153
+ }
154
+
155
+ /**
156
+ * Use tuple_slice to extract a contiguous subtuple from the argument.
157
+ *
158
+ * Example:
159
+ * std::tuple<int, const char*, double, bool> t = std::make_tuple(0,
160
+ * "HEY", 2.0, false); std::tuple<int, const char*> middle_two =
161
+ * tuple_slice<decltype(t), 1, 2>(t);
162
+ */
163
+ template <class Tuple, size_t Start, size_t N>
164
+ constexpr auto tuple_slice(Tuple t) {
165
+ constexpr size_t size = std::tuple_size<Tuple>();
166
+ static_assert(Start + N <= size, "tuple_slice: Start + N > size");
167
+ return tuple_elements(t, make_offset_index_sequence<Start, N>{});
168
+ }
169
+
170
+ /**
171
+ * Use tuple_map to run a mapping function over a tuple to get a new tuple.
172
+ *
173
+ * Example 1:
174
+ * auto result = tuple_map(std::tuple<int32_t, int32_t, int32_t>(3, 4, 5), []
175
+ * (int32_t a) -> int16_t {return a+1;});
176
+ * // result == std::tuple<int16_t, int16_t, int16_t>(4, 5, 6)
177
+ *
178
+ * Example 2:
179
+ * struct Mapper {
180
+ * std::string operator()(int32_t a) const {
181
+ * return std::to_string(a);
182
+ * }
183
+ * int64_t operator()(const std::string& a) const {
184
+ * return atoi(a.c_str());
185
+ * }
186
+ * };
187
+ * auto result = tuple_map(std::tuple<int32_t, std::string>(3, "4"),
188
+ * Mapper());
189
+ * // result == std::tuple<std::string, int64_t>("3", 4)
190
+ *
191
+ * Example 3:
192
+ * struct A final {
193
+ * int32_t func() {
194
+ * return 5;
195
+ * }
196
+ * };
197
+ * struct B final {
198
+ * std::string func() {
199
+ * return "5";
200
+ * }
201
+ * };
202
+ * auto result = tuple_map(std::make_tuple(A(), B()), [] (auto a) { return
203
+ * a.func(); });
204
+ * // result == std::tuple<int32_t, std::string>(5, "5");
205
+ */
206
+ namespace detail {
207
+ template <class Mapper, class... Args, size_t... Indices>
208
+ auto tuple_map(
209
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
210
+ std::tuple<Args...>&& tuple,
211
+ const Mapper& mapper,
212
+ std::index_sequence<Indices...>) {
213
+ return std::tuple<decltype(mapper(std::forward<Args>(std::get<Indices>(
214
+ tuple))))...>(mapper(std::forward<Args>(std::get<Indices>(tuple)))...);
215
+ }
216
+ } // namespace detail
217
+
218
+ template <class Mapper, class... Args>
219
+ auto tuple_map(std::tuple<Args...>&& tuple, const Mapper& mapper) {
220
+ return detail::tuple_map(
221
+ std::move(tuple), mapper, std::index_sequence_for<Args...>());
222
+ }
223
+
224
+ } // namespace c10::guts
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/NetworkFlow.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ /**
9
+ * This file provides a network flow implementation.
10
+ * https://en.wikipedia.org/wiki/Flow_network
11
+ *
12
+ * It aims to mirror some of the behavior of networkx, which is/was used by
13
+ * functorch partitioners for splitting the graph into a forward and backward
14
+ * graph.
15
+ */
16
+
17
+ namespace c10 {
18
+
19
+ enum class C10_API_ENUM MinCutStatus {
20
+ SUCCESS = 0,
21
+ UNBOUNDED = 1,
22
+ OVERFLOW_INF = 2,
23
+ INVALID = 3,
24
+ };
25
+
26
+ struct MinCutResult {
27
+ MinCutStatus status;
28
+ int64_t max_flow;
29
+ std::vector<std::string> reachable;
30
+ std::vector<std::string> unreachable;
31
+ };
32
+
33
+ // Modeled after networkx implementation
34
+ class C10_API NetworkFlowGraph {
35
+ public:
36
+ // selected such that INF + INF is < INT64_MAX
37
+ constexpr static int64_t INF = (1LL << 62) - 1;
38
+
39
+ struct Edge {
40
+ std::string source, dest;
41
+ int64_t capacity;
42
+ };
43
+
44
+ MinCutStatus add_edge(
45
+ const std::string& source,
46
+ const std::string& dest,
47
+ int64_t capacity = 1);
48
+
49
+ MinCutResult minimum_cut(const std::string& s, const std::string& t) const;
50
+
51
+ std::vector<Edge> edges;
52
+ };
53
+
54
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Optional.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_OPTIONAL_H_
2
+ #define C10_UTIL_OPTIONAL_H_
3
+
4
+ #include <optional>
5
+ #include <type_traits>
6
+
7
+ // Macros.h is not needed, but it does namespace shenanigans that lots
8
+ // of downstream code seems to rely on. Feel free to remove it and fix
9
+ // up builds.
10
+
11
+ namespace c10 {
12
+
13
+ #if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED)
14
+ // NOLINTNEXTLINE(misc-unused-using-decls)
15
+ using std::bad_optional_access;
16
+ // NOLINTNEXTLINE(misc-unused-using-decls)
17
+ using std::make_optional;
18
+ // NOLINTNEXTLINE(misc-unused-using-decls)
19
+ using std::nullopt;
20
+ // NOLINTNEXTLINE(misc-unused-using-decls)
21
+ using std::nullopt_t;
22
+ // NOLINTNEXTLINE(misc-unused-using-decls)
23
+ using std::optional;
24
+ #endif
25
+
26
+ #if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED)
27
+
28
+ namespace detail_ {
29
+ // the call to convert<A>(b) has return type A and converts b to type A iff b
30
+ // decltype(b) is implicitly convertible to A
31
+ template <class U>
32
+ constexpr U convert(U v) {
33
+ return v;
34
+ }
35
+ } // namespace detail_
36
+ template <class T, class F>
37
+ [[deprecated(
38
+ "Please use std::optional::value_or instead of c10::value_or_else")]] constexpr T
39
+ value_or_else(const std::optional<T>& v, F&& func) {
40
+ static_assert(
41
+ std::is_convertible_v<typename std::invoke_result_t<F>, T>,
42
+ "func parameters must be a callable that returns a type convertible to the value stored in the optional");
43
+ return v.has_value() ? *v : detail_::convert<T>(std::forward<F>(func)());
44
+ }
45
+
46
+ template <class T, class F>
47
+ [[deprecated(
48
+ "Please use std::optional::value_or instead of c10::value_or_else")]] constexpr T
49
+ value_or_else(std::optional<T>&& v, F&& func) {
50
+ static_assert(
51
+ std::is_convertible_v<typename std::invoke_result_t<F>, T>,
52
+ "func parameters must be a callable that returns a type convertible to the value stored in the optional");
53
+ return v.has_value() ? constexpr_move(std::move(v).contained_val())
54
+ : detail_::convert<T>(std::forward<F>(func)());
55
+ }
56
+
57
+ #endif
58
+
59
+ } // namespace c10
60
+ #endif // C10_UTIL_OPTIONAL_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/OptionalArrayRef.h ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file defines OptionalArrayRef<T>, a class that has almost the same
2
+ // exact functionality as std::optional<ArrayRef<T>>, except that its
3
+ // converting constructor fixes a dangling pointer issue.
4
+ //
5
+ // The implicit converting constructor of both std::optional<ArrayRef<T>> and
6
+ // std::optional<ArrayRef<T>> can cause the underlying ArrayRef<T> to store
7
+ // a dangling pointer. OptionalArrayRef<T> prevents this by wrapping
8
+ // a std::optional<ArrayRef<T>> and fixing the constructor implementation.
9
+ //
10
+ // See https://github.com/pytorch/pytorch/issues/63645 for more on this.
11
+
12
+ #pragma once
13
+
14
+ #include <c10/util/ArrayRef.h>
15
+ #include <cstdint>
16
+ #include <initializer_list>
17
+ #include <optional>
18
+ #include <type_traits>
19
+ #include <utility>
20
+
21
+ namespace c10 {
22
+
23
+ template <typename T>
24
+ class OptionalArrayRef final {
25
+ public:
26
+ // Constructors
27
+
28
+ constexpr OptionalArrayRef() noexcept = default;
29
+
30
+ constexpr OptionalArrayRef(std::nullopt_t) noexcept {}
31
+
32
+ OptionalArrayRef(const OptionalArrayRef& other) = default;
33
+
34
+ OptionalArrayRef(OptionalArrayRef&& other) noexcept = default;
35
+
36
+ constexpr OptionalArrayRef(const std::optional<ArrayRef<T>>& other) noexcept
37
+ : wrapped_opt_array_ref(other) {}
38
+
39
+ constexpr OptionalArrayRef(std::optional<ArrayRef<T>>&& other) noexcept
40
+ : wrapped_opt_array_ref(std::move(other)) {}
41
+
42
+ constexpr OptionalArrayRef(const T& value) noexcept
43
+ : wrapped_opt_array_ref(value) {}
44
+
45
+ template <
46
+ typename U = ArrayRef<T>,
47
+ std::enable_if_t<
48
+ !std::is_same_v<std::decay_t<U>, OptionalArrayRef> &&
49
+ !std::is_same_v<std::decay_t<U>, std::in_place_t> &&
50
+ std::is_constructible_v<ArrayRef<T>, U&&> &&
51
+ std::is_convertible_v<U&&, ArrayRef<T>> &&
52
+ !std::is_convertible_v<U&&, T>,
53
+ bool> = false>
54
+ constexpr OptionalArrayRef(U&& value) noexcept(
55
+ std::is_nothrow_constructible_v<ArrayRef<T>, U&&>)
56
+ : wrapped_opt_array_ref(std::forward<U>(value)) {}
57
+
58
+ template <
59
+ typename U = ArrayRef<T>,
60
+ std::enable_if_t<
61
+ !std::is_same_v<std::decay_t<U>, OptionalArrayRef> &&
62
+ !std::is_same_v<std::decay_t<U>, std::in_place_t> &&
63
+ std::is_constructible_v<ArrayRef<T>, U&&> &&
64
+ !std::is_convertible_v<U&&, ArrayRef<T>>,
65
+ bool> = false>
66
+ constexpr explicit OptionalArrayRef(U&& value) noexcept(
67
+ std::is_nothrow_constructible_v<ArrayRef<T>, U&&>)
68
+ : wrapped_opt_array_ref(std::forward<U>(value)) {}
69
+
70
+ template <typename... Args>
71
+ constexpr explicit OptionalArrayRef(
72
+ std::in_place_t ip,
73
+ Args&&... args) noexcept
74
+ : wrapped_opt_array_ref(ip, std::forward<Args>(args)...) {}
75
+
76
+ template <typename U, typename... Args>
77
+ constexpr explicit OptionalArrayRef(
78
+ std::in_place_t ip,
79
+ std::initializer_list<U> il,
80
+ Args&&... args)
81
+ : wrapped_opt_array_ref(ip, il, std::forward<Args>(args)...) {}
82
+
83
+ constexpr OptionalArrayRef(const std::initializer_list<T>& Vec)
84
+ : wrapped_opt_array_ref(ArrayRef<T>(Vec)) {}
85
+
86
+ // Destructor
87
+
88
+ ~OptionalArrayRef() = default;
89
+
90
+ // Assignment
91
+
92
+ constexpr OptionalArrayRef& operator=(std::nullopt_t) noexcept {
93
+ wrapped_opt_array_ref = std::nullopt;
94
+ return *this;
95
+ }
96
+
97
+ OptionalArrayRef& operator=(const OptionalArrayRef& other) = default;
98
+
99
+ OptionalArrayRef& operator=(OptionalArrayRef&& other) noexcept = default;
100
+
101
+ constexpr OptionalArrayRef& operator=(
102
+ const std::optional<ArrayRef<T>>& other) noexcept {
103
+ wrapped_opt_array_ref = other;
104
+ return *this;
105
+ }
106
+
107
+ constexpr OptionalArrayRef& operator=(
108
+ std::optional<ArrayRef<T>>&& other) noexcept {
109
+ wrapped_opt_array_ref = std::move(other);
110
+ return *this;
111
+ }
112
+
113
+ template <
114
+ typename U = ArrayRef<T>,
115
+ typename = std::enable_if_t<
116
+ !std::is_same_v<std::decay_t<U>, OptionalArrayRef> &&
117
+ std::is_constructible_v<ArrayRef<T>, U&&> &&
118
+ std::is_assignable_v<ArrayRef<T>&, U&&>>>
119
+ constexpr OptionalArrayRef& operator=(U&& value) noexcept(
120
+ std::is_nothrow_constructible_v<ArrayRef<T>, U&&> &&
121
+ std::is_nothrow_assignable_v<ArrayRef<T>&, U&&>) {
122
+ wrapped_opt_array_ref = std::forward<U>(value);
123
+ return *this;
124
+ }
125
+
126
+ // Observers
127
+
128
+ constexpr ArrayRef<T>* operator->() noexcept {
129
+ return &wrapped_opt_array_ref.value();
130
+ }
131
+
132
+ constexpr const ArrayRef<T>* operator->() const noexcept {
133
+ return &wrapped_opt_array_ref.value();
134
+ }
135
+
136
+ constexpr ArrayRef<T>& operator*() & noexcept {
137
+ return wrapped_opt_array_ref.value();
138
+ }
139
+
140
+ constexpr const ArrayRef<T>& operator*() const& noexcept {
141
+ return wrapped_opt_array_ref.value();
142
+ }
143
+
144
+ constexpr ArrayRef<T>&& operator*() && noexcept {
145
+ return std::move(wrapped_opt_array_ref.value());
146
+ }
147
+
148
+ constexpr const ArrayRef<T>&& operator*() const&& noexcept {
149
+ return std::move(wrapped_opt_array_ref.value());
150
+ }
151
+
152
+ constexpr explicit operator bool() const noexcept {
153
+ return wrapped_opt_array_ref.has_value();
154
+ }
155
+
156
+ constexpr bool has_value() const noexcept {
157
+ return wrapped_opt_array_ref.has_value();
158
+ }
159
+
160
+ constexpr ArrayRef<T>& value() & {
161
+ return wrapped_opt_array_ref.value();
162
+ }
163
+
164
+ constexpr const ArrayRef<T>& value() const& {
165
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
166
+ return wrapped_opt_array_ref.value();
167
+ }
168
+
169
+ constexpr ArrayRef<T>&& value() && {
170
+ return std::move(wrapped_opt_array_ref.value());
171
+ }
172
+
173
+ constexpr const ArrayRef<T>&& value() const&& {
174
+ return std::move(wrapped_opt_array_ref.value());
175
+ }
176
+
177
+ template <typename U>
178
+ constexpr std::
179
+ enable_if_t<std::is_convertible_v<U&&, ArrayRef<T>>, ArrayRef<T>>
180
+ value_or(U&& default_value) const& {
181
+ return wrapped_opt_array_ref.value_or(std::forward<U>(default_value));
182
+ }
183
+
184
+ template <typename U>
185
+ constexpr std::
186
+ enable_if_t<std::is_convertible_v<U&&, ArrayRef<T>>, ArrayRef<T>>
187
+ value_or(U&& default_value) && {
188
+ return wrapped_opt_array_ref.value_or(std::forward<U>(default_value));
189
+ }
190
+
191
+ // Modifiers
192
+
193
+ constexpr void swap(OptionalArrayRef& other) noexcept {
194
+ std::swap(wrapped_opt_array_ref, other.wrapped_opt_array_ref);
195
+ }
196
+
197
+ constexpr void reset() noexcept {
198
+ wrapped_opt_array_ref.reset();
199
+ }
200
+
201
+ template <typename... Args>
202
+ constexpr std::
203
+ enable_if_t<std::is_constructible_v<ArrayRef<T>, Args&&...>, ArrayRef<T>&>
204
+ emplace(Args&&... args) noexcept(
205
+ std::is_nothrow_constructible_v<ArrayRef<T>, Args&&...>) {
206
+ return wrapped_opt_array_ref.emplace(std::forward<Args>(args)...);
207
+ }
208
+
209
+ template <typename U, typename... Args>
210
+ constexpr ArrayRef<T>& emplace(
211
+ std::initializer_list<U> il,
212
+ Args&&... args) noexcept {
213
+ return wrapped_opt_array_ref.emplace(il, std::forward<Args>(args)...);
214
+ }
215
+
216
+ private:
217
+ std::optional<ArrayRef<T>> wrapped_opt_array_ref;
218
+ };
219
+
220
+ using OptionalIntArrayRef = OptionalArrayRef<int64_t>;
221
+
222
+ inline bool operator==(
223
+ const OptionalIntArrayRef& a1,
224
+ const IntArrayRef& other) {
225
+ if (!a1.has_value()) {
226
+ return false;
227
+ }
228
+ return a1.value() == other;
229
+ }
230
+
231
+ inline bool operator==(
232
+ const c10::IntArrayRef& a1,
233
+ const c10::OptionalIntArrayRef& a2) {
234
+ return a2 == a1;
235
+ }
236
+
237
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ParallelGuard.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ namespace c10 {
6
+
7
+ // RAII thread local guard that tracks whether code is being executed in
8
+ // `at::parallel_for` or `at::parallel_reduce` loop function.
9
+ class C10_API ParallelGuard {
10
+ public:
11
+ static bool is_enabled();
12
+
13
+ ParallelGuard(bool state);
14
+ ~ParallelGuard();
15
+
16
+ private:
17
+ bool previous_state_;
18
+ };
19
+
20
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Registry.h ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_REGISTRY_H_
2
+ #define C10_UTIL_REGISTRY_H_
3
+
4
+ /**
5
+ * Simple registry implementation that uses static variables to
6
+ * register object creators during program initialization time.
7
+ */
8
+
9
+ // NB: This Registry works poorly when you have other namespaces.
10
+ // Make all macro invocations from inside the at namespace.
11
+
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+ #include <functional>
15
+ #include <memory>
16
+ #include <mutex>
17
+ #include <stdexcept>
18
+ #include <string>
19
+ #include <unordered_map>
20
+ #include <vector>
21
+
22
+ #include <c10/macros/Export.h>
23
+ #include <c10/macros/Macros.h>
24
+ #include <c10/util/Type.h>
25
+
26
+ namespace c10 {
27
+
28
+ template <typename KeyType>
29
+ inline std::string KeyStrRepr(const KeyType& /*key*/) {
30
+ return "[key type printing not supported]";
31
+ }
32
+
33
+ template <>
34
+ inline std::string KeyStrRepr(const std::string& key) {
35
+ return key;
36
+ }
37
+
38
+ enum RegistryPriority {
39
+ REGISTRY_FALLBACK = 1,
40
+ REGISTRY_DEFAULT = 2,
41
+ REGISTRY_PREFERRED = 3,
42
+ };
43
+
44
+ /**
45
+ * @brief A template class that allows one to register classes by keys.
46
+ *
47
+ * The keys are usually a std::string specifying the name, but can be anything
48
+ * that can be used in a std::map.
49
+ *
50
+ * You should most likely not use the Registry class explicitly, but use the
51
+ * helper macros below to declare specific registries as well as registering
52
+ * objects.
53
+ */
54
+ template <class SrcType, class ObjectPtrType, class... Args>
55
+ class Registry {
56
+ public:
57
+ typedef std::function<ObjectPtrType(Args...)> Creator;
58
+
59
+ Registry(bool warning = true) : registry_(), priority_(), warning_(warning) {}
60
+ ~Registry() = default;
61
+
62
+ void Register(
63
+ const SrcType& key,
64
+ Creator creator,
65
+ const RegistryPriority priority = REGISTRY_DEFAULT) {
66
+ std::lock_guard<std::mutex> lock(register_mutex_);
67
+ // The if statement below is essentially the same as the following line:
68
+ // TORCH_CHECK_EQ(registry_.count(key), 0) << "Key " << key
69
+ // << " registered twice.";
70
+ // However, TORCH_CHECK_EQ depends on google logging, and since registration
71
+ // is carried out at static initialization time, we do not want to have an
72
+ // explicit dependency on glog's initialization function.
73
+ if (registry_.count(key) != 0) {
74
+ auto cur_priority = priority_[key];
75
+ if (priority > cur_priority) {
76
+ #ifdef DEBUG
77
+ std::string warn_msg =
78
+ "Overwriting already registered item for key " + KeyStrRepr(key);
79
+ fprintf(stderr, "%s\n", warn_msg.c_str());
80
+ #endif
81
+ registry_[key] = creator;
82
+ priority_[key] = priority;
83
+ } else if (priority == cur_priority) {
84
+ std::string err_msg =
85
+ "Key already registered with the same priority: " + KeyStrRepr(key);
86
+ fprintf(stderr, "%s\n", err_msg.c_str());
87
+ if (terminate_) {
88
+ std::exit(1);
89
+ } else {
90
+ throw std::runtime_error(err_msg);
91
+ }
92
+ } else if (warning_) {
93
+ std::string warn_msg =
94
+ "Higher priority item already registered, skipping registration of " +
95
+ KeyStrRepr(key);
96
+ fprintf(stderr, "%s\n", warn_msg.c_str());
97
+ }
98
+ } else {
99
+ registry_[key] = creator;
100
+ priority_[key] = priority;
101
+ }
102
+ }
103
+
104
+ void Register(
105
+ const SrcType& key,
106
+ Creator creator,
107
+ const std::string& help_msg,
108
+ const RegistryPriority priority = REGISTRY_DEFAULT) {
109
+ Register(key, creator, priority);
110
+ help_message_[key] = help_msg;
111
+ }
112
+
113
+ inline bool Has(const SrcType& key) {
114
+ return (registry_.count(key) != 0);
115
+ }
116
+
117
+ ObjectPtrType Create(const SrcType& key, Args... args) {
118
+ auto it = registry_.find(key);
119
+ if (it == registry_.end()) {
120
+ // Returns nullptr if the key is not registered.
121
+ return nullptr;
122
+ }
123
+ return it->second(args...);
124
+ }
125
+
126
+ /**
127
+ * Returns the keys currently registered as a std::vector.
128
+ */
129
+ std::vector<SrcType> Keys() const {
130
+ std::vector<SrcType> keys;
131
+ keys.reserve(registry_.size());
132
+ for (const auto& it : registry_) {
133
+ keys.push_back(it.first);
134
+ }
135
+ return keys;
136
+ }
137
+
138
+ inline const std::unordered_map<SrcType, std::string>& HelpMessage() const {
139
+ return help_message_;
140
+ }
141
+
142
+ const char* HelpMessage(const SrcType& key) const {
143
+ auto it = help_message_.find(key);
144
+ if (it == help_message_.end()) {
145
+ return nullptr;
146
+ }
147
+ return it->second.c_str();
148
+ }
149
+
150
+ // Used for testing, if terminate is unset, Registry throws instead of
151
+ // calling std::exit
152
+ void SetTerminate(bool terminate) {
153
+ terminate_ = terminate;
154
+ }
155
+
156
+ C10_DISABLE_COPY_AND_ASSIGN(Registry);
157
+ Registry(Registry&&) = delete;
158
+ Registry& operator=(Registry&&) = delete;
159
+
160
+ private:
161
+ std::unordered_map<SrcType, Creator> registry_;
162
+ std::unordered_map<SrcType, RegistryPriority> priority_;
163
+ bool terminate_{true};
164
+ const bool warning_;
165
+ std::unordered_map<SrcType, std::string> help_message_;
166
+ std::mutex register_mutex_;
167
+ };
168
+
169
+ template <class SrcType, class ObjectPtrType, class... Args>
170
+ class Registerer {
171
+ public:
172
+ explicit Registerer(
173
+ const SrcType& key,
174
+ Registry<SrcType, ObjectPtrType, Args...>* registry,
175
+ typename Registry<SrcType, ObjectPtrType, Args...>::Creator creator,
176
+ const std::string& help_msg = "") {
177
+ registry->Register(key, creator, help_msg);
178
+ }
179
+
180
+ explicit Registerer(
181
+ const SrcType& key,
182
+ const RegistryPriority priority,
183
+ Registry<SrcType, ObjectPtrType, Args...>* registry,
184
+ typename Registry<SrcType, ObjectPtrType, Args...>::Creator creator,
185
+ const std::string& help_msg = "") {
186
+ registry->Register(key, creator, help_msg, priority);
187
+ }
188
+
189
+ template <class DerivedType>
190
+ static ObjectPtrType DefaultCreator(Args... args) {
191
+ return ObjectPtrType(new DerivedType(args...));
192
+ }
193
+ };
194
+
195
+ /**
196
+ * C10_DECLARE_TYPED_REGISTRY is a macro that expands to a function
197
+ * declaration, as well as creating a convenient typename for its corresponding
198
+ * registerer.
199
+ */
200
+ // Note on C10_IMPORT and C10_EXPORT below: we need to explicitly mark DECLARE
201
+ // as import and DEFINE as export, because these registry macros will be used
202
+ // in downstream shared libraries as well, and one cannot use *_API - the API
203
+ // macro will be defined on a per-shared-library basis. Semantically, when one
204
+ // declares a typed registry it is always going to be IMPORT, and when one
205
+ // defines a registry (which should happen ONLY ONCE and ONLY IN SOURCE FILE),
206
+ // the instantiation unit is always going to be exported.
207
+ //
208
+ // The only unique condition is when in the same file one does DECLARE and
209
+ // DEFINE - in Windows compilers, this generates a warning that dllimport and
210
+ // dllexport are mixed, but the warning is fine and linker will be properly
211
+ // exporting the symbol. Same thing happens in the gflags flag declaration and
212
+ // definition caes.
213
+ #define C10_DECLARE_TYPED_REGISTRY( \
214
+ RegistryName, SrcType, ObjectType, PtrType, ...) \
215
+ C10_API ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
216
+ RegistryName(); \
217
+ typedef ::c10::Registerer<SrcType, PtrType<ObjectType>, ##__VA_ARGS__> \
218
+ Registerer##RegistryName
219
+
220
+ #define TORCH_DECLARE_TYPED_REGISTRY( \
221
+ RegistryName, SrcType, ObjectType, PtrType, ...) \
222
+ TORCH_API ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
223
+ RegistryName(); \
224
+ typedef ::c10::Registerer<SrcType, PtrType<ObjectType>, ##__VA_ARGS__> \
225
+ Registerer##RegistryName
226
+
227
+ #define C10_DEFINE_TYPED_REGISTRY( \
228
+ RegistryName, SrcType, ObjectType, PtrType, ...) \
229
+ C10_EXPORT ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
230
+ RegistryName() { \
231
+ static ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
232
+ registry = new ::c10:: \
233
+ Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>(); \
234
+ return registry; \
235
+ }
236
+
237
+ #define C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \
238
+ RegistryName, SrcType, ObjectType, PtrType, ...) \
239
+ C10_EXPORT ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
240
+ RegistryName() { \
241
+ static ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>* \
242
+ registry = \
243
+ new ::c10::Registry<SrcType, PtrType<ObjectType>, ##__VA_ARGS__>( \
244
+ false); \
245
+ return registry; \
246
+ }
247
+
248
+ // Note(Yangqing): The __VA_ARGS__ below allows one to specify a templated
249
+ // creator with comma in its templated arguments.
250
+ #define C10_REGISTER_TYPED_CREATOR(RegistryName, key, ...) \
251
+ static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \
252
+ key, RegistryName(), ##__VA_ARGS__);
253
+
254
+ #define C10_REGISTER_TYPED_CREATOR_WITH_PRIORITY( \
255
+ RegistryName, key, priority, ...) \
256
+ static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \
257
+ key, priority, RegistryName(), ##__VA_ARGS__);
258
+
259
+ #define C10_REGISTER_TYPED_CLASS(RegistryName, key, ...) \
260
+ static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \
261
+ key, \
262
+ RegistryName(), \
263
+ Registerer##RegistryName::DefaultCreator<__VA_ARGS__>, \
264
+ ::c10::demangle_type<__VA_ARGS__>());
265
+
266
+ #define C10_REGISTER_TYPED_CLASS_WITH_PRIORITY( \
267
+ RegistryName, key, priority, ...) \
268
+ static Registerer##RegistryName C10_ANONYMOUS_VARIABLE(g_##RegistryName)( \
269
+ key, \
270
+ priority, \
271
+ RegistryName(), \
272
+ Registerer##RegistryName::DefaultCreator<__VA_ARGS__>, \
273
+ ::c10::demangle_type<__VA_ARGS__>());
274
+
275
+ // C10_DECLARE_REGISTRY and C10_DEFINE_REGISTRY are hard-wired to use
276
+ // std::string as the key type, because that is the most commonly used cases.
277
+ #define C10_DECLARE_REGISTRY(RegistryName, ObjectType, ...) \
278
+ C10_DECLARE_TYPED_REGISTRY( \
279
+ RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__)
280
+
281
+ #define TORCH_DECLARE_REGISTRY(RegistryName, ObjectType, ...) \
282
+ TORCH_DECLARE_TYPED_REGISTRY( \
283
+ RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__)
284
+
285
+ #define C10_DEFINE_REGISTRY(RegistryName, ObjectType, ...) \
286
+ C10_DEFINE_TYPED_REGISTRY( \
287
+ RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__)
288
+
289
+ #define C10_DEFINE_REGISTRY_WITHOUT_WARNING(RegistryName, ObjectType, ...) \
290
+ C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \
291
+ RegistryName, std::string, ObjectType, std::unique_ptr, ##__VA_ARGS__)
292
+
293
+ #define C10_DECLARE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \
294
+ C10_DECLARE_TYPED_REGISTRY( \
295
+ RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__)
296
+
297
+ #define TORCH_DECLARE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \
298
+ TORCH_DECLARE_TYPED_REGISTRY( \
299
+ RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__)
300
+
301
+ #define C10_DEFINE_SHARED_REGISTRY(RegistryName, ObjectType, ...) \
302
+ C10_DEFINE_TYPED_REGISTRY( \
303
+ RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__)
304
+
305
+ #define C10_DEFINE_SHARED_REGISTRY_WITHOUT_WARNING( \
306
+ RegistryName, ObjectType, ...) \
307
+ C10_DEFINE_TYPED_REGISTRY_WITHOUT_WARNING( \
308
+ RegistryName, std::string, ObjectType, std::shared_ptr, ##__VA_ARGS__)
309
+
310
+ // C10_REGISTER_CREATOR and C10_REGISTER_CLASS are hard-wired to use std::string
311
+ // as the key
312
+ // type, because that is the most commonly used cases.
313
+ #define C10_REGISTER_CREATOR(RegistryName, key, ...) \
314
+ C10_REGISTER_TYPED_CREATOR(RegistryName, #key, __VA_ARGS__)
315
+
316
+ #define C10_REGISTER_CREATOR_WITH_PRIORITY(RegistryName, key, priority, ...) \
317
+ C10_REGISTER_TYPED_CREATOR_WITH_PRIORITY( \
318
+ RegistryName, #key, priority, __VA_ARGS__)
319
+
320
+ #define C10_REGISTER_CLASS(RegistryName, key, ...) \
321
+ C10_REGISTER_TYPED_CLASS(RegistryName, #key, __VA_ARGS__)
322
+
323
+ #define C10_REGISTER_CLASS_WITH_PRIORITY(RegistryName, key, priority, ...) \
324
+ C10_REGISTER_TYPED_CLASS_WITH_PRIORITY( \
325
+ RegistryName, #key, priority, __VA_ARGS__)
326
+
327
+ } // namespace c10
328
+
329
+ #endif // C10_UTIL_REGISTRY_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ScopeExit.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <type_traits>
4
+ #include <utility>
5
+
6
+ namespace c10 {
7
+
8
+ /**
9
+ * Mostly copied from https://llvm.org/doxygen/ScopeExit_8h_source.html
10
+ */
11
+ template <typename Callable>
12
+ class scope_exit {
13
+ Callable ExitFunction;
14
+ bool Engaged = true; // False once moved-from or release()d.
15
+
16
+ public:
17
+ template <typename Fp>
18
+ // NOLINTNEXTLINE(bugprone-forwarding-reference-overload)
19
+ explicit scope_exit(Fp&& F) : ExitFunction(std::forward<Fp>(F)) {}
20
+
21
+ scope_exit(scope_exit&& Rhs) noexcept
22
+ : ExitFunction(std::move(Rhs.ExitFunction)), Engaged(Rhs.Engaged) {
23
+ Rhs.release();
24
+ }
25
+ scope_exit(const scope_exit&) = delete;
26
+ scope_exit& operator=(scope_exit&&) = delete;
27
+ scope_exit& operator=(const scope_exit&) = delete;
28
+
29
+ void release() {
30
+ Engaged = false;
31
+ }
32
+
33
+ ~scope_exit() {
34
+ if (Engaged) {
35
+ ExitFunction();
36
+ }
37
+ }
38
+ };
39
+
40
+ // Keeps the callable object that is passed in, and execute it at the
41
+ // destruction of the returned object (usually at the scope exit where the
42
+ // returned object is kept).
43
+ //
44
+ // Interface is specified by p0052r2.
45
+ template <typename Callable>
46
+ scope_exit<std::decay_t<Callable>> make_scope_exit(Callable&& F) {
47
+ return scope_exit<std::decay_t<Callable>>(std::forward<Callable>(F));
48
+ }
49
+
50
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Semaphore.h ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <version>
4
+
5
+ /*
6
+ a simple semaphore interface.
7
+ */
8
+
9
+ // note: __cpp_lib_semaphore will not be defined in some apple platforms
10
+ // even if >= C++20.
11
+ #if __has_include(<semaphore>) && defined(__cpp_lib_semaphore) && __cpp_lib_semaphore >= 201907L
12
+ #define C10_SEMAPHORE_USE_STL
13
+ #endif
14
+
15
+ #ifdef C10_SEMAPHORE_USE_STL
16
+ #include <semaphore>
17
+ #else
18
+ // To use moodycamel semaphore, we need to include the header file
19
+ // for concurrentqueue first. Hiding implementation detail here.
20
+ #ifdef BLOCK_SIZE
21
+ #pragma push_macro("BLOCK_SIZE")
22
+ #undef BLOCK_SIZE
23
+ #include <moodycamel/concurrentqueue.h> // @manual
24
+ #pragma pop_macro("BLOCK_SIZE")
25
+ #else
26
+ #include <moodycamel/concurrentqueue.h> // @manual
27
+ #endif
28
+
29
+ #include <moodycamel/lightweightsemaphore.h> // @manual
30
+ #endif
31
+
32
+ namespace c10 {
33
+
34
+ class Semaphore {
35
+ public:
36
+ Semaphore(int32_t initial_count = 0) : impl_(initial_count) {}
37
+
38
+ void release(int32_t n = 1) {
39
+ #ifdef C10_SEMAPHORE_USE_STL
40
+ impl_.release(n);
41
+ #else
42
+ impl_.signal(n);
43
+ #endif
44
+ }
45
+
46
+ void acquire() {
47
+ #ifdef C10_SEMAPHORE_USE_STL
48
+ impl_.acquire();
49
+ #else
50
+ impl_.wait();
51
+ #endif
52
+ }
53
+
54
+ bool tryAcquire() {
55
+ #ifdef C10_SEMAPHORE_USE_STL
56
+ return impl_.try_acquire();
57
+ #else
58
+ return impl_.tryWait();
59
+ #endif
60
+ }
61
+
62
+ private:
63
+ #ifdef C10_SEMAPHORE_USE_STL
64
+ std::counting_semaphore<> impl_;
65
+ #else
66
+ moodycamel::LightweightSemaphore impl_;
67
+ #endif
68
+ };
69
+ } // namespace c10
70
+
71
+ #undef C10_SEMAPHORE_USE_STL
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/SmallBuffer.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <array>
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+ #include <type_traits>
6
+
7
+ /** Helper class for allocating temporary fixed size arrays with SBO.
8
+ *
9
+ * This is intentionally much simpler than SmallVector, to improve performance
10
+ * at the expense of many features:
11
+ * - No zero-initialization for numeric types
12
+ * - No resizing after construction
13
+ * - No copy/move
14
+ * - No non-trivial types
15
+ */
16
+
17
+ namespace c10 {
18
+
19
+ template <typename T, size_t N>
20
+ class SmallBuffer {
21
+ static_assert(std::is_trivial_v<T>, "SmallBuffer is intended for POD types");
22
+
23
+ std::array<T, N> storage_;
24
+ size_t size_{};
25
+ T* data_{};
26
+
27
+ public:
28
+ SmallBuffer(size_t size) : size_(size) {
29
+ if (size > N) {
30
+ data_ = new T[size];
31
+ } else {
32
+ data_ = &storage_[0];
33
+ }
34
+ }
35
+
36
+ SmallBuffer(const SmallBuffer&) = delete;
37
+ SmallBuffer& operator=(const SmallBuffer&) = delete;
38
+
39
+ // move constructor is needed in function return
40
+ SmallBuffer(SmallBuffer&& rhs) noexcept : size_{rhs.size_} {
41
+ rhs.size_ = 0;
42
+ if (size_ > N) {
43
+ data_ = rhs.data_;
44
+ rhs.data_ = nullptr;
45
+ } else {
46
+ storage_ = std::move(rhs.storage_);
47
+ data_ = &storage_[0];
48
+ }
49
+ }
50
+
51
+ SmallBuffer& operator=(SmallBuffer&&) = delete;
52
+
53
+ ~SmallBuffer() {
54
+ if (size_ > N) {
55
+ delete[] data_;
56
+ }
57
+ }
58
+ T& operator[](size_t idx) {
59
+ return data()[idx];
60
+ }
61
+ const T& operator[](size_t idx) const {
62
+ return data()[idx];
63
+ }
64
+ T* data() {
65
+ return data_;
66
+ }
67
+ const T* data() const {
68
+ return data_;
69
+ }
70
+ size_t size() const {
71
+ return size_;
72
+ }
73
+ T* begin() {
74
+ return data_;
75
+ }
76
+ const T* begin() const {
77
+ return data_;
78
+ }
79
+ T* end() {
80
+ return data_ + size_;
81
+ }
82
+ const T* end() const {
83
+ return data_ + size_;
84
+ }
85
+ };
86
+
87
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/SmallVector.h ADDED
@@ -0,0 +1,1467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the SmallVector class.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ // ATen: modified from llvm::SmallVector.
14
+ // used std::is_trivially_{copy,move}_constructible
15
+ // replaced iterator_range constructor with inline Container&& constructor
16
+ // replaced LLVM_NODISCARD, LLVM_LIKELY, and LLVM_UNLIKELY with c10 equivalents
17
+ // removed LLVM_GSL_OWNER
18
+ // added SmallVector::at
19
+ // added operator<< for std::ostream
20
+ // added C10_API to export SmallVectorBase
21
+
22
+ #pragma once
23
+
24
+ #include <c10/macros/Macros.h>
25
+ #include <c10/util/AlignOf.h>
26
+
27
+ #include <algorithm>
28
+ #include <cassert>
29
+ #include <cstddef>
30
+ #include <cstdlib>
31
+ #include <cstring>
32
+ #include <functional>
33
+ #include <initializer_list>
34
+ #include <iterator>
35
+ #include <limits>
36
+ #include <memory>
37
+ #include <ostream>
38
+ #include <type_traits>
39
+ #include <utility>
40
+
41
+ namespace c10 {
42
+
43
+ /// This is all the stuff common to all SmallVectors.
44
+ ///
45
+ /// The template parameter specifies the type which should be used to hold the
46
+ /// Size and Capacity of the SmallVector, so it can be adjusted.
47
+ /// Using 32 bit size is desirable to shrink the size of the SmallVector.
48
+ /// Using 64 bit size is desirable for cases like SmallVector<char>, where a
49
+ /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
50
+ /// buffering bitcode output - which can exceed 4GB.
51
+ template <class Size_T>
52
+ class C10_API SmallVectorBase {
53
+ protected:
54
+ void* BeginX;
55
+ Size_T Size = 0, Capacity;
56
+
57
+ /// The maximum value of the Size_T used.
58
+ static constexpr size_t SizeTypeMax() {
59
+ return std::numeric_limits<Size_T>::max();
60
+ }
61
+
62
+ SmallVectorBase(void* FirstEl, size_t TotalCapacity)
63
+ : BeginX(FirstEl), Capacity(TotalCapacity) {}
64
+
65
+ /// This is a helper for \a grow() that's out of line to reduce code
66
+ /// duplication. This function will report a fatal error if it can't grow at
67
+ /// least to \p MinSize.
68
+ void* mallocForGrow(size_t MinSize, size_t TSize, size_t& NewCapacity);
69
+
70
+ /// This is an implementation of the grow() method which only works
71
+ /// on POD-like data types and is out of line to reduce code duplication.
72
+ /// This function will report a fatal error if it cannot increase capacity.
73
+ void grow_pod(const void* FirstEl, size_t MinSize, size_t TSize);
74
+
75
+ public:
76
+ SmallVectorBase() = delete;
77
+ size_t size() const {
78
+ return Size;
79
+ }
80
+ size_t capacity() const {
81
+ return Capacity;
82
+ }
83
+
84
+ [[nodiscard]] bool empty() const {
85
+ return !Size;
86
+ }
87
+
88
+ /// Set the array size to \p N, which the current array must have enough
89
+ /// capacity for.
90
+ ///
91
+ /// This does not construct or destroy any elements in the vector.
92
+ ///
93
+ /// Clients can use this in conjunction with capacity() to write past the end
94
+ /// of the buffer when they know that more elements are available, and only
95
+ /// update the size later. This avoids the cost of value initializing elements
96
+ /// which will only be overwritten.
97
+ void set_size(size_t N) {
98
+ assert(N <= capacity());
99
+ Size = N;
100
+ }
101
+ };
102
+
103
+ template <class T>
104
+ using SmallVectorSizeType =
105
+ std::conditional_t<sizeof(T) < 4 && sizeof(void*) >= 8, uint64_t, uint32_t>;
106
+
107
+ /// Figure out the offset of the first element.
108
+ template <class T, typename = void>
109
+ struct SmallVectorAlignmentAndSize {
110
+ // NOLINTNEXTLINE(*c-arrays*)
111
+ alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
112
+ SmallVectorBase<SmallVectorSizeType<T>>)];
113
+ // NOLINTNEXTLINE(*c-arrays*)
114
+ alignas(T) char FirstEl[sizeof(T)];
115
+ };
116
+
117
+ /// This is the part of SmallVectorTemplateBase which does not depend on whether
118
+ /// the type T is a POD. The extra dummy template argument is used by ArrayRef
119
+ /// to avoid unnecessarily requiring T to be complete.
120
+ template <typename T, typename = void>
121
+ class SmallVectorTemplateCommon
122
+ : public SmallVectorBase<SmallVectorSizeType<T>> {
123
+ using Base = SmallVectorBase<SmallVectorSizeType<T>>;
124
+
125
+ /// Find the address of the first element. For this pointer math to be valid
126
+ /// with small-size of 0 for T with lots of alignment, it's important that
127
+ /// SmallVectorStorage is properly-aligned even for small-size of 0.
128
+ void* getFirstEl() const {
129
+ return const_cast<void*>(reinterpret_cast<const void*>(
130
+ reinterpret_cast<const char*>(this) +
131
+ offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)));
132
+ }
133
+ // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
134
+
135
+ protected:
136
+ SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
137
+
138
+ void grow_pod(size_t MinSize, size_t TSize) {
139
+ Base::grow_pod(getFirstEl(), MinSize, TSize);
140
+ }
141
+
142
+ /// Return true if this is a smallvector which has not had dynamic
143
+ /// memory allocated for it.
144
+ bool isSmall() const {
145
+ return this->BeginX == getFirstEl();
146
+ }
147
+
148
+ /// Put this vector in a state of being small.
149
+ void resetToSmall() {
150
+ this->BeginX = getFirstEl();
151
+ this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
152
+ }
153
+
154
+ /// Return true if V is an internal reference to the given range.
155
+ bool isReferenceToRange(const void* V, const void* First, const void* Last)
156
+ const {
157
+ // Use std::less to avoid UB.
158
+ std::less<> LessThan;
159
+ return !LessThan(V, First) && LessThan(V, Last);
160
+ }
161
+
162
+ /// Return true if V is an internal reference to this vector.
163
+ bool isReferenceToStorage(const void* V) const {
164
+ return isReferenceToRange(V, this->begin(), this->end());
165
+ }
166
+
167
+ /// Return true if First and Last form a valid (possibly empty) range in this
168
+ /// vector's storage.
169
+ bool isRangeInStorage(const void* First, const void* Last) const {
170
+ // Use std::less to avoid UB.
171
+ std::less<> LessThan;
172
+ return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
173
+ !LessThan(this->end(), Last);
174
+ }
175
+
176
+ /// Return true unless Elt will be invalidated by resizing the vector to
177
+ /// NewSize.
178
+ bool isSafeToReferenceAfterResize(const void* Elt, size_t NewSize) {
179
+ // Past the end.
180
+ if (C10_LIKELY(!isReferenceToStorage(Elt)))
181
+ return true;
182
+
183
+ // Return false if Elt will be destroyed by shrinking.
184
+ if (NewSize <= this->size())
185
+ return Elt < this->begin() + NewSize;
186
+
187
+ // Return false if we need to grow.
188
+ return NewSize <= this->capacity();
189
+ }
190
+
191
+ /// Check whether Elt will be invalidated by resizing the vector to NewSize.
192
+ void assertSafeToReferenceAfterResize(const void* Elt, size_t NewSize) {
193
+ (void)Elt; // Suppress unused variable warning
194
+ (void)NewSize; // Suppress unused variable warning
195
+ assert(
196
+ isSafeToReferenceAfterResize(Elt, NewSize) &&
197
+ "Attempting to reference an element of the vector in an operation "
198
+ "that invalidates it");
199
+ }
200
+
201
+ /// Check whether Elt will be invalidated by increasing the size of the
202
+ /// vector by N.
203
+ void assertSafeToAdd(const void* Elt, size_t N = 1) {
204
+ this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
205
+ }
206
+
207
+ /// Check whether any part of the range will be invalidated by clearing.
208
+ void assertSafeToReferenceAfterClear(const T* From, const T* To) {
209
+ if (From == To)
210
+ return;
211
+ this->assertSafeToReferenceAfterResize(From, 0);
212
+ this->assertSafeToReferenceAfterResize(To - 1, 0);
213
+ }
214
+ template <
215
+ class ItTy,
216
+ std::enable_if_t<!std::is_same_v<std::remove_const_t<ItTy>, T*>, bool> =
217
+ false>
218
+ void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
219
+
220
+ /// Check whether any part of the range will be invalidated by growing.
221
+ void assertSafeToAddRange(const T* From, const T* To) {
222
+ if (From == To)
223
+ return;
224
+ this->assertSafeToAdd(From, To - From);
225
+ this->assertSafeToAdd(To - 1, To - From);
226
+ }
227
+ template <
228
+ class ItTy,
229
+ std::enable_if_t<!std::is_same_v<std::remove_const_t<ItTy>, T*>, bool> =
230
+ false>
231
+ void assertSafeToAddRange(ItTy, ItTy) {}
232
+
233
+ /// Reserve enough space to add one element, and return the updated element
234
+ /// pointer in case it was a reference to the storage.
235
+ template <class U>
236
+ static const T* reserveForParamAndGetAddressImpl(
237
+ U* This,
238
+ const T& Elt,
239
+ size_t N) {
240
+ size_t NewSize = This->size() + N;
241
+ if (C10_LIKELY(NewSize <= This->capacity()))
242
+ return &Elt;
243
+
244
+ bool ReferencesStorage = false;
245
+ int64_t Index = -1;
246
+ if constexpr (!U::TakesParamByValue) {
247
+ if (C10_UNLIKELY(This->isReferenceToStorage(&Elt))) {
248
+ ReferencesStorage = true;
249
+ Index = &Elt - This->begin();
250
+ }
251
+ }
252
+ This->grow(NewSize);
253
+ return ReferencesStorage ? This->begin() + Index : &Elt;
254
+ }
255
+
256
+ public:
257
+ using size_type = size_t;
258
+ using difference_type = ptrdiff_t;
259
+ using value_type = T;
260
+ using iterator = T*;
261
+ using const_iterator = const T*;
262
+
263
+ using const_reverse_iterator = std::reverse_iterator<const_iterator>;
264
+ using reverse_iterator = std::reverse_iterator<iterator>;
265
+
266
+ using reference = T&;
267
+ using const_reference = const T&;
268
+ using pointer = T*;
269
+ using const_pointer = const T*;
270
+
271
+ using Base::capacity;
272
+ using Base::empty;
273
+ using Base::size;
274
+
275
+ // forward iterator creation methods.
276
+ iterator begin() {
277
+ return (iterator)this->BeginX;
278
+ }
279
+ const_iterator begin() const {
280
+ return (const_iterator)this->BeginX;
281
+ }
282
+ iterator end() {
283
+ return begin() + size();
284
+ }
285
+ const_iterator end() const {
286
+ return begin() + size();
287
+ }
288
+
289
+ // reverse iterator creation methods.
290
+ reverse_iterator rbegin() {
291
+ return reverse_iterator(end());
292
+ }
293
+ const_reverse_iterator rbegin() const {
294
+ return const_reverse_iterator(end());
295
+ }
296
+ reverse_iterator rend() {
297
+ return reverse_iterator(begin());
298
+ }
299
+ const_reverse_iterator rend() const {
300
+ return const_reverse_iterator(begin());
301
+ }
302
+
303
+ size_type size_in_bytes() const {
304
+ return size() * sizeof(T);
305
+ }
306
+ constexpr size_type max_size() const {
307
+ return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
308
+ }
309
+
310
+ size_t capacity_in_bytes() const {
311
+ return capacity() * sizeof(T);
312
+ }
313
+
314
+ /// Return a pointer to the vector's buffer, even if empty().
315
+ pointer data() {
316
+ return pointer(begin());
317
+ }
318
+ /// Return a pointer to the vector's buffer, even if empty().
319
+ const_pointer data() const {
320
+ return const_pointer(begin());
321
+ }
322
+
323
+ // SmallVector::at is NOT from LLVM.
324
+ reference at(size_type idx) {
325
+ assert(idx < size());
326
+ return begin()[idx];
327
+ }
328
+ const_reference at(size_type idx) const {
329
+ assert(idx < size());
330
+ return begin()[idx];
331
+ }
332
+ reference operator[](size_type idx) {
333
+ assert(idx < size());
334
+ return begin()[idx];
335
+ }
336
+ const_reference operator[](size_type idx) const {
337
+ assert(idx < size());
338
+ return begin()[idx];
339
+ }
340
+
341
+ reference front() {
342
+ assert(!empty());
343
+ return begin()[0];
344
+ }
345
+ const_reference front() const {
346
+ assert(!empty());
347
+ return begin()[0];
348
+ }
349
+
350
+ reference back() {
351
+ assert(!empty());
352
+ return end()[-1];
353
+ }
354
+ const_reference back() const {
355
+ assert(!empty());
356
+ return end()[-1];
357
+ }
358
+ };
359
+
360
+ /// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
361
+ /// method implementations that are designed to work with non-trivial T's.
362
+ ///
363
+ /// We approximate is_trivially_copyable with trivial move/copy construction and
364
+ /// trivial destruction. While the standard doesn't specify that you're allowed
365
+ /// copy these types with memcpy, there is no way for the type to observe this.
366
+ /// This catches the important case of std::pair<POD, POD>, which is not
367
+ /// trivially assignable.
368
+ ///
369
+ /// XXX: if build fails here fall back to C10_IS_TRIVIALLY_COPYABLE and make a
370
+ /// note
371
+ template <
372
+ typename T,
373
+ bool = (std::is_trivially_copy_constructible_v<T>) &&
374
+ (std::is_trivially_move_constructible_v<T>) &&
375
+ std::is_trivially_destructible_v<T>>
376
+ class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
377
+ friend class SmallVectorTemplateCommon<T>;
378
+
379
+ protected:
380
+ static constexpr bool TakesParamByValue = false;
381
+ using ValueParamT = const T&;
382
+
383
+ SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
384
+
385
+ static void destroy_range(T* S, T* E) {
386
+ while (S != E) {
387
+ --E;
388
+ E->~T();
389
+ }
390
+ }
391
+
392
+ /// Move the range [I, E) into the uninitialized memory starting with "Dest",
393
+ /// constructing elements as needed.
394
+ template <typename It1, typename It2>
395
+ static void uninitialized_move(It1 I, It1 E, It2 Dest) {
396
+ std::uninitialized_copy(
397
+ std::make_move_iterator(I), std::make_move_iterator(E), Dest);
398
+ }
399
+
400
+ /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
401
+ /// constructing elements as needed.
402
+ template <typename It1, typename It2>
403
+ static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
404
+ std::uninitialized_copy(I, E, Dest);
405
+ }
406
+
407
+ /// Grow the allocated memory (without initializing new elements), doubling
408
+ /// the size of the allocated memory. Guarantees space for at least one more
409
+ /// element, or MinSize more elements if specified.
410
+ void grow(size_t MinSize = 0);
411
+
412
+ /// Create a new allocation big enough for \p MinSize and pass back its size
413
+ /// in \p NewCapacity. This is the first section of \a grow().
414
+ T* mallocForGrow(size_t MinSize, size_t& NewCapacity) {
415
+ return static_cast<T*>(
416
+ SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
417
+ MinSize, sizeof(T), NewCapacity));
418
+ }
419
+
420
+ /// Move existing elements over to the new allocation \p NewElts, the middle
421
+ /// section of \a grow().
422
+ void moveElementsForGrow(T* NewElts);
423
+
424
+ /// Transfer ownership of the allocation, finishing up \a grow().
425
+ void takeAllocationForGrow(T* NewElts, size_t NewCapacity);
426
+
427
+ /// Reserve enough space to add one element, and return the updated element
428
+ /// pointer in case it was a reference to the storage.
429
+ const T* reserveForParamAndGetAddress(const T& Elt, size_t N = 1) {
430
+ return this->reserveForParamAndGetAddressImpl(this, Elt, N);
431
+ }
432
+
433
+ /// Reserve enough space to add one element, and return the updated element
434
+ /// pointer in case it was a reference to the storage.
435
+ T* reserveForParamAndGetAddress(T& Elt, size_t N = 1) {
436
+ return const_cast<T*>(this->reserveForParamAndGetAddressImpl(this, Elt, N));
437
+ }
438
+
439
+ static T&& forward_value_param(T&& V) {
440
+ return std::move(V);
441
+ }
442
+ static const T& forward_value_param(const T& V) {
443
+ return V;
444
+ }
445
+
446
+ void growAndAssign(size_t NumElts, const T& Elt) {
447
+ // Grow manually in case Elt is an internal reference.
448
+ size_t NewCapacity = 0;
449
+ T* NewElts = mallocForGrow(NumElts, NewCapacity);
450
+ std::uninitialized_fill_n(NewElts, NumElts, Elt);
451
+ this->destroy_range(this->begin(), this->end());
452
+ takeAllocationForGrow(NewElts, NewCapacity);
453
+ this->set_size(NumElts);
454
+ }
455
+
456
+ template <typename... ArgTypes>
457
+ T& growAndEmplaceBack(ArgTypes&&... Args) {
458
+ // Grow manually in case one of Args is an internal reference.
459
+ size_t NewCapacity = 0;
460
+ T* NewElts = mallocForGrow(0, NewCapacity);
461
+ ::new ((void*)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
462
+ moveElementsForGrow(NewElts);
463
+ takeAllocationForGrow(NewElts, NewCapacity);
464
+ this->set_size(this->size() + 1);
465
+ return this->back();
466
+ }
467
+
468
+ public:
469
+ void push_back(const T& Elt) {
470
+ const T* EltPtr = reserveForParamAndGetAddress(Elt);
471
+ ::new ((void*)this->end()) T(*EltPtr);
472
+ this->set_size(this->size() + 1);
473
+ }
474
+
475
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
476
+ void push_back(T&& Elt) {
477
+ T* EltPtr = reserveForParamAndGetAddress(Elt);
478
+ ::new ((void*)this->end()) T(::std::move(*EltPtr));
479
+ this->set_size(this->size() + 1);
480
+ }
481
+
482
+ void pop_back() {
483
+ this->set_size(this->size() - 1);
484
+ this->end()->~T();
485
+ }
486
+ };
487
+
488
+ // Define this out-of-line to dissuade the C++ compiler from inlining it.
489
+ template <typename T, bool TriviallyCopyable>
490
+ void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
491
+ size_t NewCapacity = 0;
492
+ T* NewElts = mallocForGrow(MinSize, NewCapacity);
493
+ moveElementsForGrow(NewElts);
494
+ takeAllocationForGrow(NewElts, NewCapacity);
495
+ }
496
+
497
+ // Define this out-of-line to dissuade the C++ compiler from inlining it.
498
+ template <typename T, bool TriviallyCopyable>
499
+ void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
500
+ T* NewElts) {
501
+ // Move the elements over.
502
+ this->uninitialized_move(this->begin(), this->end(), NewElts);
503
+
504
+ // Destroy the original elements.
505
+ destroy_range(this->begin(), this->end());
506
+ }
507
+
508
+ // Define this out-of-line to dissuade the C++ compiler from inlining it.
509
+ template <typename T, bool TriviallyCopyable>
510
+ void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
511
+ T* NewElts,
512
+ size_t NewCapacity) {
513
+ // If this wasn't grown from the inline copy, deallocate the old space.
514
+ if (!this->isSmall())
515
+ free(this->begin());
516
+
517
+ this->BeginX = NewElts;
518
+ this->Capacity = NewCapacity;
519
+ }
520
+
521
+ /// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
522
+ /// method implementations that are designed to work with trivially copyable
523
+ /// T's. This allows using memcpy in place of copy/move construction and
524
+ /// skipping destruction.
525
+ template <typename T>
526
+ class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
527
+ friend class SmallVectorTemplateCommon<T>;
528
+
529
+ protected:
530
+ /// True if it's cheap enough to take parameters by value. Doing so avoids
531
+ /// overhead related to mitigations for reference invalidation.
532
+ static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void*);
533
+
534
+ /// Either const T& or T, depending on whether it's cheap enough to take
535
+ /// parameters by value.
536
+ using ValueParamT = std::conditional_t<TakesParamByValue, T, const T&>;
537
+
538
+ SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
539
+
540
+ // No need to do a destroy loop for POD's.
541
+ static void destroy_range(T*, T*) {}
542
+
543
+ /// Move the range [I, E) onto the uninitialized memory
544
+ /// starting with "Dest", constructing elements into it as needed.
545
+ template <typename It1, typename It2>
546
+ static void uninitialized_move(It1 I, It1 E, It2 Dest) {
547
+ // Just do a copy.
548
+ uninitialized_copy(I, E, Dest);
549
+ }
550
+
551
+ /// Copy the range [I, E) onto the uninitialized memory
552
+ /// starting with "Dest", constructing elements into it as needed.
553
+ template <typename It1, typename It2>
554
+ static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
555
+ // Arbitrary iterator types; just use the basic implementation.
556
+ std::uninitialized_copy(I, E, Dest);
557
+ }
558
+
559
+ /// Copy the range [I, E) onto the uninitialized memory
560
+ /// starting with "Dest", constructing elements into it as needed.
561
+ template <typename T1, typename T2>
562
+ static void uninitialized_copy(
563
+ T1* I,
564
+ T1* E,
565
+ T2* Dest,
566
+ std::enable_if_t<std::is_same_v<std::remove_const_t<T1>, T2>>* =
567
+ nullptr) {
568
+ // Use memcpy for PODs iterated by pointers (which includes SmallVector
569
+ // iterators): std::uninitialized_copy optimizes to memmove, but we can
570
+ // use memcpy here. Note that I and E are iterators and thus might be
571
+ // invalid for memcpy if they are equal.
572
+ if (I != E)
573
+ memcpy(reinterpret_cast<void*>(Dest), I, (E - I) * sizeof(T));
574
+ }
575
+
576
+ /// Double the size of the allocated memory, guaranteeing space for at
577
+ /// least one more element or MinSize if specified.
578
+ void grow(size_t MinSize = 0) {
579
+ this->grow_pod(MinSize, sizeof(T));
580
+ }
581
+
582
+ /// Reserve enough space to add one element, and return the updated element
583
+ /// pointer in case it was a reference to the storage.
584
+ const T* reserveForParamAndGetAddress(const T& Elt, size_t N = 1) {
585
+ return this->reserveForParamAndGetAddressImpl(this, Elt, N);
586
+ }
587
+
588
+ /// Reserve enough space to add one element, and return the updated element
589
+ /// pointer in case it was a reference to the storage.
590
+ T* reserveForParamAndGetAddress(T& Elt, size_t N = 1) {
591
+ return const_cast<T*>(this->reserveForParamAndGetAddressImpl(this, Elt, N));
592
+ }
593
+
594
+ /// Copy \p V or return a reference, depending on \a ValueParamT.
595
+ static ValueParamT forward_value_param(ValueParamT V) {
596
+ return V;
597
+ }
598
+
599
+ void growAndAssign(size_t NumElts, T Elt) {
600
+ // Elt has been copied in case it's an internal reference, side-stepping
601
+ // reference invalidation problems without losing the realloc optimization.
602
+ this->set_size(0);
603
+ this->grow(NumElts);
604
+ std::uninitialized_fill_n(this->begin(), NumElts, Elt);
605
+ this->set_size(NumElts);
606
+ }
607
+
608
+ template <typename... ArgTypes>
609
+ T& growAndEmplaceBack(ArgTypes&&... Args) {
610
+ // Use push_back with a copy in case Args has an internal reference,
611
+ // side-stepping reference invalidation problems without losing the realloc
612
+ // optimization.
613
+ push_back(T(std::forward<ArgTypes>(Args)...));
614
+ return this->back();
615
+ }
616
+
617
+ public:
618
+ void push_back(ValueParamT Elt) {
619
+ const T* EltPtr = reserveForParamAndGetAddress(Elt);
620
+ memcpy(reinterpret_cast<void*>(this->end()), EltPtr, sizeof(T));
621
+ this->set_size(this->size() + 1);
622
+ }
623
+
624
+ void pop_back() {
625
+ this->set_size(this->size() - 1);
626
+ }
627
+ };
628
+
629
+ /// This class consists of common code factored out of the SmallVector class to
630
+ /// reduce code duplication based on the SmallVector 'N' template parameter.
631
+ template <typename T>
632
+ class SmallVectorImpl : public SmallVectorTemplateBase<T> {
633
+ using SuperClass = SmallVectorTemplateBase<T>;
634
+
635
+ public:
636
+ using iterator = typename SuperClass::iterator;
637
+ using const_iterator = typename SuperClass::const_iterator;
638
+ using reference = typename SuperClass::reference;
639
+ using size_type = typename SuperClass::size_type;
640
+
641
+ protected:
642
+ using SmallVectorTemplateBase<T>::TakesParamByValue;
643
+ using ValueParamT = typename SuperClass::ValueParamT;
644
+
645
+ // Default ctor - Initialize to empty.
646
+ explicit SmallVectorImpl(unsigned N) : SmallVectorTemplateBase<T>(N) {}
647
+
648
+ public:
649
+ SmallVectorImpl(const SmallVectorImpl&) = delete;
650
+
651
+ ~SmallVectorImpl() {
652
+ // Subclass has already destructed this vector's elements.
653
+ // If this wasn't grown from the inline copy, deallocate the old space.
654
+ if (!this->isSmall())
655
+ free(this->begin());
656
+ }
657
+
658
+ void clear() {
659
+ this->destroy_range(this->begin(), this->end());
660
+ this->Size = 0;
661
+ }
662
+
663
+ private:
664
+ template <bool ForOverwrite>
665
+ void resizeImpl(size_type N) {
666
+ if (N < this->size()) {
667
+ this->pop_back_n(this->size() - N);
668
+ } else if (N > this->size()) {
669
+ this->reserve(N);
670
+ for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
671
+ if (ForOverwrite)
672
+ new (&*I) T;
673
+ else
674
+ new (&*I) T();
675
+ this->set_size(N);
676
+ }
677
+ }
678
+
679
+ public:
680
+ void resize(size_type N) {
681
+ resizeImpl<false>(N);
682
+ }
683
+
684
+ /// Like resize, but \ref T is POD, the new values won't be initialized.
685
+ void resize_for_overwrite(size_type N) {
686
+ resizeImpl<true>(N);
687
+ }
688
+
689
+ void resize(size_type N, ValueParamT NV) {
690
+ if (N == this->size())
691
+ return;
692
+
693
+ if (N < this->size()) {
694
+ this->pop_back_n(this->size() - N);
695
+ return;
696
+ }
697
+
698
+ // N > this->size(). Defer to append.
699
+ this->append(N - this->size(), NV);
700
+ }
701
+
702
+ void reserve(size_type N) {
703
+ if (this->capacity() < N)
704
+ this->grow(N);
705
+ }
706
+
707
+ void pop_back_n(size_type NumItems) {
708
+ assert(this->size() >= NumItems);
709
+ this->destroy_range(this->end() - NumItems, this->end());
710
+ this->set_size(this->size() - NumItems);
711
+ }
712
+
713
+ [[nodiscard]] T pop_back_val() {
714
+ T Result = ::std::move(this->back());
715
+ this->pop_back();
716
+ return Result;
717
+ }
718
+
719
+ void swap(SmallVectorImpl& RHS) noexcept;
720
+
721
+ /// Add the specified range to the end of the SmallVector.
722
+ template <
723
+ typename in_iter,
724
+ typename = std::enable_if_t<std::is_convertible_v<
725
+ typename std::iterator_traits<in_iter>::iterator_category,
726
+ std::input_iterator_tag>>>
727
+ void append(in_iter in_start, in_iter in_end) {
728
+ this->assertSafeToAddRange(in_start, in_end);
729
+ size_type NumInputs = std::distance(in_start, in_end);
730
+ this->reserve(this->size() + NumInputs);
731
+ this->uninitialized_copy(in_start, in_end, this->end());
732
+ this->set_size(this->size() + NumInputs);
733
+ }
734
+
735
+ /// Append \p NumInputs copies of \p Elt to the end.
736
+ void append(size_type NumInputs, ValueParamT Elt) {
737
+ const T* EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
738
+ std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
739
+ this->set_size(this->size() + NumInputs);
740
+ }
741
+
742
+ void append(std::initializer_list<T> IL) {
743
+ append(IL.begin(), IL.end());
744
+ }
745
+
746
+ void append(const SmallVectorImpl& RHS) {
747
+ append(RHS.begin(), RHS.end());
748
+ }
749
+
750
+ void assign(size_type NumElts, ValueParamT Elt) {
751
+ // Note that Elt could be an internal reference.
752
+ if (NumElts > this->capacity()) {
753
+ this->growAndAssign(NumElts, Elt);
754
+ return;
755
+ }
756
+
757
+ // Assign over existing elements.
758
+ std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
759
+ if (NumElts > this->size())
760
+ std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
761
+ else if (NumElts < this->size())
762
+ this->destroy_range(this->begin() + NumElts, this->end());
763
+ this->set_size(NumElts);
764
+ }
765
+
766
+ // FIXME: Consider assigning over existing elements, rather than clearing &
767
+ // re-initializing them - for all assign(...) variants.
768
+
769
+ template <
770
+ typename in_iter,
771
+ typename = std::enable_if_t<std::is_convertible_v<
772
+ typename std::iterator_traits<in_iter>::iterator_category,
773
+ std::input_iterator_tag>>>
774
+ void assign(in_iter in_start, in_iter in_end) {
775
+ this->assertSafeToReferenceAfterClear(in_start, in_end);
776
+ clear();
777
+ append(in_start, in_end);
778
+ }
779
+
780
+ void assign(std::initializer_list<T> IL) {
781
+ clear();
782
+ append(IL);
783
+ }
784
+
785
+ void assign(const SmallVectorImpl& RHS) {
786
+ assign(RHS.begin(), RHS.end());
787
+ }
788
+
789
+ iterator erase(iterator I) {
790
+ assert(
791
+ this->isReferenceToStorage(I) && "Iterator to erase is out of bounds.");
792
+
793
+ iterator N = I;
794
+ // Shift all elts down one.
795
+ std::move(I + 1, this->end(), I);
796
+ // Drop the last elt.
797
+ this->pop_back();
798
+ return (N);
799
+ }
800
+
801
+ iterator erase(iterator S, iterator E) {
802
+ assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.");
803
+
804
+ iterator N = S;
805
+ // Shift all elts down.
806
+ iterator I = std::move(E, this->end(), S);
807
+ // Drop the last elts.
808
+ this->destroy_range(I, this->end());
809
+ this->set_size(I - this->begin());
810
+ return (N);
811
+ }
812
+
813
+ private:
814
+ template <class ArgType>
815
+ iterator insert_one_impl(iterator I, ArgType&& Elt) {
816
+ // Callers ensure that ArgType is derived from T.
817
+ static_assert(
818
+ std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>, T>::
819
+ value,
820
+ "ArgType must be derived from T!");
821
+
822
+ if (I == this->end()) { // Important special case for empty vector.
823
+ this->push_back(::std::forward<ArgType>(Elt));
824
+ return this->end() - 1;
825
+ }
826
+
827
+ assert(
828
+ this->isReferenceToStorage(I) &&
829
+ "Insertion iterator is out of bounds.");
830
+
831
+ // Grow if necessary.
832
+ size_t Index = I - this->begin();
833
+ std::remove_reference_t<ArgType>* EltPtr =
834
+ this->reserveForParamAndGetAddress(Elt);
835
+ I = this->begin() + Index;
836
+
837
+ ::new ((void*)this->end()) T(::std::move(this->back()));
838
+ // Push everything else over.
839
+ std::move_backward(I, this->end() - 1, this->end());
840
+ this->set_size(this->size() + 1);
841
+
842
+ // If we just moved the element we're inserting, be sure to update
843
+ // the reference (never happens if TakesParamByValue).
844
+ static_assert(
845
+ !TakesParamByValue || std::is_same_v<ArgType, T>,
846
+ "ArgType must be 'T' when taking by value!");
847
+ if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
848
+ ++EltPtr;
849
+
850
+ *I = ::std::forward<ArgType>(*EltPtr);
851
+ return I;
852
+ }
853
+
854
+ public:
855
+ iterator insert(iterator I, T&& Elt) {
856
+ return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
857
+ }
858
+
859
+ iterator insert(iterator I, const T& Elt) {
860
+ return insert_one_impl(I, this->forward_value_param(Elt));
861
+ }
862
+
863
+ iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
864
+ // Convert iterator to elt# to avoid invalidating iterator when we reserve()
865
+ size_t InsertElt = I - this->begin();
866
+
867
+ if (I == this->end()) { // Important special case for empty vector.
868
+ append(NumToInsert, Elt);
869
+ return this->begin() + InsertElt;
870
+ }
871
+
872
+ assert(
873
+ this->isReferenceToStorage(I) &&
874
+ "Insertion iterator is out of bounds.");
875
+
876
+ // Ensure there is enough space, and get the (maybe updated) address of
877
+ // Elt.
878
+ const T* EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
879
+
880
+ // Uninvalidate the iterator.
881
+ I = this->begin() + InsertElt;
882
+
883
+ // If there are more elements between the insertion point and the end of the
884
+ // range than there are being inserted, we can use a simple approach to
885
+ // insertion. Since we already reserved space, we know that this won't
886
+ // reallocate the vector.
887
+ if (size_t(this->end() - I) >= NumToInsert) {
888
+ T* OldEnd = this->end();
889
+ append(
890
+ std::move_iterator<iterator>(this->end() - NumToInsert),
891
+ std::move_iterator<iterator>(this->end()));
892
+
893
+ // Copy the existing elements that get replaced.
894
+ std::move_backward(I, OldEnd - NumToInsert, OldEnd);
895
+
896
+ // If we just moved the element we're inserting, be sure to update
897
+ // the reference (never happens if TakesParamByValue).
898
+ if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
899
+ EltPtr += NumToInsert;
900
+
901
+ std::fill_n(I, NumToInsert, *EltPtr);
902
+ return I;
903
+ }
904
+
905
+ // Otherwise, we're inserting more elements than exist already, and we're
906
+ // not inserting at the end.
907
+
908
+ // Move over the elements that we're about to overwrite.
909
+ T* OldEnd = this->end();
910
+ this->set_size(this->size() + NumToInsert);
911
+ size_t NumOverwritten = OldEnd - I;
912
+ this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten);
913
+
914
+ // If we just moved the element we're inserting, be sure to update
915
+ // the reference (never happens if TakesParamByValue).
916
+ if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
917
+ EltPtr += NumToInsert;
918
+
919
+ // Replace the overwritten part.
920
+ std::fill_n(I, NumOverwritten, *EltPtr);
921
+
922
+ // Insert the non-overwritten middle part.
923
+ std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
924
+ return I;
925
+ }
926
+
927
+ template <
928
+ typename ItTy,
929
+ typename = std::enable_if_t<std::is_convertible_v<
930
+ typename std::iterator_traits<ItTy>::iterator_category,
931
+ std::input_iterator_tag>>>
932
+ iterator insert(iterator I, ItTy From, ItTy To) {
933
+ // Convert iterator to elt# to avoid invalidating iterator when we reserve()
934
+ size_t InsertElt = I - this->begin();
935
+
936
+ if (I == this->end()) { // Important special case for empty vector.
937
+ append(From, To);
938
+ return this->begin() + InsertElt;
939
+ }
940
+
941
+ assert(
942
+ this->isReferenceToStorage(I) &&
943
+ "Insertion iterator is out of bounds.");
944
+
945
+ // Check that the reserve that follows doesn't invalidate the iterators.
946
+ this->assertSafeToAddRange(From, To);
947
+
948
+ size_t NumToInsert = std::distance(From, To);
949
+
950
+ // Ensure there is enough space.
951
+ reserve(this->size() + NumToInsert);
952
+
953
+ // Uninvalidate the iterator.
954
+ I = this->begin() + InsertElt;
955
+
956
+ // If there are more elements between the insertion point and the end of the
957
+ // range than there are being inserted, we can use a simple approach to
958
+ // insertion. Since we already reserved space, we know that this won't
959
+ // reallocate the vector.
960
+ if (size_t(this->end() - I) >= NumToInsert) {
961
+ T* OldEnd = this->end();
962
+ append(
963
+ std::move_iterator<iterator>(this->end() - NumToInsert),
964
+ std::move_iterator<iterator>(this->end()));
965
+
966
+ // Copy the existing elements that get replaced.
967
+ std::move_backward(I, OldEnd - NumToInsert, OldEnd);
968
+
969
+ std::copy(From, To, I);
970
+ return I;
971
+ }
972
+
973
+ // Otherwise, we're inserting more elements than exist already, and we're
974
+ // not inserting at the end.
975
+
976
+ // Move over the elements that we're about to overwrite.
977
+ T* OldEnd = this->end();
978
+ this->set_size(this->size() + NumToInsert);
979
+ size_t NumOverwritten = OldEnd - I;
980
+ this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten);
981
+
982
+ // Replace the overwritten part.
983
+ for (T* J = I; NumOverwritten > 0; --NumOverwritten) {
984
+ *J = *From;
985
+ ++J;
986
+ ++From;
987
+ }
988
+
989
+ // Insert the non-overwritten middle part.
990
+ this->uninitialized_copy(From, To, OldEnd);
991
+ return I;
992
+ }
993
+
994
+ void insert(iterator I, std::initializer_list<T> IL) {
995
+ insert(I, IL.begin(), IL.end());
996
+ }
997
+
998
+ template <typename... ArgTypes>
999
+ reference emplace_back(ArgTypes&&... Args) {
1000
+ if (C10_UNLIKELY(this->size() >= this->capacity()))
1001
+ return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
1002
+
1003
+ ::new ((void*)this->end()) T(std::forward<ArgTypes>(Args)...);
1004
+ this->set_size(this->size() + 1);
1005
+ return this->back();
1006
+ }
1007
+
1008
+ SmallVectorImpl& operator=(const SmallVectorImpl& RHS);
1009
+
1010
+ SmallVectorImpl& operator=(SmallVectorImpl&& RHS) noexcept(
1011
+ std::is_nothrow_move_constructible_v<T> &&
1012
+ std::is_nothrow_destructible_v<T>);
1013
+
1014
+ bool operator==(const SmallVectorImpl& RHS) const {
1015
+ if (this->size() != RHS.size())
1016
+ return false;
1017
+ return std::equal(this->begin(), this->end(), RHS.begin());
1018
+ }
1019
+ bool operator!=(const SmallVectorImpl& RHS) const {
1020
+ return !(*this == RHS);
1021
+ }
1022
+
1023
+ bool operator<(const SmallVectorImpl& RHS) const {
1024
+ return std::lexicographical_compare(
1025
+ this->begin(), this->end(), RHS.begin(), RHS.end());
1026
+ }
1027
+ };
1028
+
1029
+ template <typename T>
1030
+ void SmallVectorImpl<T>::swap(SmallVectorImpl<T>& RHS) noexcept {
1031
+ if (this == &RHS)
1032
+ return;
1033
+
1034
+ // We can only avoid copying elements if neither vector is small.
1035
+ if (!this->isSmall() && !RHS.isSmall()) {
1036
+ std::swap(this->BeginX, RHS.BeginX);
1037
+ std::swap(this->Size, RHS.Size);
1038
+ std::swap(this->Capacity, RHS.Capacity);
1039
+ return;
1040
+ }
1041
+ this->reserve(RHS.size());
1042
+ RHS.reserve(this->size());
1043
+
1044
+ // Swap the shared elements.
1045
+ size_t NumShared = this->size();
1046
+ if (NumShared > RHS.size())
1047
+ NumShared = RHS.size();
1048
+ for (size_type i = 0; i != NumShared; ++i)
1049
+ std::swap((*this)[i], RHS[i]);
1050
+
1051
+ // Copy over the extra elts.
1052
+ if (this->size() > RHS.size()) {
1053
+ size_t EltDiff = this->size() - RHS.size();
1054
+ this->uninitialized_copy(this->begin() + NumShared, this->end(), RHS.end());
1055
+ RHS.set_size(RHS.size() + EltDiff);
1056
+ this->destroy_range(this->begin() + NumShared, this->end());
1057
+ this->set_size(NumShared);
1058
+ } else if (RHS.size() > this->size()) {
1059
+ size_t EltDiff = RHS.size() - this->size();
1060
+ this->uninitialized_copy(RHS.begin() + NumShared, RHS.end(), this->end());
1061
+ this->set_size(this->size() + EltDiff);
1062
+ this->destroy_range(RHS.begin() + NumShared, RHS.end());
1063
+ RHS.set_size(NumShared);
1064
+ }
1065
+ }
1066
+
1067
+ template <typename T>
1068
+ SmallVectorImpl<T>& SmallVectorImpl<T>::operator=(
1069
+ const SmallVectorImpl<T>& RHS) {
1070
+ // Avoid self-assignment.
1071
+ if (this == &RHS)
1072
+ return *this;
1073
+
1074
+ // If we already have sufficient space, assign the common elements, then
1075
+ // destroy any excess.
1076
+ size_t RHSSize = RHS.size();
1077
+ size_t CurSize = this->size();
1078
+ if (CurSize >= RHSSize) {
1079
+ // Assign common elements.
1080
+ iterator NewEnd;
1081
+ if (RHSSize)
1082
+ NewEnd = std::copy(RHS.begin(), RHS.begin() + RHSSize, this->begin());
1083
+ else
1084
+ NewEnd = this->begin();
1085
+
1086
+ // Destroy excess elements.
1087
+ this->destroy_range(NewEnd, this->end());
1088
+
1089
+ // Trim.
1090
+ this->set_size(RHSSize);
1091
+ return *this;
1092
+ }
1093
+
1094
+ // If we have to grow to have enough elements, destroy the current elements.
1095
+ // This allows us to avoid copying them during the grow.
1096
+ // FIXME: don't do this if they're efficiently moveable.
1097
+ if (this->capacity() < RHSSize) {
1098
+ // Destroy current elements.
1099
+ this->clear();
1100
+ CurSize = 0;
1101
+ this->grow(RHSSize);
1102
+ } else if (CurSize) {
1103
+ // Otherwise, use assignment for the already-constructed elements.
1104
+ std::copy(RHS.begin(), RHS.begin() + CurSize, this->begin());
1105
+ }
1106
+
1107
+ // Copy construct the new elements in place.
1108
+ this->uninitialized_copy(
1109
+ RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize);
1110
+
1111
+ // Set end.
1112
+ this->set_size(RHSSize);
1113
+ return *this;
1114
+ }
1115
+
1116
+ template <typename T>
1117
+ SmallVectorImpl<T>& SmallVectorImpl<T>::
1118
+ operator=(SmallVectorImpl<T>&& RHS) noexcept(
1119
+ std::is_nothrow_move_constructible_v<T> &&
1120
+ std::is_nothrow_destructible_v<T>) {
1121
+ // Avoid self-assignment.
1122
+ if (this == &RHS)
1123
+ return *this;
1124
+
1125
+ // If the RHS isn't small, clear this vector and then steal its buffer.
1126
+ if (!RHS.isSmall()) {
1127
+ this->destroy_range(this->begin(), this->end());
1128
+ if (!this->isSmall())
1129
+ free(this->begin());
1130
+ this->BeginX = RHS.BeginX;
1131
+ this->Size = RHS.Size;
1132
+ this->Capacity = RHS.Capacity;
1133
+ RHS.resetToSmall();
1134
+ return *this;
1135
+ }
1136
+
1137
+ // If we already have sufficient space, assign the common elements, then
1138
+ // destroy any excess.
1139
+ size_t RHSSize = RHS.size();
1140
+ size_t CurSize = this->size();
1141
+ if (CurSize >= RHSSize) {
1142
+ // Assign common elements.
1143
+ iterator NewEnd = this->begin();
1144
+ if (RHSSize)
1145
+ NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
1146
+
1147
+ // Destroy excess elements and trim the bounds.
1148
+ this->destroy_range(NewEnd, this->end());
1149
+ this->set_size(RHSSize);
1150
+
1151
+ // Clear the RHS.
1152
+ RHS.clear();
1153
+
1154
+ return *this;
1155
+ }
1156
+
1157
+ // If we have to grow to have enough elements, destroy the current elements.
1158
+ // This allows us to avoid copying them during the grow.
1159
+ // FIXME: this may not actually make any sense if we can efficiently move
1160
+ // elements.
1161
+ if (this->capacity() < RHSSize) {
1162
+ // Destroy current elements.
1163
+ this->clear();
1164
+ CurSize = 0;
1165
+ this->grow(RHSSize);
1166
+ } else if (CurSize) {
1167
+ // Otherwise, use assignment for the already-constructed elements.
1168
+ std::move(RHS.begin(), RHS.begin() + CurSize, this->begin());
1169
+ }
1170
+
1171
+ // Move-construct the new elements in place.
1172
+ this->uninitialized_move(
1173
+ RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize);
1174
+
1175
+ // Set end.
1176
+ this->set_size(RHSSize);
1177
+
1178
+ RHS.clear();
1179
+ return *this;
1180
+ }
1181
+
1182
+ /// Storage for the SmallVector elements. This is specialized for the N=0 case
1183
+ /// to avoid allocating unnecessary storage.
1184
+ template <typename T, unsigned N>
1185
+ struct SmallVectorStorage {
1186
+ alignas(T) char InlineElts[N * sizeof(T)];
1187
+ };
1188
+
1189
+ /// We need the storage to be properly aligned even for small-size of 0 so that
1190
+ /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
1191
+ /// well-defined.
1192
+ template <typename T>
1193
+ struct alignas(T) SmallVectorStorage<T, 0> {};
1194
+
1195
+ /// Forward declaration of SmallVector so that
1196
+ /// calculateSmallVectorDefaultInlinedElements can reference
1197
+ /// `sizeof(SmallVector<T, 0>)`.
1198
+ template <typename T, unsigned N>
1199
+ class /* LLVM_GSL_OWNER */ SmallVector;
1200
+
1201
+ /// Helper class for calculating the default number of inline elements for
1202
+ /// `SmallVector<T>`.
1203
+ ///
1204
+ /// This should be migrated to a constexpr function when our minimum
1205
+ /// compiler support is enough for multi-statement constexpr functions.
1206
+ template <typename T>
1207
+ struct CalculateSmallVectorDefaultInlinedElements {
1208
+ // Parameter controlling the default number of inlined elements
1209
+ // for `SmallVector<T>`.
1210
+ //
1211
+ // The default number of inlined elements ensures that
1212
+ // 1. There is at least one inlined element.
1213
+ // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
1214
+ // it contradicts 1.
1215
+ static constexpr size_t kPreferredSmallVectorSizeof = 64;
1216
+
1217
+ // static_assert that sizeof(T) is not "too big".
1218
+ //
1219
+ // Because our policy guarantees at least one inlined element, it is possible
1220
+ // for an arbitrarily large inlined element to allocate an arbitrarily large
1221
+ // amount of inline storage. We generally consider it an antipattern for a
1222
+ // SmallVector to allocate an excessive amount of inline storage, so we want
1223
+ // to call attention to these cases and make sure that users are making an
1224
+ // intentional decision if they request a lot of inline storage.
1225
+ //
1226
+ // We want this assertion to trigger in pathological cases, but otherwise
1227
+ // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
1228
+ // larger than kPreferredSmallVectorSizeof (otherwise,
1229
+ // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
1230
+ // pattern seems useful in practice).
1231
+ //
1232
+ // One wrinkle is that this assertion is in theory non-portable, since
1233
+ // sizeof(T) is in general platform-dependent. However, we don't expect this
1234
+ // to be much of an issue, because most LLVM development happens on 64-bit
1235
+ // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
1236
+ // 32-bit hosts, dodging the issue. The reverse situation, where development
1237
+ // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
1238
+ // 64-bit host, is expected to be very rare.
1239
+ static_assert(
1240
+ sizeof(T) <= 256,
1241
+ "You are trying to use a default number of inlined elements for "
1242
+ "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
1243
+ "explicit number of inlined elements with `SmallVector<T, N>` to make "
1244
+ "sure you really want that much inline storage.");
1245
+
1246
+ // Discount the size of the header itself when calculating the maximum inline
1247
+ // bytes.
1248
+ static constexpr size_t PreferredInlineBytes =
1249
+ kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
1250
+ static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
1251
+ static constexpr size_t value =
1252
+ NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
1253
+ };
1254
+
1255
+ /// This is a 'vector' (really, a variable-sized array), optimized
1256
+ /// for the case when the array is small. It contains some number of elements
1257
+ /// in-place, which allows it to avoid heap allocation when the actual number of
1258
+ /// elements is below that threshold. This allows normal "small" cases to be
1259
+ /// fast without losing generality for large inputs.
1260
+ ///
1261
+ /// \note
1262
+ /// In the absence of a well-motivated choice for the number of inlined
1263
+ /// elements \p N, it is recommended to use \c SmallVector<T> (that is,
1264
+ /// omitting the \p N). This will choose a default number of inlined elements
1265
+ /// reasonable for allocation on the stack (for example, trying to keep \c
1266
+ /// sizeof(SmallVector<T>) around 64 bytes).
1267
+ ///
1268
+ /// \warning This does not attempt to be exception safe.
1269
+ ///
1270
+ /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
1271
+ template <
1272
+ typename T,
1273
+ unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
1274
+ class /* LLVM_GSL_OWNER */ SmallVector : public SmallVectorImpl<T>,
1275
+ SmallVectorStorage<T, N> {
1276
+ public:
1277
+ SmallVector() : SmallVectorImpl<T>(N) {}
1278
+
1279
+ ~SmallVector() {
1280
+ // Destroy the constructed elements in the vector.
1281
+ this->destroy_range(this->begin(), this->end());
1282
+ }
1283
+
1284
+ explicit SmallVector(size_t Size, const T& Value = T())
1285
+ : SmallVectorImpl<T>(N) {
1286
+ this->assign(Size, Value);
1287
+ }
1288
+
1289
+ template <
1290
+ typename ItTy,
1291
+ typename = std::enable_if_t<std::is_convertible_v<
1292
+ typename std::iterator_traits<ItTy>::iterator_category,
1293
+ std::input_iterator_tag>>>
1294
+ SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
1295
+ this->append(S, E);
1296
+ }
1297
+
1298
+ // note: The enable_if restricts Container to types that have a .begin() and
1299
+ // .end() that return valid input iterators.
1300
+ template <
1301
+ typename Container,
1302
+ std::enable_if_t<
1303
+ std::is_convertible_v<
1304
+ typename std::iterator_traits<
1305
+ decltype(std::declval<Container>()
1306
+ .begin())>::iterator_category,
1307
+ std::input_iterator_tag> &&
1308
+ std::is_convertible_v<
1309
+ typename std::iterator_traits<
1310
+ decltype(std::declval<Container>()
1311
+ .end())>::iterator_category,
1312
+ std::input_iterator_tag>,
1313
+ int> = 0>
1314
+ explicit SmallVector(Container&& c) : SmallVectorImpl<T>(N) {
1315
+ this->append(c.begin(), c.end());
1316
+ }
1317
+
1318
+ SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
1319
+ this->assign(IL);
1320
+ }
1321
+
1322
+ SmallVector(const SmallVector& RHS) : SmallVectorImpl<T>(N) {
1323
+ if (!RHS.empty())
1324
+ SmallVectorImpl<T>::operator=(RHS);
1325
+ }
1326
+
1327
+ SmallVector& operator=(const SmallVector& RHS) {
1328
+ SmallVectorImpl<T>::operator=(RHS);
1329
+ return *this;
1330
+ }
1331
+
1332
+ SmallVector(SmallVector&& RHS) noexcept(
1333
+ std::is_nothrow_move_assignable_v<SmallVectorImpl<T>>)
1334
+ : SmallVectorImpl<T>(N) {
1335
+ if (!RHS.empty())
1336
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
1337
+ }
1338
+
1339
+ // note: The enable_if restricts Container to types that have a .begin() and
1340
+ // .end() that return valid input iterators.
1341
+ template <
1342
+ typename Container,
1343
+ std::enable_if_t<
1344
+ std::is_convertible_v<
1345
+ typename std::iterator_traits<
1346
+ decltype(std::declval<Container>()
1347
+ .begin())>::iterator_category,
1348
+ std::input_iterator_tag> &&
1349
+ std::is_convertible_v<
1350
+ typename std::iterator_traits<
1351
+ decltype(std::declval<Container>()
1352
+ .end())>::iterator_category,
1353
+ std::input_iterator_tag>,
1354
+ int> = 0>
1355
+ SmallVector& operator=(const Container& RHS) {
1356
+ this->assign(RHS.begin(), RHS.end());
1357
+ return *this;
1358
+ }
1359
+
1360
+ SmallVector(SmallVectorImpl<T>&& RHS) noexcept(
1361
+ std::is_nothrow_move_assignable_v<SmallVectorImpl<T>>)
1362
+ : SmallVectorImpl<T>(N) {
1363
+ if (!RHS.empty())
1364
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
1365
+ }
1366
+
1367
+ SmallVector& operator=(SmallVector&& RHS) noexcept(
1368
+ std::is_nothrow_move_assignable_v<SmallVectorImpl<T>>) {
1369
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
1370
+ return *this;
1371
+ }
1372
+
1373
+ SmallVector& operator=(SmallVectorImpl<T>&& RHS) noexcept(
1374
+ std::is_nothrow_move_constructible_v<SmallVectorImpl<T>>) {
1375
+ SmallVectorImpl<T>::operator=(::std::move(RHS));
1376
+ return *this;
1377
+ }
1378
+
1379
+ // note: The enable_if restricts Container to types that have a .begin() and
1380
+ // .end() that return valid input iterators.
1381
+ template <
1382
+ typename Container,
1383
+ std::enable_if_t<
1384
+ std::is_convertible_v<
1385
+ typename std::iterator_traits<
1386
+ decltype(std::declval<Container>()
1387
+ .begin())>::iterator_category,
1388
+ std::input_iterator_tag> &&
1389
+ std::is_convertible_v<
1390
+ typename std::iterator_traits<
1391
+ decltype(std::declval<Container>()
1392
+ .end())>::iterator_category,
1393
+ std::input_iterator_tag>,
1394
+ int> = 0>
1395
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
1396
+ SmallVector& operator=(Container&& C) {
1397
+ this->assign(C.begin(), C.end());
1398
+ return *this;
1399
+ }
1400
+
1401
+ SmallVector& operator=(std::initializer_list<T> IL) {
1402
+ this->assign(IL);
1403
+ return *this;
1404
+ }
1405
+ };
1406
+
1407
+ template <typename T, unsigned N>
1408
+ inline size_t capacity_in_bytes(const SmallVector<T, N>& X) {
1409
+ return X.capacity_in_bytes();
1410
+ }
1411
+
1412
+ template <typename T, unsigned N>
1413
+ std::ostream& operator<<(std::ostream& out, const SmallVector<T, N>& list) {
1414
+ int i = 0;
1415
+ out << "[";
1416
+ for (auto e : list) {
1417
+ if (i++ > 0)
1418
+ out << ", ";
1419
+ out << e;
1420
+ }
1421
+ out << "]";
1422
+ return out;
1423
+ }
1424
+
1425
+ template <typename RangeType>
1426
+ using ValueTypeFromRangeType = std::remove_const_t<
1427
+ std::remove_reference_t<decltype(*std::begin(std::declval<RangeType&>()))>>;
1428
+
1429
+ /// Given a range of type R, iterate the entire range and return a
1430
+ /// SmallVector with elements of the vector. This is useful, for example,
1431
+ /// when you want to iterate a range and then sort the results.
1432
+ template <unsigned Size, typename R>
1433
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
1434
+ SmallVector<ValueTypeFromRangeType<R>, Size> to_vector(R&& Range) {
1435
+ return {std::begin(Range), std::end(Range)};
1436
+ }
1437
+ template <typename R>
1438
+ SmallVector<
1439
+ ValueTypeFromRangeType<R>,
1440
+ CalculateSmallVectorDefaultInlinedElements<
1441
+ ValueTypeFromRangeType<R>>::value>
1442
+ // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
1443
+ to_vector(R&& Range) {
1444
+ return {std::begin(Range), std::end(Range)};
1445
+ }
1446
+
1447
+ } // end namespace c10
1448
+
1449
+ namespace std {
1450
+
1451
+ /// Implement std::swap in terms of SmallVector swap.
1452
+ template <typename T>
1453
+ inline void swap(
1454
+ c10::SmallVectorImpl<T>& LHS,
1455
+ c10::SmallVectorImpl<T>& RHS) noexcept {
1456
+ LHS.swap(RHS);
1457
+ }
1458
+
1459
+ /// Implement std::swap in terms of SmallVector swap.
1460
+ template <typename T, unsigned N>
1461
+ inline void swap(
1462
+ c10::SmallVector<T, N>& LHS,
1463
+ c10::SmallVector<T, N>& RHS) noexcept {
1464
+ LHS.swap(RHS);
1465
+ }
1466
+
1467
+ } // end namespace std
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/StringUtil.h ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_STRINGUTIL_H_
2
+ #define C10_UTIL_STRINGUTIL_H_
3
+
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/string_utils.h>
6
+
7
+ #include <cstddef>
8
+ #include <optional>
9
+ #include <ostream>
10
+ #include <sstream>
11
+ #include <string>
12
+ #include <string_view>
13
+ #include <type_traits>
14
+ #include <vector>
15
+
16
+ C10_CLANG_DIAGNOSTIC_PUSH()
17
+ #if C10_CLANG_HAS_WARNING("-Wshorten-64-to-32")
18
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wshorten-64-to-32")
19
+ #endif
20
+
21
+ namespace c10 {
22
+
23
+ namespace detail {
24
+
25
+ // Obtains the base name from a full path.
26
+ C10_API std::string StripBasename(const std::string& full_path);
27
+
28
+ C10_API std::string ExcludeFileExtension(const std::string& full_path);
29
+
30
+ struct CompileTimeEmptyString {
31
+ operator const std::string&() const {
32
+ static const std::string empty_string_literal;
33
+ return empty_string_literal;
34
+ }
35
+ operator const char*() const {
36
+ return "";
37
+ }
38
+ };
39
+
40
+ template <typename T>
41
+ struct CanonicalizeStrTypes {
42
+ using type = const T&;
43
+ };
44
+
45
+ template <size_t N>
46
+ // NOLINTNEXTLINE(*c-arrays*)
47
+ struct CanonicalizeStrTypes<char[N]> {
48
+ using type = const char*;
49
+ };
50
+
51
+ inline std::ostream& _str(std::ostream& ss) {
52
+ return ss;
53
+ }
54
+
55
+ template <class T, class = std::ostream&>
56
+ struct Streamable : std::false_type {};
57
+
58
+ template <class T>
59
+ struct Streamable<T, decltype(std::declval<std::ostream&>() << T{})>
60
+ : std::true_type {};
61
+
62
+ template <typename T>
63
+ inline std::ostream& _str(std::ostream& ss, const T& t) {
64
+ if constexpr (std::is_enum_v<T> && !Streamable<T>::value) {
65
+ // NOLINTNEXTLINE(modernize-type-traits)
66
+ return _str(ss, static_cast<typename std::underlying_type<T>::type>(t));
67
+ } else {
68
+ // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage)
69
+ ss << t;
70
+ return ss;
71
+ }
72
+ }
73
+
74
+ template <typename T>
75
+ inline std::ostream& _str(std::ostream& ss, const std::optional<T>& t) {
76
+ if (t.has_value()) {
77
+ return _str(ss, t.value());
78
+ }
79
+ ss << "std::nullopt";
80
+ return ss;
81
+ }
82
+ // Overloads of _str for wide types; forces narrowing.
83
+ C10_API std::ostream& _str(std::ostream& ss, const wchar_t* wCStr);
84
+ C10_API std::ostream& _str(std::ostream& ss, const wchar_t& wChar);
85
+ C10_API std::ostream& _str(std::ostream& ss, const std::wstring& wString);
86
+
87
+ template <>
88
+ inline std::ostream& _str<CompileTimeEmptyString>(
89
+ std::ostream& ss,
90
+ const CompileTimeEmptyString&) {
91
+ return ss;
92
+ }
93
+
94
+ template <typename T, typename... Args>
95
+ inline std::ostream& _str(std::ostream& ss, const T& t, const Args&... args) {
96
+ return _str(_str(ss, t), args...);
97
+ }
98
+
99
+ template <typename... Args>
100
+ struct _str_wrapper final {
101
+ static std::string call(const Args&... args) {
102
+ std::ostringstream ss;
103
+ _str(ss, args...);
104
+ return ss.str();
105
+ }
106
+ };
107
+
108
+ // Specializations for already-a-string types.
109
+ template <>
110
+ struct _str_wrapper<std::string> final {
111
+ // return by reference to avoid the binary size of a string copy
112
+ static const std::string& call(const std::string& str) {
113
+ return str;
114
+ }
115
+ };
116
+
117
+ template <>
118
+ struct _str_wrapper<const char*> final {
119
+ static const char* call(const char* str) {
120
+ return str;
121
+ }
122
+ };
123
+
124
+ // For c10::str() with an empty argument list (which is common in our assert
125
+ // macros), we don't want to pay the binary size for constructing and
126
+ // destructing a stringstream or even constructing a string.
127
+ template <>
128
+ struct _str_wrapper<> final {
129
+ static CompileTimeEmptyString call() {
130
+ return CompileTimeEmptyString();
131
+ }
132
+ };
133
+
134
+ } // namespace detail
135
+
136
+ // Convert a list of string-like arguments into a single string.
137
+ template <typename... Args>
138
+ inline decltype(auto) str(const Args&... args) {
139
+ return detail::_str_wrapper<
140
+ typename detail::CanonicalizeStrTypes<Args>::type...>::call(args...);
141
+ }
142
+
143
+ template <class Container>
144
+ inline std::string Join(const std::string& delimiter, const Container& v) {
145
+ std::stringstream s;
146
+ int cnt = static_cast<int64_t>(v.size()) - 1;
147
+ for (auto i = v.begin(); i != v.end(); ++i, --cnt) {
148
+ s << (*i) << (cnt ? delimiter : "");
149
+ }
150
+ return std::move(s).str();
151
+ }
152
+
153
+ // Replace all occurrences of "from" substring to "to" string.
154
+ // Returns number of replacements
155
+ size_t C10_API
156
+ ReplaceAll(std::string& s, std::string_view from, std::string_view to);
157
+
158
+ /// Represents a location in source code (for debugging).
159
+ struct C10_API SourceLocation {
160
+ const char* function;
161
+ const char* file;
162
+ uint32_t line;
163
+ };
164
+
165
+ std::ostream& operator<<(std::ostream& out, const SourceLocation& loc);
166
+
167
+ // unix isprint but insensitive to locale
168
+ inline bool isPrint(char s) {
169
+ return s > 0x1f && s < 0x7f;
170
+ }
171
+
172
+ inline void printQuotedString(std::ostream& stmt, const std::string_view str) {
173
+ stmt << "\"";
174
+ for (auto s : str) {
175
+ switch (s) {
176
+ case '\\':
177
+ stmt << "\\\\";
178
+ break;
179
+ case '\'':
180
+ stmt << "\\'";
181
+ break;
182
+ case '\"':
183
+ stmt << "\\\"";
184
+ break;
185
+ case '\a':
186
+ stmt << "\\a";
187
+ break;
188
+ case '\b':
189
+ stmt << "\\b";
190
+ break;
191
+ case '\f':
192
+ stmt << "\\f";
193
+ break;
194
+ case '\n':
195
+ stmt << "\\n";
196
+ break;
197
+ case '\r':
198
+ stmt << "\\r";
199
+ break;
200
+ case '\t':
201
+ stmt << "\\t";
202
+ break;
203
+ case '\v':
204
+ stmt << "\\v";
205
+ break;
206
+ default:
207
+ if (isPrint(s)) {
208
+ stmt << s;
209
+ } else {
210
+ // C++ io has stateful formatting settings. Messing with
211
+ // them is probably worse than doing this manually.
212
+ // NOLINTNEXTLINE(*c-arrays*)
213
+ char buf[4] = "000";
214
+ // NOLINTNEXTLINE(*narrowing-conversions)
215
+ buf[2] += s % 8;
216
+ s /= 8;
217
+ // NOLINTNEXTLINE(*narrowing-conversions)
218
+ buf[1] += s % 8;
219
+ s /= 8;
220
+ // NOLINTNEXTLINE(*narrowing-conversions)
221
+ buf[0] += s;
222
+ stmt << "\\" << buf;
223
+ }
224
+ break;
225
+ }
226
+ }
227
+ stmt << "\"";
228
+ }
229
+
230
+ template <typename T>
231
+ std::optional<T> tryToNumber(const char* symbol) = delete;
232
+ template <typename T>
233
+ std::optional<T> tryToNumber(const std::string& symbol) = delete;
234
+
235
+ /*
236
+ * Convert a string to a 64 bit integer. Trailing whitespaces are not supported.
237
+ * Similarly, integer string with trailing characters like "123abc" will be
238
+ * rejected.
239
+ */
240
+ template <>
241
+ C10_API std::optional<int64_t> tryToNumber<int64_t>(const char* symbol);
242
+ template <>
243
+ C10_API std::optional<int64_t> tryToNumber<int64_t>(const std::string& symbol);
244
+
245
+ /*
246
+ * Convert a string to a double. Trailing whitespaces are not supported.
247
+ * Similarly, integer string with trailing characters like "123abc" will
248
+ * be rejected.
249
+ */
250
+ template <>
251
+ C10_API std::optional<double> tryToNumber<double>(const char* symbol);
252
+ template <>
253
+ C10_API std::optional<double> tryToNumber<double>(const std::string& symbol);
254
+
255
+ C10_API std::vector<std::string_view> split(
256
+ std::string_view target,
257
+ char delimiter);
258
+ } // namespace c10
259
+
260
+ C10_CLANG_DIAGNOSTIC_POP()
261
+
262
+ #endif // C10_UTIL_STRINGUTIL_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Synchronized.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <mutex>
4
+
5
+ namespace c10 {
6
+
7
+ /**
8
+ * A very simple Synchronization class for error-free use of data
9
+ * in a multi-threaded context. See folly/docs/Synchronized.md for
10
+ * the inspiration of this class.
11
+ *
12
+ * Full URL:
13
+ * https://github.com/facebook/folly/blob/main/folly/docs/Synchronized.md
14
+ *
15
+ * This class implements a small subset of the generic functionality
16
+ * implemented by folly:Synchronized<T>. Specifically, only withLock<T>
17
+ * is implemented here since it's the smallest possible API that is
18
+ * able to cover a large surface area of functionality offered by
19
+ * folly::Synchronized<T>.
20
+ */
21
+ template <typename T>
22
+ class Synchronized final {
23
+ mutable std::mutex mutex_;
24
+ T data_;
25
+
26
+ public:
27
+ Synchronized() = default;
28
+ Synchronized(T const& data) : data_(data) {}
29
+ Synchronized(T&& data) : data_(std::move(data)) {}
30
+
31
+ // Don't permit copy construction, move, assignment, or
32
+ // move assignment, since the underlying std::mutex
33
+ // isn't necessarily copyable/moveable.
34
+ Synchronized(Synchronized const&) = delete;
35
+ Synchronized(Synchronized&&) = delete;
36
+ Synchronized operator=(Synchronized const&) = delete;
37
+ Synchronized operator=(Synchronized&&) = delete;
38
+ ~Synchronized() = default;
39
+
40
+ /**
41
+ * To use, call withLock<T> with a callback that accepts T either
42
+ * by copy or by reference. Use the protected variable in the
43
+ * provided callback safely.
44
+ */
45
+ template <typename CB>
46
+ auto withLock(CB&& cb) {
47
+ std::lock_guard<std::mutex> guard(this->mutex_);
48
+ return std::forward<CB>(cb)(this->data_);
49
+ }
50
+
51
+ /**
52
+ * To use, call withLock<T> with a callback that accepts T either
53
+ * by copy or by const reference. Use the protected variable in
54
+ * the provided callback safely.
55
+ */
56
+ template <typename CB>
57
+ auto withLock(CB&& cb) const {
58
+ std::lock_guard<std::mutex> guard(this->mutex_);
59
+ return std::forward<CB>(cb)(this->data_);
60
+ }
61
+ };
62
+ } // end namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ThreadLocal.h ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ /**
6
+ * Android versions with libgnustl incorrectly handle thread_local C++
7
+ * qualifier with composite types. NDK up to r17 version is affected.
8
+ *
9
+ * (A fix landed on Jun 4 2018:
10
+ * https://android-review.googlesource.com/c/toolchain/gcc/+/683601)
11
+ *
12
+ * In such cases, use c10::ThreadLocal<T> wrapper
13
+ * which is `pthread_*` based with smart pointer semantics.
14
+ *
15
+ * In addition, convenient macro C10_DEFINE_TLS_static is available.
16
+ * To define static TLS variable of type std::string, do the following
17
+ * ```
18
+ * C10_DEFINE_TLS_static(std::string, str_tls_);
19
+ * ///////
20
+ * {
21
+ * *str_tls_ = "abc";
22
+ * assert(str_tls_->length(), 3);
23
+ * }
24
+ * ```
25
+ *
26
+ * (see c10/test/util/ThreadLocal_test.cpp for more examples)
27
+ */
28
+ #if !defined(C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE)
29
+
30
+ #if defined(C10_ANDROID) && defined(__GLIBCXX__) && __GLIBCXX__ < 20180604
31
+ #define C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE
32
+ #endif // defined(C10_ANDROID) && defined(__GLIBCXX__) && __GLIBCXX__ < 20180604
33
+
34
+ #endif // !defined(C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE)
35
+
36
+ #if defined(C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE)
37
+ #include <c10/util/Exception.h>
38
+ #include <errno.h>
39
+ #include <pthread.h>
40
+ #include <memory>
41
+ namespace c10 {
42
+
43
+ /**
44
+ * @brief Temporary thread_local C++ qualifier replacement for Android
45
+ * based on `pthread_*`.
46
+ * To be used with composite types that provide default ctor.
47
+ */
48
+ template <typename Type>
49
+ class ThreadLocal {
50
+ public:
51
+ ThreadLocal() {
52
+ pthread_key_create(
53
+ &key_, [](void* buf) { delete static_cast<Type*>(buf); });
54
+ }
55
+
56
+ ~ThreadLocal() {
57
+ if (void* current = pthread_getspecific(key_)) {
58
+ delete static_cast<Type*>(current);
59
+ }
60
+
61
+ pthread_key_delete(key_);
62
+ }
63
+
64
+ ThreadLocal(const ThreadLocal&) = delete;
65
+ ThreadLocal& operator=(const ThreadLocal&) = delete;
66
+
67
+ Type& get() {
68
+ if (void* current = pthread_getspecific(key_)) {
69
+ return *static_cast<Type*>(current);
70
+ }
71
+
72
+ std::unique_ptr<Type> ptr = std::make_unique<Type>();
73
+ if (0 == pthread_setspecific(key_, ptr.get())) {
74
+ return *ptr.release();
75
+ }
76
+
77
+ int err = errno;
78
+ TORCH_INTERNAL_ASSERT(false, "pthread_setspecific() failed, errno = ", err);
79
+ }
80
+
81
+ Type& operator*() {
82
+ return get();
83
+ }
84
+
85
+ Type* operator->() {
86
+ return &get();
87
+ }
88
+
89
+ private:
90
+ pthread_key_t key_;
91
+ };
92
+
93
+ } // namespace c10
94
+
95
+ #define C10_DEFINE_TLS_static(Type, Name) static ::c10::ThreadLocal<Type> Name
96
+
97
+ #define C10_DECLARE_TLS_class_static(Class, Type, Name) \
98
+ static ::c10::ThreadLocal<Type> Name
99
+
100
+ #define C10_DEFINE_TLS_class_static(Class, Type, Name) \
101
+ ::c10::ThreadLocal<Type> Class::Name
102
+
103
+ #else // defined(C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE)
104
+
105
+ namespace c10 {
106
+
107
+ /**
108
+ * @brief Default thread_local implementation for non-Android cases.
109
+ * To be used with composite types that provide default ctor.
110
+ */
111
+ template <typename Type>
112
+ class ThreadLocal {
113
+ public:
114
+ using Accessor = Type* (*)();
115
+ explicit ThreadLocal(Accessor accessor) : accessor_(accessor) {}
116
+
117
+ ThreadLocal(const ThreadLocal&) = delete;
118
+ ThreadLocal(ThreadLocal&&) noexcept = default;
119
+ ThreadLocal& operator=(const ThreadLocal&) = delete;
120
+ ThreadLocal& operator=(ThreadLocal&&) noexcept = default;
121
+ ~ThreadLocal() = default;
122
+
123
+ Type& get() {
124
+ return *accessor_();
125
+ }
126
+
127
+ Type& operator*() {
128
+ return get();
129
+ }
130
+
131
+ Type* operator->() {
132
+ return &get();
133
+ }
134
+
135
+ private:
136
+ Accessor accessor_;
137
+ };
138
+
139
+ } // namespace c10
140
+
141
+ #define C10_DEFINE_TLS_static(Type, Name) \
142
+ static ::c10::ThreadLocal<Type> Name([]() { \
143
+ static thread_local Type var; \
144
+ return &var; \
145
+ })
146
+
147
+ #define C10_DECLARE_TLS_class_static(Class, Type, Name) \
148
+ static ::c10::ThreadLocal<Type> Name
149
+
150
+ #define C10_DEFINE_TLS_class_static(Class, Type, Name) \
151
+ ::c10::ThreadLocal<Type> Class::Name([]() { \
152
+ static thread_local Type var; \
153
+ return &var; \
154
+ })
155
+
156
+ #endif // defined(C10_PREFER_CUSTOM_THREAD_LOCAL_STORAGE)
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/ThreadLocalDebugInfo.h ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Export.h>
4
+
5
+ #include <cstdint>
6
+ #include <memory>
7
+
8
+ namespace c10 {
9
+
10
+ enum class C10_API_ENUM DebugInfoKind : uint8_t {
11
+ PRODUCER_INFO = 0,
12
+ MOBILE_RUNTIME_INFO,
13
+ PROFILER_STATE,
14
+ INFERENCE_CONTEXT, // for inference usage
15
+ PARAM_COMMS_INFO,
16
+
17
+ TEST_INFO, // used only in tests
18
+ TEST_INFO_2, // used only in tests
19
+ };
20
+
21
+ class C10_API DebugInfoBase {
22
+ public:
23
+ DebugInfoBase() = default;
24
+ virtual ~DebugInfoBase() = default;
25
+ };
26
+
27
+ // Thread local debug information is propagated across the forward
28
+ // (including async fork tasks) and backward passes and is supposed
29
+ // to be utilized by the user's code to pass extra information from
30
+ // the higher layers (e.g. model id) down to the lower levels
31
+ // (e.g. to the operator observers used for debugging, logging,
32
+ // profiling, etc)
33
+ class C10_API ThreadLocalDebugInfo {
34
+ public:
35
+ static DebugInfoBase* get(DebugInfoKind kind);
36
+
37
+ // Get current ThreadLocalDebugInfo
38
+ static std::shared_ptr<ThreadLocalDebugInfo> current();
39
+
40
+ // Internal, use DebugInfoGuard/ThreadLocalStateGuard
41
+ static void _forceCurrentDebugInfo(
42
+ std::shared_ptr<ThreadLocalDebugInfo> info);
43
+
44
+ // Push debug info struct of a given kind
45
+ static void _push(DebugInfoKind kind, std::shared_ptr<DebugInfoBase> info);
46
+ // Pop debug info, throws in case the last pushed
47
+ // debug info is not of a given kind
48
+ static std::shared_ptr<DebugInfoBase> _pop(DebugInfoKind kind);
49
+ // Peek debug info, throws in case the last pushed debug info is not of the
50
+ // given kind
51
+ static std::shared_ptr<DebugInfoBase> _peek(DebugInfoKind kind);
52
+
53
+ private:
54
+ std::shared_ptr<DebugInfoBase> info_;
55
+ DebugInfoKind kind_;
56
+ std::shared_ptr<ThreadLocalDebugInfo> parent_info_;
57
+
58
+ friend class DebugInfoGuard;
59
+ };
60
+
61
+ // DebugInfoGuard is used to set debug information,
62
+ // ThreadLocalDebugInfo is semantically immutable, the values are set
63
+ // through the scope-based guard object.
64
+ // Nested DebugInfoGuard adds/overrides existing values in the scope,
65
+ // restoring the original values after exiting the scope.
66
+ // Users can access the values through the ThreadLocalDebugInfo::get() call;
67
+ class C10_API DebugInfoGuard {
68
+ public:
69
+ DebugInfoGuard(DebugInfoKind kind, std::shared_ptr<DebugInfoBase> info);
70
+
71
+ explicit DebugInfoGuard(std::shared_ptr<ThreadLocalDebugInfo> info);
72
+
73
+ ~DebugInfoGuard();
74
+
75
+ DebugInfoGuard(const DebugInfoGuard&) = delete;
76
+ DebugInfoGuard(DebugInfoGuard&&) = delete;
77
+ DebugInfoGuard& operator=(const DebugInfoGuard&) = delete;
78
+ DebugInfoGuard& operator=(DebugInfoGuard&&) = delete;
79
+
80
+ private:
81
+ bool active_ = false;
82
+ std::shared_ptr<ThreadLocalDebugInfo> prev_info_ = nullptr;
83
+ };
84
+
85
+ } // namespace c10
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/Type.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_UTIL_TYPE_H_
2
+ #define C10_UTIL_TYPE_H_
3
+
4
+ #include <cstddef>
5
+ #include <string>
6
+ #ifdef __GXX_RTTI
7
+ #include <typeinfo>
8
+ #endif // __GXX_RTTI
9
+
10
+ #include <c10/macros/Macros.h>
11
+
12
+ namespace c10 {
13
+
14
+ /// Utility to demangle a C++ symbol name.
15
+ C10_API std::string demangle(const char* name);
16
+
17
+ /// Returns the printable name of the type.
18
+ template <typename T>
19
+ inline const char* demangle_type() {
20
+ #ifdef __GXX_RTTI
21
+ static const auto& name = *(new std::string(demangle(typeid(T).name())));
22
+ return name.c_str();
23
+ #else // __GXX_RTTI
24
+ return "(RTTI disabled, cannot show name)";
25
+ #endif // __GXX_RTTI
26
+ }
27
+
28
+ } // namespace c10
29
+
30
+ #endif // C10_UTIL_TYPE_H_
code/LaDi-RL-old-qwen-cod/LaDi-RL-old-qwen-cod/venv/lib64/python3.10/site-packages/torch/include/c10/util/TypeCast.h ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/macros/Macros.h>
3
+ #include <c10/util/BFloat16.h>
4
+ #include <c10/util/Float8_e4m3fn.h>
5
+ #include <c10/util/Float8_e4m3fnuz.h>
6
+ #include <c10/util/Float8_e5m2.h>
7
+ #include <c10/util/Float8_e5m2fnuz.h>
8
+ #include <c10/util/Float8_e8m0fnu.h>
9
+ #include <c10/util/Half.h>
10
+ #include <c10/util/complex.h>
11
+ #include <c10/util/overflows.h>
12
+
13
+ #include <type_traits>
14
+
15
+ C10_CLANG_DIAGNOSTIC_PUSH()
16
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion")
17
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion")
18
+ #endif
19
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
20
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
21
+ #endif
22
+
23
+ namespace c10 {
24
+
25
+ template <typename dest_t, typename src_t>
26
+ struct needs_real {
27
+ constexpr static bool value =
28
+ (is_complex<src_t>::value && !is_complex<dest_t>::value);
29
+ };
30
+
31
+ template <bool, typename src_t>
32
+ struct maybe_real {
33
+ C10_HOST_DEVICE static inline src_t apply(src_t src) {
34
+ return src;
35
+ }
36
+ };
37
+
38
+ template <typename src_t>
39
+ struct maybe_real<true, src_t> {
40
+ C10_HOST_DEVICE static inline decltype(auto) apply(src_t src) {
41
+ return src.real();
42
+ }
43
+ };
44
+
45
+ template <bool, typename src_t>
46
+ struct maybe_bool {
47
+ C10_HOST_DEVICE static inline src_t apply(src_t src) {
48
+ return src;
49
+ }
50
+ };
51
+
52
+ template <typename src_t>
53
+ struct maybe_bool<true, src_t> {
54
+ C10_HOST_DEVICE static inline decltype(auto) apply(src_t src) {
55
+ // Don't use bool operator so as to to also compile for ComplexHalf.
56
+ return src.real() || src.imag();
57
+ }
58
+ };
59
+
60
+ // Note: deliberately ignores undefined behavior, consistent with NumPy.
61
+ // PyTorch's type conversions can cause a variety of undefined behavior,
62
+ // including float to integral overflow and signed to unsigned integer overflow.
63
+ // Some of this undefined behavior is addressed below.
64
+ template <typename dest_t, typename src_t>
65
+ struct static_cast_with_inter_type {
66
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline dest_t apply(
67
+ src_t src) {
68
+ constexpr bool real = needs_real<dest_t, src_t>::value;
69
+ auto r = maybe_real<real, src_t>::apply(src);
70
+ return static_cast<dest_t>(r);
71
+ }
72
+ };
73
+
74
+ // Partial template specialization for casting to bool.
75
+ // Need to handle complex types separately, as we don't
76
+ // simply want to cast the real part to bool.
77
+ template <typename src_t>
78
+ struct static_cast_with_inter_type<bool, src_t> {
79
+ C10_HOST_DEVICE static inline bool apply(src_t src) {
80
+ constexpr bool complex = needs_real<bool, src_t>::value;
81
+ return static_cast<bool>(maybe_bool<complex, src_t>::apply(src));
82
+ }
83
+ };
84
+
85
+ // Partial template instantiation for casting to uint8.
86
+ // Note: Converting from negative float values to unsigned integer types is
87
+ // undefined behavior in C++, and current CPU and GPU compilers exhibit
88
+ // divergent behavior. Casting from negative float values to signed
89
+ // integer types and then to unsigned integer types is not undefined,
90
+ // however, so this cast improves the consistency of type conversions
91
+ // to uint8 across compilers.
92
+ // Further note: Type conversions across compilers still have other undefined
93
+ // and divergent behavior.
94
+ template <typename src_t>
95
+ struct static_cast_with_inter_type<uint8_t, src_t> {
96
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline uint8_t apply(
97
+ src_t src) {
98
+ constexpr bool real = needs_real<uint8_t, src_t>::value;
99
+ return static_cast<uint8_t>(
100
+ static_cast<int64_t>(maybe_real<real, src_t>::apply(src)));
101
+ }
102
+ };
103
+
104
+ template <>
105
+ struct static_cast_with_inter_type<c10::complex<c10::Half>, c10::BFloat16> {
106
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
107
+ c10::Half>
108
+ apply(c10::BFloat16 src) {
109
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
110
+ }
111
+ };
112
+
113
+ template <>
114
+ struct static_cast_with_inter_type<c10::complex<c10::Half>, c10::Float8_e5m2> {
115
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
116
+ c10::Half>
117
+ apply(c10::Float8_e5m2 src) {
118
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
119
+ }
120
+ };
121
+
122
+ template <>
123
+ struct static_cast_with_inter_type<
124
+ c10::complex<c10::Half>,
125
+ c10::Float8_e5m2fnuz> {
126
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
127
+ c10::Half>
128
+ apply(c10::Float8_e5m2fnuz src) {
129
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
130
+ }
131
+ };
132
+
133
+ template <>
134
+ struct static_cast_with_inter_type<
135
+ c10::complex<c10::Half>,
136
+ c10::Float8_e4m3fn> {
137
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
138
+ c10::Half>
139
+ apply(c10::Float8_e4m3fn src) {
140
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
141
+ }
142
+ };
143
+
144
+ template <>
145
+ struct static_cast_with_inter_type<
146
+ c10::complex<c10::Half>,
147
+ c10::Float8_e4m3fnuz> {
148
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
149
+ c10::Half>
150
+ apply(c10::Float8_e4m3fnuz src) {
151
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
152
+ }
153
+ };
154
+
155
+ // TODO(#146647): Can we make all these template specialization happen
156
+ // based off our apply macros?
157
+ template <>
158
+ struct static_cast_with_inter_type<
159
+ c10::complex<c10::Half>,
160
+ c10::Float8_e8m0fnu> {
161
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
162
+ c10::Half>
163
+ apply(c10::Float8_e8m0fnu src) {
164
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
165
+ }
166
+ };
167
+
168
+ template <>
169
+ struct static_cast_with_inter_type<c10::complex<c10::Half>, c10::Half> {
170
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
171
+ c10::Half>
172
+ apply(c10::Half src) {
173
+ return static_cast<c10::complex<c10::Half>>(c10::complex<float>{src});
174
+ }
175
+ };
176
+
177
+ template <>
178
+ struct static_cast_with_inter_type<
179
+ c10::complex<c10::Half>,
180
+ c10::complex<double>> {
181
+ C10_HOST_DEVICE __ubsan_ignore_undefined__ static inline c10::complex<
182
+ c10::Half>
183
+ apply(c10::complex<double> src) {
184
+ return static_cast<c10::complex<c10::Half>>(
185
+ static_cast<c10::complex<float>>(src));
186
+ }
187
+ };
188
+
189
+ template <typename To, typename From>
190
+ C10_HOST_DEVICE To convert(From f) {
191
+ return static_cast_with_inter_type<To, From>::apply(f);
192
+ }
193
+
194
+ // Define separately to avoid being inlined and prevent code-size bloat
195
+ [[noreturn]] C10_API void report_overflow(const char* name);
196
+
197
+ template <typename To, typename From>
198
+ To checked_convert(From f, const char* name) {
199
+ // Converting to bool can't overflow so we exclude this case from checking.
200
+ if (!std::is_same_v<To, bool> && overflows<To, From>(f)) {
201
+ report_overflow(name);
202
+ }
203
+ return convert<To, From>(f);
204
+ }
205
+
206
+ } // namespace c10
207
+
208
+ C10_CLANG_DIAGNOSTIC_POP()
209
+
210
+ // Trigger tests for D25440771. TODO: Remove this line any time you want.