)
+
+endif()
+
+if(CUTLASS_ENABLE_CUDNN AND NOT CUDNN_FOUND)
+ message(FATAL_ERROR "CUTLASS_ENABLE_CUDNN enabled but cuDNN library could not be found.")
+endif()
+
+message(STATUS "Configuring cuDNN ... done.")
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm50_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm50_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..617d041a3418a00e543c398900ef6080bc321b9d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm50_8h_source.html
@@ -0,0 +1,129 @@
+
+
+
+
+
+
+CUTLASS: mma_sm50.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 53 struct Mma <gemm::GemmShape<1, 1, 1>, 1, float, LayoutA, float, LayoutB, float, LayoutC, OpMultiplyAdd> {
60 Array<float, 1>
const &a,
61 Array<float, 1>
const &b,
62 Array<float, 1>
const &c
64 d[0] = a[0] * b[0] + c[0];
79 struct Mma <gemm::GemmShape<1, 1, 1>, 1, double, LayoutA, double, LayoutB, double, LayoutC, OpMultiplyAdd> {
86 Array<double, 1>
const &a,
87 Array<double, 1>
const &b,
88 Array<double, 1>
const &c
91 d[0] = a[0] * b[0] + c[0];
106 struct Mma <gemm::GemmShape<1, 1, 1>, 1, int, LayoutA, int, LayoutB, int, LayoutC, OpMultiplyAdd> {
113 Array<int, 1>
const &a,
114 Array<int, 1>
const &b,
115 Array<int, 1>
const &c
118 d[0] = a[0] * b[0] + c[0];
134 gemm::GemmShape<1, 1, 1>,
154 d[0].real() = a[0].real() * b[0].real() + c[0].real();
155 d[0].imag() = a[0].imag() * b[0].real() + c[0].imag();
156 d[0].real() = -a[0].imag() * b[0].imag() + d[0].real();
157 d[0].imag() = a[0].real() * b[0].imag() + d[0].imag();
173 gemm::GemmShape<1, 1, 1>,
189 Array<float, 1>
const &b,
193 d[0].real() = a[0].real() * b[0] + c[0].real();
194 d[0].imag() = a[0].imag() * b[0] + c[0].imag();
210 gemm::GemmShape<1, 1, 1>,
225 Array<float, 1>
const &a,
230 d[0].real() = a[0] * b[0].real() + c[0].real();
231 d[0].imag() = a[0] * b[0].imag() + d[0].imag();
247 gemm::GemmShape<1, 1, 1>,
267 d[0].real() = a[0].real() * b[0].real() + c[0].real();
268 d[0].imag() = a[0].imag() * b[0].real() + c[0].imag();
269 d[0].real() = -a[0].imag() * b[0].imag() + d[0].real();
270 d[0].imag() = a[0].real() * b[0].imag() + d[0].imag();
284 gemm::GemmShape<1, 1, 1>,
300 Array<double, 1>
const &b,
304 d[0].real() = a[0].real() * b[0] + c[0].real();
305 d[0].imag() = a[0].imag() * b[0] + c[0].imag();
319 gemm::GemmShape<1, 1, 1>,
334 Array<double, 1>
const &a,
339 d[0].real() = a[0] * b[0].real() + c[0].real();
340 d[0].imag() = a[0] * b[0].imag() + d[0].imag();
355 struct Mma <gemm::GemmShape<1, 1, 1>, 1,
half_t , LayoutA,
half_t , LayoutB, float, LayoutC, OpMultiplyAdd> {
362 Array<half_t, 1>
const &a,
363 Array<half_t, 1>
const &b,
364 Array<float, 1>
const &c
366 d[0] = float(a[0]) * float(b[0]) + c[0];
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, int, LayoutA, int, LayoutB, int, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< int, 1 > &d, Array< int, 1 > const &a, Array< int, 1 > const &b, Array< int, 1 > const &c)
Definition: arch/mma_sm50.h:111
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, double, LayoutB, complex< double >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< double >, 1 > &d, Array< complex< double >, 1 > const &a, Array< double, 1 > const &b, Array< complex< double >, 1 > const &c)
Definition: arch/mma_sm50.h:297
+
Definition: aligned_buffer.h:35
+
+
IEEE half-precision floating-point type.
Definition: half.h:126
+
Defines common types used for all GEMM-like operators.
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< float >, LayoutA, complex< float >, LayoutB, complex< float >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< float >, 1 > &d, Array< complex< float >, 1 > const &a, Array< complex< float >, 1 > const &b, Array< complex< float >, 1 > const &c)
Definition: arch/mma_sm50.h:147
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, complex< double >, LayoutB, complex< double >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< double >, 1 > &d, Array< complex< double >, 1 > const &a, Array< complex< double >, 1 > const &b, Array< complex< double >, 1 > const &c)
Definition: arch/mma_sm50.h:260
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, half_t, LayoutA, half_t, LayoutB, float, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< float, 1 > &d, Array< half_t, 1 > const &a, Array< half_t, 1 > const &b, Array< float, 1 > const &c)
Definition: arch/mma_sm50.h:360
+
Templates exposing architecture support for multiply-add operations.
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< float >, LayoutA, float, LayoutB, complex< float >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< float >, 1 > &d, Array< complex< float >, 1 > const &a, Array< float, 1 > const &b, Array< complex< float >, 1 > const &c)
Definition: arch/mma_sm50.h:186
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, float, LayoutA, float, LayoutB, float, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< float, 1 > &d, Array< float, 1 > const &a, Array< float, 1 > const &b, Array< float, 1 > const &c)
Definition: arch/mma_sm50.h:58
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, float, LayoutA, complex< float >, LayoutB, complex< float >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< float >, 1 > &d, Array< float, 1 > const &a, Array< complex< float >, 1 > const &b, Array< complex< float >, 1 > const &c)
Definition: arch/mma_sm50.h:223
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Shape of a matrix multiply-add operation.
Definition: include/cutlass/gemm/gemm.h:57
+
+
Defines layout functions used by TensorRef and derived classes.
+
Matrix multiply-add operation.
Definition: arch/mma.h:92
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, double, LayoutA, complex< double >, LayoutB, complex< double >, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< complex< double >, 1 > &d, Array< double, 1 > const &a, Array< complex< double >, 1 > const &b, Array< complex< double >, 1 > const &c)
Definition: arch/mma_sm50.h:332
+
cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, double, LayoutA, double, LayoutB, double, LayoutC, OpMultiplyAdd >::operator() CUTLASS_HOST_DEVICE void operator()(Array< double, 1 > &d, Array< double, 1 > const &a, Array< double, 1 > const &b, Array< double, 1 > const &c)
Definition: arch/mma_sm50.h:84
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm60_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm60_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..c1d586de8c811ddaf821d339f7c9245f24dfa55e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/arch_2mma__sm60_8h__dep__incl.md5
@@ -0,0 +1 @@
+ba69b14e3936946092854211499ae9fa
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..ed90b055aa2e85cfd2d56b78dfa40ddce682a621
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array_8h_source.html
@@ -0,0 +1,194 @@
+
+
+
+
+
+
+CUTLASS: array.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 49 template <
typename T,
int N,
bool RegisterSized>
52 sizeof (
typename Array<T, N, RegisterSized>::Storage) * 8 * Array<T, N, RegisterSized>::kStorageElements;
60 return !(x & (x - 1));
78 class Array<T, N, true> {
89 static size_t const kStorageElements = N;
92 static size_t const kElements = N;
157 return ptr_ == other.ptr_;
162 return ptr_ != other.ptr_;
167 class const_iterator {
194 const_iterator ret(*
this );
201 const_iterator ret(*
this );
213 return ptr_ == other.ptr_;
218 return ptr_ != other.ptr_;
223 class reverse_iterator {
269 return ptr_ == other.ptr_;
274 return ptr_ != other.ptr_;
279 class const_reverse_iterator {
306 const_reverse_iterator ret(*
this );
313 const_reverse_iterator ret(*
this );
325 return ptr_ == other.ptr_;
330 return ptr_ != other.ptr_;
347 for (
int i = 0; i < kElements; ++i) {
348 storage[i] = x.storage[i];
359 reference
at (size_type pos) {
360 return reinterpret_cast< reference
> (storage[pos]);
364 const_reference
at (size_type pos)
const {
365 return reinterpret_cast< const_reference
> (storage[pos]);
370 return reinterpret_cast< reference
> (storage[pos]);
375 return reinterpret_cast< const_reference
> (storage[pos]);
380 return reinterpret_cast< reference
> (storage[0]);
385 return reinterpret_cast< const_reference
> (storage[0]);
390 return reinterpret_cast< reference
> (storage[kStorageElements - 1]);
395 return reinterpret_cast< const_reference
> (storage[kStorageElements - 1]);
400 return reinterpret_cast< pointer
> (storage);
405 return reinterpret_cast< const_pointer
> (storage);
410 return reinterpret_cast< pointer
> (storage);
415 return reinterpret_cast< const_pointer
> (storage);
437 for (
int i = 0; i < kElements; ++i) {
444 return iterator(storage);
449 return const_iterator(storage);
454 return iterator(reinterpret_cast<pointer>(storage + kStorageElements));
459 return const_iterator(reinterpret_cast<const_pointer>(storage + kStorageElements));
464 return reverse_iterator(reinterpret_cast<pointer>(storage + kStorageElements));
469 return const_reverse_iterator(reinterpret_cast<const_pointer>(storage + kStorageElements));
474 return reverse_iterator(reinterpret_cast<pointer>(storage));
478 const_reverse_iterator
crend ()
const {
479 return const_reverse_iterator(reinterpret_cast<const_pointer>(storage));
value_type * pointer
Definition: array.h:103
+
CUTLASS_HOST_DEVICE bool operator!=(iterator const &other) const
Definition: array.h:161
+
CUTLASS_HOST_DEVICE const_reverse_iterator()
Definition: array.h:287
+
CUTLASS_HOST_DEVICE const_iterator(T const *_ptr)
Definition: array.h:178
+
CUTLASS_HOST_DEVICE const_iterator()
Definition: array.h:175
+
CUTLASS_HOST_DEVICE constexpr bool empty() const
Definition: array.h:420
+
CUTLASS_HOST_DEVICE const_reverse_iterator crbegin() const
Definition: array.h:468
+
ptrdiff_t difference_type
Definition: array.h:100
+
CUTLASS_HOST_DEVICE reverse_iterator & operator--()
Definition: array.h:243
+
Definition: aligned_buffer.h:35
+
+
static int const value
Definition: numeric_types.h:43
+
CUTLASS_HOST_DEVICE const_iterator operator++(int)
Definition: array.h:193
+
CUTLASS_HOST_DEVICE void fill(T const &value)
Definition: array.h:435
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
CUTLASS_HOST_DEVICE iterator end()
Definition: array.h:453
+
CUTLASS_HOST_DEVICE pointer data()
Definition: array.h:399
+
CUTLASS_HOST_DEVICE iterator begin()
Definition: array.h:443
+
CUTLASS_HOST_DEVICE reverse_iterator rbegin()
Definition: array.h:463
+
Aligned array type.
Definition: array.h:511
+
CUTLASS_HOST_DEVICE const_reference operator[](size_type pos) const
Definition: array.h:374
+
CUTLASS_HOST_DEVICE pointer raw_data()
Definition: array.h:409
+
CUTLASS_HOST_DEVICE reverse_iterator rend()
Definition: array.h:473
+
CUTLASS_HOST_DEVICE const_iterator cend() const
Definition: array.h:458
+
CUTLASS_HOST_DEVICE const_reverse_iterator(T const *_ptr)
Definition: array.h:290
+
CUTLASS_HOST_DEVICE reverse_iterator operator--(int)
Definition: array.h:256
+
size_t size_type
Definition: array.h:99
+
CUTLASS_HOST_DEVICE const_reverse_iterator & operator++()
Definition: array.h:293
+
CUTLASS_HOST_DEVICE constexpr size_type size() const
Definition: array.h:425
+
CUTLASS_HOST_DEVICE reference back()
Definition: array.h:389
+
CUTLASS_HOST_DEVICE bool operator!=(reverse_iterator const &other) const
Definition: array.h:273
+
CUTLASS_HOST_DEVICE reverse_iterator operator++(int)
Definition: array.h:249
+
CUTLASS_HOST_DEVICE bool operator!=(const_iterator const &other) const
Definition: array.h:217
+
CUTLASS_HOST_DEVICE bool operator!=(const_iterator const &other) const
Definition: array.h:329
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
value_type const & const_reference
Definition: array.h:102
+
CUTLASS_HOST_DEVICE reverse_iterator & operator++()
Definition: array.h:237
+
CUTLASS_HOST_DEVICE T const & operator*() const
Definition: array.h:207
+
value_type & reference
Definition: array.h:101
+
CUTLASS_HOST_DEVICE bool operator==(iterator const &other) const
Definition: array.h:156
+
CUTLASS_HOST_DEVICE const_reverse_iterator crend() const
Definition: array.h:478
+
CUTLASS_HOST_DEVICE reverse_iterator()
Definition: array.h:231
+
CUTLASS_HOST_DEVICE T & operator*() const
Definition: array.h:151
+
Defines the size of an element in bits.
Definition: numeric_types.h:42
+
CUTLASS_HOST_DEVICE iterator operator++(int)
Definition: array.h:137
+
CUTLASS_HOST_DEVICE bool operator==(reverse_iterator const &other) const
Definition: array.h:268
+
+
CUTLASS_HOST_DEVICE iterator & operator++()
Definition: array.h:125
+
T Storage
Storage type.
Definition: array.h:82
+
CUTLASS_HOST_DEVICE reverse_iterator(T *_ptr)
Definition: array.h:234
+
CUTLASS_HOST_DEVICE iterator(T *_ptr)
Definition: array.h:122
+
CUTLASS_HOST_DEVICE const_iterator & operator++()
Definition: array.h:181
+
CUTLASS_HOST_DEVICE const_reference back() const
Definition: array.h:394
+
CUTLASS_HOST_DEVICE iterator & operator--()
Definition: array.h:131
+
CUTLASS_HOST_DEVICE const_reference at(size_type pos) const
Definition: array.h:364
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
CUTLASS_HOST_DEVICE T & operator*() const
Definition: array.h:263
+
CUTLASS_HOST_DEVICE bool operator==(const_iterator const &other) const
Definition: array.h:212
+
CUTLASS_HOST_DEVICE reference front()
Definition: array.h:379
+
T Element
Element type.
Definition: array.h:85
+
CUTLASS_HOST_DEVICE const_pointer raw_data() const
Definition: array.h:414
+
CUTLASS_HOST_DEVICE constexpr size_type max_size() const
Definition: array.h:430
+
CUTLASS_HOST_DEVICE const_pointer data() const
Definition: array.h:404
+
CUTLASS_HOST_DEVICE bool operator==(const_iterator const &other) const
Definition: array.h:324
+
CUTLASS_HOST_DEVICE iterator()
Definition: array.h:119
+
CUTLASS_HOST_DEVICE constexpr bool ispow2(unsigned x)
Returns true if the argument is a power of 2.
Definition: array.h:59
+
CUTLASS_HOST_DEVICE Array(Array const &x)
Definition: array.h:345
+
CUTLASS_HOST_DEVICE iterator operator--(int)
Definition: array.h:144
+
CUTLASS_HOST_DEVICE constexpr unsigned floor_pow_2(unsigned x)
Returns the largest power of two not greater than the argument.
Definition: array.h:67
+
CUTLASS_HOST_DEVICE const_reverse_iterator operator--(int)
Definition: array.h:312
+
value_type const * const_pointer
Definition: array.h:104
+
CUTLASS_HOST_DEVICE const_reverse_iterator & operator--()
Definition: array.h:299
+
T value_type
Definition: array.h:98
+
CUTLASS_HOST_DEVICE reference operator[](size_type pos)
Definition: array.h:369
+
CUTLASS_HOST_DEVICE const_iterator cbegin() const
Definition: array.h:448
+
CUTLASS_HOST_DEVICE Array()
Definition: array.h:342
+
CUTLASS_HOST_DEVICE const_iterator operator--(int)
Definition: array.h:200
+
CUTLASS_HOST_DEVICE const_reverse_iterator operator++(int)
Definition: array.h:305
+
Basic include for CUTLASS.
+
CUTLASS_HOST_DEVICE T const & operator*() const
Definition: array.h:319
+
CUTLASS_HOST_DEVICE const_reference front() const
Definition: array.h:384
+
CUTLASS_HOST_DEVICE reference at(size_type pos)
Definition: array.h:359
+
CUTLASS_HOST_DEVICE const_iterator & operator--()
Definition: array.h:187
+
CUTLASS_HOST_DEVICE void clear()
Efficient clear method.
Definition: array.h:354
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..258b5a3b8e30bf0e906a0ba9ac8b67ea6e1a6b65
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__dep__incl.md5
@@ -0,0 +1 @@
+7c0288c037b6ea169ec7a3aa1015a4d4
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..bf4801afa01b1dd14583ef65d684eb5ebb991781
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/array__subbyte_8h__incl.md5
@@ -0,0 +1 @@
+36310516438810c2a8ba31a7816cd1de
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1AlignedArray__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1AlignedArray__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d8a08d8073b777c052a334d5f8f82ffd9ffe47b5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1AlignedArray__inherit__graph.md5
@@ -0,0 +1 @@
+5bfb78a70e6c0c4f1dba98d2cf455a30
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reference.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reference.html
new file mode 100644
index 0000000000000000000000000000000000000000..8ee82fd4f9deab76d5955f12cfc65fbebd473f71
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reference.html
@@ -0,0 +1,306 @@
+
+
+
+
+
+
+CUTLASS: cutlass::Array< T, N, false >::const_reference Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Reference object extracts sub-byte items.
+
+
+
#include <array_subbyte.h >
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reference::const_reference
+ (
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reference::const_reference
+ (
+ Storage const *
+ ptr ,
+
+
+
+
+ int
+ idx = 0
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE const T cutlass::Array< T, N, false >::const_reference::get
+ (
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reference::operator float
+ (
+ )
+ const
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reference::operator int
+ (
+ )
+ const
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reference::operator T
+ (
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reverse__iterator.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reverse__iterator.html
new file mode 100644
index 0000000000000000000000000000000000000000..2fdecf8ff9e65b109140c3dd9194d986639cc290
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4_1_1const__reverse__iterator.html
@@ -0,0 +1,192 @@
+
+
+
+
+
+
+CUTLASS: cutlass::Array< T, N, false >::const_reverse_iterator Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Bidirectional constant iterator over elements.
+
+
+
#include <array_subbyte.h >
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reverse_iterator::const_reverse_iterator
+ (
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, false >::const_reverse_iterator::const_reverse_iterator
+ (
+ Storage const *
+ ptr ,
+
+
+
+
+ int
+ idx = 0
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01true_01_4_1_1iterator.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01true_01_4_1_1iterator.html
new file mode 100644
index 0000000000000000000000000000000000000000..e67289515248eee49f51555b56c409217dcc2036
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1Array_3_01T_00_01N_00_01true_01_4_1_1iterator.html
@@ -0,0 +1,376 @@
+
+
+
+
+
+
+CUTLASS: cutlass::Array< T, N, true >::iterator Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Bidirectional iterator over elements.
+
+
+
#include <array.h >
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::Array< T, N, true >::iterator::iterator
+ (
+ T *
+ _ptr )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE T& cutlass::Array< T, N, true >::iterator::operator*
+ (
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
+
+
+
+template<typename T , int N>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1ConstSubbyteReference.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1ConstSubbyteReference.html
new file mode 100644
index 0000000000000000000000000000000000000000..96afa9ebf2f0728b6587e82b6401ca25633385e7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1ConstSubbyteReference.html
@@ -0,0 +1,803 @@
+
+
+
+
+
+
+CUTLASS: cutlass::ConstSubbyteReference< Element_, Storage_ > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <subbyte_reference.h >
+
+
+
template<typename Element_, typename Storage_ = uint8_t>
+class cutlass::ConstSubbyteReference< Element_, Storage_ >
+
+
This class provides a mechanism for packing and unpacking elements smaller than one byte. It assumes these sub-byte elements are packed in a traditional C++ numeric type.
+
The intended application is to provide a mechanism to indirectly reference elements in memory or Array<> objects whose addresses cannot otherwise be taken since they are smaller than one byte.
+
Supports basic pointer arithmetic:
+
Example:
+
int4b_t *ptr = ...;
+
SubbyteReference<int4b_t> ref = ptr; ref += 15;
+
int4b_t x = ref; // load an int4b_t ref = x + 2_s4; // perform arithmetic on int4b_t and then store
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
Parameters
+
+ offset pointer to memory logical offset in units of Element
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+inline explicit
+
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
+
+
+
+template<typename Element_, typename Storage_ = uint8_t>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1PredicateVector_1_1Iterator-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1PredicateVector_1_1Iterator-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..e9fa08c05cf48f66418165ae72e991fe6d77c3a4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1PredicateVector_1_1Iterator-members.html
@@ -0,0 +1,130 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator , including all inherited members.
+
+ at () const cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ get ()cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ Iterator (Iterator const &it)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ Iterator (PredicateVector &vec, int _start=0)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator!= (Iterator const &it) const cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator* () const cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator+ (int offset)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator++ ()cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator++ (int)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator+= (int offset)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator- (int offset)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator-- ()cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator-- (int)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator-= (int offset)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ operator== (Iterator const &it) const cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+ set (bool value=true)cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1thread_1_1LinearCombinationRelu_3_01ElementOutput___00_01Count_00_01int_00_01float_00_01Round_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1thread_1_1LinearCombinationRelu_3_01ElementOutput___00_01Count_00_01int_00_01float_00_01Round_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..dc5adccdfe98b10578a70bc7e3b2bb4dac5747a3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1thread_1_1LinearCombinationRelu_3_01ElementOutput___00_01Count_00_01int_00_01float_00_01Round_01_4.html
@@ -0,0 +1,423 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::thread::LinearCombinationRelu< ElementOutput_, Count, int, float, Round > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <linear_combination_relu.h >
+
+
+struct Params
+ Host-constructable parameters structure. More...
+
+
+
+
template<typename ElementOutput_, int Count, FloatRoundStyle Round>
+class cutlass::epilogue::thread::LinearCombinationRelu< ElementOutput_, Count, int, float, Round >
+
+
Applies a linear combination operator to an array of elements then clamps the output before converting to the output element type.
+
D = alpha * accumulator + beta * source + uniform
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
+
+
+
+template<typename ElementOutput_ , int Count, FloatRoundStyle Round>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1Epilogue__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1Epilogue__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..82666861bbffd3d24982e08884ade87807199f44
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1Epilogue__inherit__graph.md5
@@ -0,0 +1 @@
+a130b0088436334ae74190708d9a2deb
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1InterleavedEpilogue-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1InterleavedEpilogue-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..0e2c78d2287de4ada55bb52abaeb984d2fbe7e78
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1InterleavedEpilogue-members.html
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero > , including all inherited members.
+
+ AccumulatorAccessType typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ AccumulatorFragmentIterator typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ AccumulatorTile typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ ConstTensorRef typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ ElementAccumulator typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ ElementOutput typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ InterleavedEpilogue (SharedStorage &shared_storage, int thread_idx, int warp_idx, int lane_idx)cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero > inline
+ kElementsPerAccess cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero > static
+ kPartitionsK cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero > static
+ Layout typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ operator() (OutputOp const &output_op, OutputTileIterator destination_iterator, AccumulatorTile const &accumulators, OutputTileIterator source_iterator)cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero > inline
+ OutputAccessType typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ OutputOp typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ OutputTileIterator typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ Shape typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ SyncTensorRef typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ TensorRef typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ WarpCount typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+ WarpMmaOperator typedefcutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1SharedLoadIterator-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1SharedLoadIterator-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..6618353b8909d34dcf87f24025458356788893ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1threadblock_1_1SharedLoadIterator-members.html
@@ -0,0 +1,134 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > , including all inherited members.
+
+ AccessType typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ add_pointer_offset (LongIndex pointer_offset)cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > inline
+ add_tile_offset (TensorCoord const &offset)cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > inline
+ ConstTensorRef typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ Element typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ Fragment typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ Index typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ kAlignment cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > static
+ kElementsPerAccess cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > static
+ kMinAlignment cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > static
+ kThreads cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > static
+ Layout typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ load (Fragment &frag)cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > inline
+ load_with_pointer_offset (Fragment &frag, Index pointer_offset)cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > inline
+ LongIndex typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ Shape typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ SharedLoadIterator (TensorRef ref, int thread_idx)cutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment > inline
+ TensorCoord typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ TensorRef typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+ ThreadMap typedefcutlass::epilogue::threadblock::SharedLoadIterator< ThreadMap_, Element_, MaxAlignment >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorTensorOp_3_01WarpShape___00_01OperatorShape_6b5ec5b2b023c078c305dbf7583b79cf.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorTensorOp_3_01WarpShape___00_01OperatorShape_6b5ec5b2b023c078c305dbf7583b79cf.html
new file mode 100644
index 0000000000000000000000000000000000000000..ec5b9c28dcfc508d1d9eddefccecd1c8a418179d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorTensorOp_3_01WarpShape___00_01OperatorShape_6b5ec5b2b023c078c305dbf7583b79cf.html
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > , including all inherited members.
+
+ AccumulatorTile typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ Fragment typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ FragmentIteratorTensorOp (AccumulatorTile const &accum)cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > inline
+ kInterleavedK cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > static
+ kIterations cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > static
+ Layout typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ load (Fragment &frag, int index_offset=0) const cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > inline
+ operator++ ()cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > inline
+ operator-- ()cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > > inline
+ OperatorElementC typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ OperatorFragmentC typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ OperatorShape typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ Policy typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+ WarpShape typedefcutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1G8fb159e6b5b40e2838be5f52cfe17062.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1G8fb159e6b5b40e2838be5f52cfe17062.html
new file mode 100644
index 0000000000000000000000000000000000000000..279b491babfa86347985d50a3e01b033bad42aa0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1G8fb159e6b5b40e2838be5f52cfe17062.html
@@ -0,0 +1,127 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > , including all inherited members.
+
+ AccessType typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ AccumulatorTile typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ ElementC typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ Fragment typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ FragmentIteratorVoltaTensorOp (AccumulatorTile const &accum)cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > inline
+ InterleavedTileShape typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ kIterations cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > static
+ Layout typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ load (Fragment &frag, int index_offset=0) const cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > inline
+ operator++ ()cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > inline
+ operator-- ()cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor > inline
+ Policy typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+ WarpShape typedefcutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorWmmaTensorOp_3_01WarpShape___00_01OperatorShfdb1f120c6797383663f9fd11d0fc599.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorWmmaTensorOp_3_01WarpShape___00_01OperatorShfdb1f120c6797383663f9fd11d0fc599.html
new file mode 100644
index 0000000000000000000000000000000000000000..f16d06bd06b291f01b092cff897622ce6702bfba
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1FragmentIteratorWmmaTensorOp_3_01WarpShape___00_01OperatorShfdb1f120c6797383663f9fd11d0fc599.html
@@ -0,0 +1,403 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Partial specialization for row-major shared memory.
+
+
+
#include <fragment_iterator_wmma_tensor_op.h >
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename OperatorShape_ , typename OperatorElementC_ , typename OperatorFragmentC_ >
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1TileIteratorSimt_3_01WarpShape___00_01Operator___00_01Elemen511cc12482dd0c67e9fe697263803a4d.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1TileIteratorSimt_3_01WarpShape___00_01Operator___00_01Elemen511cc12482dd0c67e9fe697263803a4d.html
new file mode 100644
index 0000000000000000000000000000000000000000..6abc63788cd0ae54127052df5af27d397cb93ba7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1epilogue_1_1warp_1_1TileIteratorSimt_3_01WarpShape___00_01Operator___00_01Elemen511cc12482dd0c67e9fe697263803a4d.html
@@ -0,0 +1,137 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > , including all inherited members.
+
+ AccumulatorTile typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ add_pointer_offset (Index pointer_offset)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ add_tile_offset (TensorCoord const &tile_offset)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ Element typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ Fragment typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ Index typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ kIterations cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > static
+ Layout typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ load (Fragment &frag) const cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ load_with_pointer_offset (Fragment &frag, Index pointer_offset) const cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ LongIndex typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ Operator typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ operator+= (TensorCoord const &tile_offset)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ Padding typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ Policy typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ Shape typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ store (Fragment const &frag)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ store_with_pointer_offset (Fragment const &frag, Index pointer_offset)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ TensorCoord typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ TensorRef typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+ TileIteratorSimt ()cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ TileIteratorSimt (TensorRef const &ref, unsigned lane_id)cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ > inline
+ WarpShape typedefcutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1GemmSplitKParallel-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1GemmSplitKParallel-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..f688f2b08ec21984d0adcd9eb071d71e65396dce
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1GemmSplitKParallel-members.html
@@ -0,0 +1,142 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > , including all inherited members.
+
+ ArchTag typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ can_implement (Arguments const &args)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline static
+ ConvertScaledOp typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ElementA typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ElementAccumulator typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ElementB typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ElementC typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ EpilogueOutputOp typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ GemmKernel typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ GemmSplitKParallel ()cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ get_workspace_size (Arguments const &args)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline static
+ initialize (Arguments const &args, void *workspace)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ InstructionShape typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ kStages cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > static
+ LayoutA typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ LayoutB typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ LayoutC typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ Operator typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ operator() (cudaStream_t stream=nullptr)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ operator() (Arguments const &args, void *workspace=nullptr, cudaStream_t stream=nullptr)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ OperatorClass typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ReductionKernel typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ReductionOp typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ run (cudaStream_t stream=nullptr)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ ThreadblockShape typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ ThreadblockSwizzle typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+ update (Arguments const &args, void *workspace=nullptr)cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ > inline
+ WarpShape typedefcutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1Gemm_3_01ElementA___00_01LayoutA___00_01ElementB___00_01Layout4d0960ae6b1d1bf19e6239dbd002249c.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1Gemm_3_01ElementA___00_01LayoutA___00_01ElementB___00_01Layout4d0960ae6b1d1bf19e6239dbd002249c.html
new file mode 100644
index 0000000000000000000000000000000000000000..323ecfc2b00e2bd29d931479f934a916af60756c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1device_1_1Gemm_3_01ElementA___00_01LayoutA___00_01ElementB___00_01Layout4d0960ae6b1d1bf19e6239dbd002249c.html
@@ -0,0 +1,947 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm device Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+
+
+
+
+
+
Partial specialization for column-major output exchanges problem size and operand.
+
+
+
#include <gemm.h >
+
+
+using ElementA = ElementA_
+
+using LayoutA = LayoutA_
+
+using TensorRefA = TensorRef < ElementA const, LayoutA >
+
+using ElementB = ElementB_
+
+using LayoutB = LayoutB_
+
+using TensorRefB = TensorRef < ElementB const, LayoutB >
+
+using ElementC = ElementC_
+
+using LayoutC = layout::ColumnMajor
+
+using TensorRefC = TensorRef < ElementC const, LayoutC >
+
+using TensorRefD = TensorRef < ElementC , LayoutC >
+
+using ElementAccumulator = ElementAccumulator_
+
+using OperatorClass = OperatorClass_
+
+using ArchTag = ArchTag_
+
+using ThreadblockShape = ThreadblockShape_
+
+using WarpShape = WarpShape_
+
+using InstructionShape = InstructionShape_
+
+using EpilogueOutputOp = EpilogueOutputOp_
+
+using ThreadblockSwizzle = ThreadblockSwizzle_
+
+using Operator = Operator_
+
+using UnderlyingOperator = Gemm < ElementB , typename layout::LayoutTranspose < LayoutB >::type, ElementA , typename layout::LayoutTranspose < LayoutA >::type, ElementC , layout::RowMajor , ElementAccumulator , OperatorClass , ArchTag , ThreadblockShape , WarpShape , InstructionShape , EpilogueOutputOp , ThreadblockSwizzle , Stages, kAlignmentB , kAlignmentA , SplitKSerial, Operator , kIsBetaZero >
+
+using UnderlyingArguments = typename UnderlyingOperator::Arguments
+
+using GemmKernel = typename UnderlyingOperator::GemmKernel
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ArchTag = ArchTag_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ElementA = ElementA_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ElementAccumulator = ElementAccumulator_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ElementB = ElementB_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ElementC = ElementC_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::EpilogueOutputOp = EpilogueOutputOp_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::GemmKernel = typename UnderlyingOperator::GemmKernel
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::InstructionShape = InstructionShape_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::LayoutA = LayoutA_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::LayoutB = LayoutB_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::LayoutC = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Operator = Operator_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::OperatorClass = OperatorClass_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::TensorRefA = TensorRef <ElementA const, LayoutA >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::TensorRefB = TensorRef <ElementB const, LayoutB >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::TensorRefC = TensorRef <ElementC const, LayoutC >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::TensorRefD = TensorRef <ElementC , LayoutC >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ThreadblockShape = ThreadblockShape_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::ThreadblockSwizzle = ThreadblockSwizzle_
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::UnderlyingArguments = typename UnderlyingOperator::Arguments
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::UnderlyingOperator = Gemm < ElementB , typename layout::LayoutTranspose <LayoutB >::type, ElementA , typename layout::LayoutTranspose <LayoutA >::type, ElementC , layout::RowMajor , ElementAccumulator , OperatorClass , ArchTag , ThreadblockShape , WarpShape , InstructionShape , EpilogueOutputOp , ThreadblockSwizzle , Stages, kAlignmentB , kAlignmentA , SplitKSerial, Operator , kIsBetaZero >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+ using cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::WarpShape = WarpShape_
+
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Gemm
+ (
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ static Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::can_implement
+ (
+ Arguments const &
+ args )
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ static size_t cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::get_workspace_size
+ (
+ Arguments const &
+ args )
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::initialize
+ (
+ Arguments const &
+ args ,
+
+
+
+
+ void *
+ workspace = nullptr ,
+
+
+
+
+ cudaStream_t
+ stream = nullptr
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::operator()
+ (
+ cudaStream_t
+ stream = nullptr )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::operator()
+ (
+ Arguments const &
+ args ,
+
+
+
+
+ void *
+ workspace = nullptr ,
+
+
+
+
+ cudaStream_t
+ stream = nullptr
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::run
+ (
+ cudaStream_t
+ stream = nullptr )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ static UnderlyingArguments cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::to_underlying_arguments
+ (
+ Arguments const &
+ args )
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ Status cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::update
+ (
+ Arguments const &
+ args ,
+
+
+
+
+ void *
+ workspace = nullptr
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ int const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kAlignmentA = AlignmentA
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ int const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kAlignmentB = AlignmentB
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ int const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kAlignmentC = UnderlyingOperator::kAlignmentC
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ bool const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kIsBetaZero = IsBetaZero
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ bool const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kSplitKSerial = SplitKSerial
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA_ , typename LayoutA_ , typename ElementB_ , typename LayoutB_ , typename ElementC_ , typename ElementAccumulator_ , typename OperatorClass_ , typename ArchTag_ , typename ThreadblockShape_ , typename WarpShape_ , typename InstructionShape_ , typename EpilogueOutputOp_ , typename ThreadblockSwizzle_ , int Stages, int AlignmentA, int AlignmentB, bool SplitKSerial, typename Operator_ , bool IsBetaZero>
+
+
+
+
+
+ int const cutlass::gemm::device::Gemm < ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor , ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::kStages = Stages
+
+
+
+
+static
+
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1threadblock_1_1MmaBase_1_1SharedStorage.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1threadblock_1_1MmaBase_1_1SharedStorage.html
new file mode 100644
index 0000000000000000000000000000000000000000..7d58f10961eb5eb7424aed5ed5b7730124ff594c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1threadblock_1_1MmaBase_1_1SharedStorage.html
@@ -0,0 +1,328 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::threadblock::MmaBase< Shape_, Policy_, Stages, Enable >::SharedStorage Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Shared storage object needed by threadblock-scoped GEMM.
+
+
+
#include <mma_base.h >
+
+
+
+
+using ShapeA = MatrixShape < Shape::kM+Policy::SmemPaddingA::kRow, Shape::kK *kStages +Policy::SmemPaddingA::kColumn >
+ Shape of the A matrix operand in shared memory. More...
+
+using ShapeB = MatrixShape < Shape::kK *kStages +Policy::SmemPaddingB::kRow, Shape::kN+Policy::SmemPaddingB::kColumn >
+ Shape of the B matrix operand in shared memory. More...
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
+
+
+
+template<typename Shape_, typename Policy_, int Stages, typename Enable = bool>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator.html
new file mode 100644
index 0000000000000000000000000000000000000000..c8cd37939629e255f1ad23ff1535d5b9d8b3e5b2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand, Element_, Layout_, Policy_, PartitionsK, PartitionGroupSize > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <mma_simt_tile_iterator.h >
+
+
template<typename Shape_, Operand Operand, typename Element_, typename Layout_, typename Policy_, int PartitionsK = 1, int PartitionGroupSize = 1>
+class cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand, Element_, Layout_, Policy_, PartitionsK, PartitionGroupSize >
+
+
Iterates over operands to warp-level matrix multiply operations targeting SIMT instructions
+
concept: MutableRandomAccessContiguousTileIteratorConcept
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kC_00_01Element_a1f4bdda9e7a19223c391e2ec786b91d.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kC_00_01Element_a1f4bdda9e7a19223c391e2ec786b91d.html
new file mode 100644
index 0000000000000000000000000000000000000000..53e96dc89eb48ecc7eab7321fc88ae86d4668381
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kC_00_01Element_a1f4bdda9e7a19223c391e2ec786b91d.html
@@ -0,0 +1,137 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > , including all inherited members.
+
+ add_pointer_offset (LongIndex offset)cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ add_tile_offset (TensorCoord const &coord)cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ Delta typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ Element typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ Fragment typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ Index typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ Iterations typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ kOperand cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > static
+ Layout typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ load (Fragment &frag) const cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ load_with_pointer_offset (Fragment &frag, Index pointer_offset) const cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ LongIndex typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ MmaSimtTileIterator ()cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ MmaSimtTileIterator (TensorRef const &ref, int lane_id)cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ operator++ ()cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ operator-- ()cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ Policy typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ Shape typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ store (Fragment const &frag) const cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ store_with_pointer_offset (Fragment const &frag, Index pointer_offset) const cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ > inline
+ TensorCoord typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ TensorRef typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+ ThreadShape typedefcutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan34be8e21a40af3ebd2dc3dff460dca72.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan34be8e21a40af3ebd2dc3dff460dca72.html
new file mode 100644
index 0000000000000000000000000000000000000000..409775130db01fbc7c0ccd442203265177584ca2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan34be8e21a40af3ebd2dc3dff460dca72.html
@@ -0,0 +1,919 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <mma_tensor_op_tile_iterator_sm70.h >
+
+
+struct Policy
+ Internal structure of iterator - made public to enable introspection. More...
+
+
+
+
template<typename Shape_, typename Element_, typename InstructionShape_, int OpDelta_>
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >
+
+
This tile iterator is specialized for 32-thread TensorOps.
+
Satisfies: ReadableRandomAccessContiguousTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+ pointer_offset loads a tile with a logical offset AND a pointer offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ byte_offset loads a tile with a linear offset in units of bytes
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+ byte_offset loads a tile with a logical offset AND a pointer offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ pointer_offset loads a tile with a linear offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
advances in units of whole tiles along the logical coordinate space of the tensor
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
Notify the iterator which k-group it is currently pointing to.
+
This does not advance the iterator. Rather, it overrides its internal tracking with constant-valued k-group index to enable the compiler to fold constants and achieve more efficient code.
+
This is used by some nontrivial permuted layouts.
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , typename InstructionShape_ , int OpDelta_>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan5a221944f4a0e16ccab77ba684856942.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan5a221944f4a0e16ccab77ba684856942.html
new file mode 100644
index 0000000000000000000000000000000000000000..2431525c8edb1fca8bc3299d89f04806ad796e7e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operan5a221944f4a0e16ccab77ba684856942.html
@@ -0,0 +1,954 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <mma_tensor_op_tile_iterator_sm70.h >
+
+
+using Shape = Shape_
+ Shape of tile to load (concept: PitchLinearShape) More...
+
+using Element = Element_
+ Element type. More...
+
+using Layout = cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise < sizeof_bits < Element_ >::value, kKBlock >
+ Layout of source tile. More...
+
+using InstructionShape = InstructionShape_
+ Shape of one matrix product operation (concept: MatrixShape ) More...
+
+using TensorRef = TensorRef < Element , Layout >
+ TensorRef type for loading element from a tensor. More...
+
+using Index = typename TensorRef::Index
+ Index type. More...
+
+using LongIndex = typename TensorRef::LongIndex
+ Long Index type. More...
+
+using TensorCoord = typename TensorRef::TensorCoord
+ Coordinate for an element in the tensor. More...
+
+using Base = MmaVoltaTensorOpMultiplicandTileIterator < layout::PitchLinearShape < Shape::kRow, Shape::kColumn >, kOperand , Element , layout::VoltaTensorOpMultiplicandCrosswise < sizeof_bits < Element_ >::value, kKBlock >, layout::PitchLinearShape < InstructionShape::kRow, InstructionShape::kColumn >, kOpDelta , kThreads >
+ Underlying tile iterator implementation. More...
+
+using Fragment = Array< Element , Shape::kCount/kThreads *2 >
+ Fragment object holding a thread's part of a tile. More...
+
+
+
+
template<typename Shape_, Operand Operand_, typename Element_, typename InstructionShape_, int OpDelta_, int KBlock>
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >
+
+
This tile iterator is specialized for 32-thread TensorOps. It uses LDS to load from shared memory and therefore must be initialized with a TensorRef to shared memory.
+
Satisfies: ReadableRandomAccessContiguousTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+ using cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator < Shape_, Operand_, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise < sizeof_bits < Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >::Base = MmaVoltaTensorOpMultiplicandTileIterator < layout::PitchLinearShape <Shape::kRow, Shape::kColumn>, kOperand , Element , layout::VoltaTensorOpMultiplicandCrosswise <sizeof_bits <Element_>::value, kKBlock >, layout::PitchLinearShape <InstructionShape::kRow, InstructionShape::kColumn>, kOpDelta , kThreads >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Advances an iterator along logical dimensions of matrix in units of whole tiles
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+ pointer_offset loads a tile with a logical offset AND a pointer offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ byte_offset loads a tile with a linear offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ tile_offset loads a tile with a logical offset in units of whole tiles
+ byte_offset loads a tile with a logical offset AND a pointer offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Parameters
+
+ frag fragment to load from the tensor
+ pointer_offset loads a tile with a linear offset
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
advances in units of whole tiles along the logical coordinate space of the tensor
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
advances in units of whole tiles along the logical coordinate space of the tensor
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Notify the iterator which k-group it is currently pointing to.
+
This does not advance the iterator. Rather, it overrides its internal tracking with constant-valued k-group index to enable the compiler to fold constants and achieve more efficient code.
+
This is used by some nontrivial permuted layouts.
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape )
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , Operand Operand_, typename Element_ , typename InstructionShape_ , int OpDelta_, int KBlock>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1RowMajor-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1RowMajor-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..6903ff8001c7bb156d3c3b44865c948cb91e0e55
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1RowMajor-members.html
@@ -0,0 +1,130 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::layout::RowMajor , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1TensorCxRSKx.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1TensorCxRSKx.html
new file mode 100644
index 0000000000000000000000000000000000000000..f0b76bcd15db55bfc90e5c69f53e0e19e44030b2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1layout_1_1TensorCxRSKx.html
@@ -0,0 +1,457 @@
+
+
+
+
+
+
+CUTLASS: cutlass::layout::TensorCxRSKx< Interleave > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Mapping function for 4-D CxRSKx tensors.
+
+
+
#include <tensor.h >
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
+
+
+
+template<int Interleave>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen41e459f664d17473570cf22fb616845f.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen41e459f664d17473570cf22fb616845f.html
new file mode 100644
index 0000000000000000000000000000000000000000..7bb740e5ca04d1e6efba2259945181445f976ece
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen41e459f664d17473570cf22fb616845f.html
@@ -0,0 +1,204 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >::Params Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Parameters object is precomputed state and is host-constructible.
+
+
+
#include <predicated_tile_access_iterator.h >
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ >
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen809793e785fb4211888c6b4e5dcfcb39.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen809793e785fb4211888c6b4e5dcfcb39.html
new file mode 100644
index 0000000000000000000000000000000000000000..002f69fd3bf7b9a19ad9543e5ea6710986f217e0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen809793e785fb4211888c6b4e5dcfcb39.html
@@ -0,0 +1,888 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <predicated_tile_access_iterator.h >
+
+
+class Params
+ Parameters object is precomputed state and is host-constructible. More...
+
+
+
+
template<typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, typename AccessType_, int InterleavedK>
+class cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >
+
+
Specialization of PredicatedTileAccessIterator for interleaved-32 data. It is mapped to the congruous layout.
+
Satisfies: ForwardTileIteratorConcept | ReadableContiguousTileIteratorConcept | WriteableContiguousTileIteratorConcept | MaskedTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+ using cutlass::transform::threadblock::PredicatedTileAccessIterator < Shape_, Element_, layout::RowMajorInterleaved < InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >::UnderlyingIterator = PredicatedTileAccessIterator < layout::PitchLinearShape <Shape::kColumn * kInterleavedK , Shape::kRow / kInterleavedK >, Element , layout::PitchLinear , (kAdvanceRank == 0 ? 1 : 0), ThreadMap , AccessType >
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
Constructs a TileIterator from its precomputed state, threadblock offset, and thread ID
+
Parameters
+
+ params Precomputed parameters object
+ pointer Pointer to start of tensor
+ extent Extent of tensor
+ thread_id ID of each participating thread
+ threadblock_offset Initial offset of threadblock
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
Parameters
+
+ params Precomputed parameters object
+ pointer Pointer to start of tensor
+ extent Extent of tensor
+ thread_id ID of each participating thread
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
Advances an iterator along logical dimensions of matrix in units of whole tiles
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
Advances to the next tile in memory.
+
The first time this method is called, predicates are updated, and the iterator's internal pointer is reverted to the first "steady state" tile. Subsequent calls are lightweight and must only update the internal pointer.
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
Advances to the next tile in memory.
+
The first time this method is called, predicates are updated, and the iterator's internal pointer is reverted to the first "steady state" tile. Subsequent calls are lightweight and must only update the internal pointer.
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , typename AccessType_ , int InterleavedK>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0010e951973fa9415dd5e9e2e33dbd5289.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0010e951973fa9415dd5e9e2e33dbd5289.html
new file mode 100644
index 0000000000000000000000000000000000000000..673b35856194e898e2574126cae2deabacc7ec51
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0010e951973fa9415dd5e9e2e33dbd5289.html
@@ -0,0 +1,144 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > , including all inherited members.
+
+ AccessType typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ add_pointer_offset (LongIndex pointer_offset)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ clear_mask ()cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ Element typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ enable_mask ()cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ Fragment typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ get_mask (Mask &mask)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ Index typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ kAdvanceRank cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > static
+ kInterleavedK cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > static
+ Layout typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ load (Fragment &frag)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ load_with_pointer_offset (Fragment &frag, Index pointer_offset)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ LongIndex typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ Mask typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ NonConstPointer typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ operator++ ()cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ operator++ (int)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ Pointer typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ PredicatedTileIterator (Params const ¶ms, Pointer pointer, TensorCoord extent, int thread_id, TensorCoord const &threadblock_offset)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ PredicatedTileIterator (Params const ¶ms, Pointer pointer, TensorCoord extent, int thread_id)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ set_mask (Mask const &mask)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ Shape typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ store (Fragment const &frag)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ store_with_pointer_offset (Fragment const &frag, Index pointer_offset)cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize > inline
+ TensorCoord typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ TensorRef typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ TensorView typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ ThreadMap typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+ UnderlyingIterator typedefcutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0041ea81994f8af0d4d071fdb9e66b5ff0.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0041ea81994f8af0d4d071fdb9e66b5ff0.html
new file mode 100644
index 0000000000000000000000000000000000000000..33e445c40fad96eed1111dc8586e647572327da4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___0041ea81994f8af0d4d071fdb9e66b5ff0.html
@@ -0,0 +1,879 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessSize > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <predicated_tile_iterator.h >
+
+
+class Params
+ Parameters object is precomputed state and is host-constructible. More...
+
+
+
+CUTLASS_HOST_DEVICE PredicatedTileIterator (Params const ¶ms, Pointer pointer, TensorCoord extent, int thread_id, TensorCoord const &threadblock_offset)
+ Constructs a TileIterator from its precomputed state, threadblock offset, and thread ID. More...
+
+CUTLASS_HOST_DEVICE PredicatedTileIterator (Params const ¶ms, Pointer pointer, TensorCoord extent, int thread_id)
+ Construct a PredicatedTileIterator with zero threadblock offset. More...
+
+CUTLASS_HOST_DEVICE void add_pointer_offset (LongIndex pointer_offset)
+ Adds a pointer offset in units of Element. More...
+
+CUTLASS_HOST_DEVICE PredicatedTileIterator & operator++ ()
+
+CUTLASS_HOST_DEVICE PredicatedTileIterator operator++ (int)
+
+CUTLASS_HOST_DEVICE void clear_mask ()
+ Clears the predicate set efficiently. More...
+
+CUTLASS_HOST_DEVICE void enable_mask ()
+ Clears the predicate set efficiently. More...
+
+CUTLASS_HOST_DEVICE void set_mask (Mask const &mask)
+ Sets the predicate mask, overriding value stored in predicate iterator. More...
+
+CUTLASS_HOST_DEVICE void get_mask (Mask &mask)
+ Gets the mask. More...
+
+CUTLASS_DEVICE void load_with_pointer_offset (Fragment &frag, Index pointer_offset)
+ Loads a fragment from memory. More...
+
+CUTLASS_DEVICE void load (Fragment &frag)
+ Loads a fragment from memory. More...
+
+CUTLASS_DEVICE void store_with_pointer_offset (Fragment const &frag, Index pointer_offset)
+ Store a fragment to memory. More...
+
+CUTLASS_DEVICE void store (Fragment const &frag)
+ Store a fragment to memory. More...
+
+
+
+
template<typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int AccessSize>
+class cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessSize >
+
+
Specialization of PredicatedTileIterator for pitch-linear data.
+
Satisfies: ForwardTileIteratorConcept | ReadableContiguousTileIteratorConcept | WriteableContiguousTileIteratorConcept | MaskedTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+ using cutlass::transform::threadblock::PredicatedTileIterator < Shape_, Element_, layout::RowMajor , AdvanceRank, ThreadMap_, AccessSize >::UnderlyingIterator = PredicatedTileIterator < layout::PitchLinearShape <Shape::kColumn, Shape::kRow>, Element , layout::PitchLinear , (kAdvanceRank == 0 ? 1 : 0), ThreadMap , AccessSize >
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
Parameters
+
+ params Precomputed parameters object
+ pointer Pointer to start of tensor
+ extent Extent of tensor
+ thread_id ID of each participating thread
+ threadblock_offset Initial offset of threadblock
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
Parameters
+
+ params Precomputed parameters object
+ pointer Pointer to start of tensor
+ extent Extent of tensor
+ thread_id ID of each participating thread
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
Advances to the next tile in memory.
+
The first time this method is called, predicates are updated, and the iterator's internal pointer is reverted to the first "steady state" tile. Subsequent calls are lightweight and must only update the internal pointer.
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
Advances to the next tile in memory.
+
The first time this method is called, predicates are updated, and the iterator's internal pointer is reverted to the first "steady state" tile. Subsequent calls are lightweight and must only update the internal pointer.
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___006a5f2f7a8271031e6cdc5daa5441f2af.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___006a5f2f7a8271031e6cdc5daa5441f2af.html
new file mode 100644
index 0000000000000000000000000000000000000000..7780ad67e5cefdb79c7956785c0748d9dbc3a476
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileIterator_3_01Shape___00_01Element___006a5f2f7a8271031e6cdc5daa5441f2af.html
@@ -0,0 +1,204 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessSize >::Params Class Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Parameters object is precomputed state and is host-constructible.
+
+
+
#include <predicated_tile_iterator.h >
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int AccessSize>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__0855e9d9ab619202d2397180c1e4c4a5.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__0855e9d9ab619202d2397180c1e4c4a5.html
new file mode 100644
index 0000000000000000000000000000000000000000..749e511aea6658a13dc47fc74bce0c2d5ddb411c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__0855e9d9ab619202d2397180c1e4c4a5.html
@@ -0,0 +1,552 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, Alignment > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <regular_tile_access_iterator_pitch_linear.h >
+
+
+
template<typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int Alignment>
+class cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, Alignment >
+
+
Tile iterator specialized for congruous arrangements for TensorOps
+
Satisfies: ForwardTileIteratorConcept | ReadableContiguousTileIteratorConcept | WriteableContiguousTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
Parameters
+
+ ref Pointer to start of tensor
+ thread_id ID of each participating thread
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__213c660dae89d11f257af8ed849b6926.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__213c660dae89d11f257af8ed849b6926.html
new file mode 100644
index 0000000000000000000000000000000000000000..b9ae704020f8a621e4e283ab99e2e6d9e5e8a825
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__213c660dae89d11f257af8ed849b6926.html
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > , including all inherited members.
+
+ AccessType typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ add_pointer_offset (LongIndex pointer_offset)cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ add_tile_offset (TensorCoord const &coord)cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ Element typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ get () const cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ Index typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ kAdvanceRank cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > static
+ kAlignment cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > static
+ Layout typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ LongIndex typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ operator++ ()cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ operator++ (int)cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ RegularTileAccessIterator (TensorRef ref, int thread_id)cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ set_iteration_index (int index)cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment > inline
+ Shape typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ TensorCoord typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ TensorRef typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ ThreadMap typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+ UnderlyingIterator typedefcutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__a3c11cf1f00ef7a1efb8389ac6e4c6e0.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__a3c11cf1f00ef7a1efb8389ac6e4c6e0.html
new file mode 100644
index 0000000000000000000000000000000000000000..9df346780d487e89acb08801bb9f2b3ae1d755bd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileAccessIterator_3_01Shape___00_01Element__a3c11cf1f00ef7a1efb8389ac6e4c6e0.html
@@ -0,0 +1,568 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <regular_tile_access_iterator_tensor_op.h >
+
+
+
template<typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int Alignment, int Crosswise>
+class cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment >
+
+
Tile Iterator specialized for column-major crosswise TensorOp formats.
+
Satisfies: ForwardTileIteratorConcept | ReadableContiguousTileIteratorConcept | WriteableContiguousTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+ using cutlass::transform::threadblock::RegularTileAccessIterator < Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCrosswise < sizeof_bits < Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment >::UnderlyingIterator = RegularTileAccessIterator < layout::PitchLinearShape <Shape::kRow, Shape::kColumn>, Element , layout::TensorOpMultiplicandCrosswise <sizeof_bits <Element_>::value, Crosswise>, (kAdvanceRank == 0 ? 0 : 1), ThreadMap_>
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
Parameters
+
+ ref Pointer to start of tensor
+ thread_id ID of each participating thread
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment, int Crosswise>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_01a75d2cd74e722d6ad6a3b41aabfd432d.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_01a75d2cd74e722d6ad6a3b41aabfd432d.html
new file mode 100644
index 0000000000000000000000000000000000000000..849aad20a9ee4c66421ed84eea46577e03af2a7e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/classcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_01a75d2cd74e722d6ad6a3b41aabfd432d.html
@@ -0,0 +1,614 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::threadblock::RegularTileIterator< Shape_, Element_, layout::VoltaTensorOpMultiplicandBCongruous< sizeof_bits< Element_ >::value >, AdvanceRank, ThreadMap_, Alignment > Class Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <regular_tile_iterator_tensor_op_sm70.h >
+
+
+struct Detail
+ Internal details made public to facilitate introspection. More...
+
+
+
+
template<typename Shape_, typename Element_, int AdvanceRank, typename ThreadMap_, int Alignment>
+class cutlass::transform::threadblock::RegularTileIterator< Shape_, Element_, layout::VoltaTensorOpMultiplicandBCongruous< sizeof_bits< Element_ >::value >, AdvanceRank, ThreadMap_, Alignment >
+
+
Tile iterator specialized for congruous arrangements for TensorOps
+
Satisfies: ForwardTileIteratorConcept | ReadableContiguousTileIteratorConcept | WriteableContiguousTileIteratorConcept
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
Parameters
+
+ ref Pointer to start of tensor
+ thread_id ID of each participating thread
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment>
+
+
+
+
+
+
The documentation for this class was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/complex_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/complex_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..a27fb31753bebf12b265e7a54b3206b511bafeaf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/complex_8h.html
@@ -0,0 +1,277 @@
+
+
+
+
+
+
+CUTLASS: complex.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <cuComplex.h>
+
#include <cstdint>
+
#include "cutlass/cutlass.h "
+
#include "cutlass/half.h "
+
#include "cutlass/real.h "
+
#include <iosfwd>
+
+
Go to the source code of this file.
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/conversion__op_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/conversion__op_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..c7d446d7281f4e815aef0a88632f3aa34851231f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/conversion__op_8h__incl.md5
@@ -0,0 +1 @@
+68149105e4ee3f941f9f4c6644ad1e6e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__simt_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__simt_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..7b1ca00d20778c5218d65a0336eeb60e50076650
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__simt_8h__incl.md5
@@ -0,0 +1 @@
+d2287c7c613ed1a22af3e6cda1ebc3ef
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__wmma__tensor__op_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__wmma__tensor__op_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..e0cefcccc910be2d93afd65f514b91e3490adf15
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__epilogue__wmma__tensor__op_8h.html
@@ -0,0 +1,156 @@
+
+
+
+
+
+
+CUTLASS: default_epilogue_wmma_tensor_op.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Epilogue for threadblock scoped GEMMs using Tensor Ops.
+More...
+
+
Go to the source code of this file.
+
+
+
The epilogue rearranges the result of a matrix product through shared memory to match canonical tensor layouts in global memory. Epilogues support conversion and reduction operations.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..deb0a609875faea21deb1ac2ab312c747f60566d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__dep__incl.md5
@@ -0,0 +1 @@
+ff8ed2f3eab4876976f33e0f69a5978b
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..75abf3784fb21c1a3ff773976176ea0d234d928c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__configuration_8h__incl.md5
@@ -0,0 +1 @@
+f582e75284c2acc19887ebcaf50d875e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__splitk__parallel_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__splitk__parallel_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..ff9fd7022f80eef504ee17d3e511ad8c41ef60c4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__gemm__splitk__parallel_8h.html
@@ -0,0 +1,151 @@
+
+
+
+
+
+
+CUTLASS: default_gemm_splitk_parallel.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Default kernel-level GEMM definitions combine threadblock-scoped matrix multiply-add with the appropriate threadblock-scoped epilogue.
+More...
+
+
Go to the source code of this file.
+
+
+struct cutlass::gemm::kernel::DefaultGemmSplitKParallel< ElementA_, LayoutA_, kAlignmentA, ElementB_, LayoutB_, kAlignmentB, ElementC_, LayoutC_, ElementAccumulator, OperatorClass, ArchTag, ThreadblockShape, WarpShape, InstructionShape, EpilogueOutputOp, ThreadblockSwizzle, Stages, Operator >
+
+
+
+
Note, CUTLASS epilogues universally target row-major outputs. Column-major outputs are accommodated by exchanging A and B operands and assuming transposed layouts. Partial specializations here choose 'device::GemmTransposed' to implement this functionality.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..6536deb27903a6834a09cb7c3902022868470566
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma_8h.html
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+CUTLASS: default_mma.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Template for a pipelined GEMM kernel. Does not compute batching or support split-K.
+More...
+
+
Go to the source code of this file.
+
+
+struct cutlass::gemm::threadblock::DefaultMma< ElementA_, LayoutA_, kAlignmentA, ElementB_, LayoutB_, kAlignmentB, ElementAccumulator_, LayoutC_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, Stages, Operator, AccumulatorsInRowMajor >
+
+struct cutlass::gemm::threadblock::DefaultMma< ElementA, LayoutA, kAlignmentA, ElementB, LayoutB, kAlignmentB, ElementAccumulator, layout::RowMajor, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, InstructionShape, 2, Operator, false >
+ Specialization for row-major output (OperatorClass Simt) More...
+
+struct cutlass::gemm::threadblock::DefaultMma< ElementA, LayoutA, kAlignmentA, ElementB, LayoutB, kAlignmentB, ElementAccumulator, layout::RowMajor, arch::OpClassTensorOp, ArchTag, ThreadblockShape, WarpShape, InstructionShape, 2, Operator, false >
+ Specialization for row-major output (OperatorClass Simt) More...
+
+struct cutlass::gemm::threadblock::DefaultMma< ElementA, LayoutA, kAlignmentA, ElementB, LayoutB, kAlignmentB, ElementAccumulator, layout::ColumnMajorInterleaved< InterleavedK >, OperatorClass, ArchTag, ThreadblockShape, WarpShape, InstructionShape, 2, Operator, true >
+ Specialization for column-major-interleaved output. More...
+
+struct cutlass::gemm::threadblock::DefaultMma< int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementAccumulator, layout::RowMajor, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape< 1, 1, 4 >, 2, Operator, false >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__core__wmma_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__core__wmma_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..4524e6ba97b807fa23dd51b29ce03a0e1bc9a265
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__core__wmma_8h__incl.md5
@@ -0,0 +1 @@
+9b741cb3ec6b9fe82225cf103760fb94
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__tensor__op_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__tensor__op_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..b814ebb2c731e0a50105dc9ae153e7b136bf904b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__tensor__op_8h_source.html
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+CUTLASS: default_mma_tensor_op.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 44 typename InstructionShape_,
58 typename Operator_ = arch::OpMultiplyAdd,
63 bool AccumulatorsInRowMajor =
false ,
76 typename InstructionShape_,
95 bool AccumulatorsInRowMajor,
103 cutlass::layout::RowMajor, Operator_>,
108 WarpShape_, ElementA, LayoutA, ElementB, LayoutB, ElementC, LayoutC,
109 Policy , PartitionsK, AccumulatorsInRowMajor, PartitionsN>;
Describes the size of a matrix tile.
Definition: matrix_shape.h:42
+
Definition: aligned_buffer.h:35
+
Partial specialization for m-by-n-by-kgroup.
Definition: default_mma_tensor_op.h:67
+
Structure to compute the matrix product targeting CUDA cores and SIMT math instructions.
Definition: mma_tensor_op.h:82
+
Mapping function for column-major matrices.
Definition: layout/matrix.h:142
+
Policy.
Definition: mma_tensor_op_policy.h:48
+
Mapping function for row-major matrices.
Definition: layout/matrix.h:50
+
cutlass::gemm::warp::MmaTensorOpPolicy< cutlass::arch::Mma< InstructionShape_, 32, ElementA, cutlass::layout::RowMajor, ElementB, cutlass::layout::ColumnMajor, ElementC, cutlass::layout::RowMajor, Operator_ >, cutlass::MatrixShape< 1, 1 > > Policy
Definition: default_mma_tensor_op.h:104
+
Matrix multiply-add operation.
Definition: arch/mma.h:92
+
Templates implementing warp-level matrix multiply-accumulate operations targeting Tensor Cores...
+
Basic include for CUTLASS.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__wmma__tensor__op_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__wmma__tensor__op_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..0a3900d520488464537f6a659a8bf4687e5c9d83
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__mma__wmma__tensor__op_8h.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+CUTLASS: default_mma_wmma_tensor_op.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Default warp-level GEMM operators selected by data type, size, and layouts of operands.
+More...
+
+
Go to the source code of this file.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__thread__map__volta__tensor__op_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__thread__map__volta__tensor__op_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..860259ab7722aad3c5d92c189ee0a6aa08dd09e1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/default__thread__map__volta__tensor__op_8h__dep__incl.md5
@@ -0,0 +1 @@
+28589440300af4fa0f85256d89d9be23
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/device__memory_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/device__memory_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..43540aaaf44b7d89d19514a65a6b671f4f25cbeb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/device__memory_8h__incl.md5
@@ -0,0 +1 @@
+eaea6e8e2cfd800403a58eff2d52d126
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000001_000033.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000001_000033.html
new file mode 100644
index 0000000000000000000000000000000000000000..dc4922d55a2a7a3520a4f27da53828adc4d52cd8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000001_000033.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: cutlass -> platform Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
cutlass → platform Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000012_000010.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000012_000010.html
new file mode 100644
index 0000000000000000000000000000000000000000..6597eec78c3aa284f5c32f70fff8af11950f7610
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000012_000010.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: threadblock -> thread Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
threadblock → thread Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000025.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000025.html
new file mode 100644
index 0000000000000000000000000000000000000000..7587d9d67271d907bda848f40c0f89455fbac3bd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000025.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: gemm -> layout Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000032.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000032.html
new file mode 100644
index 0000000000000000000000000000000000000000..c336a01c5af1943aca160f7e2a0ef0f518332a8f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000013_000032.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: gemm -> transform Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gemm → transform Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000014_000025.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000014_000025.html
new file mode 100644
index 0000000000000000000000000000000000000000..45a46747cf7d1d5ceecbbc951eb23d8fbde5886e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000014_000025.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: kernel -> layout Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
kernel → layout Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000009.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000009.html
new file mode 100644
index 0000000000000000000000000000000000000000..69ebad11c55484d5e87334d95e367ab997a7accd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000009.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: device -> epilogue Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
device → epilogue Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000016.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000016.html
new file mode 100644
index 0000000000000000000000000000000000000000..1f440a8b9f286cdd11ea6bbfc0d0f34726907665
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_000015_000016.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+CUTLASS: device -> threadblock Relation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
device → threadblock Relation
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_048c1df36ab9c2efbb0733edba6291c9.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_048c1df36ab9c2efbb0733edba6291c9.html
new file mode 100644
index 0000000000000000000000000000000000000000..c24171a510ee7f1dfe59a9642855d341952a9b69
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_048c1df36ab9c2efbb0733edba6291c9.html
@@ -0,0 +1,171 @@
+
+
+
+
+
+
+CUTLASS: arch Directory Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_1315f14109599b6cf6873e0273f5d760_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_1315f14109599b6cf6873e0273f5d760_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..6c439bfbeb01394837c3f0923a7c09bc968067e1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_1315f14109599b6cf6873e0273f5d760_dep.md5
@@ -0,0 +1 @@
+a75246c917a5344809f79edf5178cb0a
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_36528dc2736efa40b421028b7309c671_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_36528dc2736efa40b421028b7309c671_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..00f193e8d160179ae56e5fe38dbfb269419c30a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_36528dc2736efa40b421028b7309c671_dep.md5
@@ -0,0 +1 @@
+533c199178041f9857f4f58fde927dfe
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_58e788c69476ee3a6457c1bb0aea7b40_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_58e788c69476ee3a6457c1bb0aea7b40_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..81d12cde56c910b6b8b71d55910bcc1d5c0d6d30
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_58e788c69476ee3a6457c1bb0aea7b40_dep.md5
@@ -0,0 +1 @@
+40afe0a166cced15b02409a058c3f0e9
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_7a8f757b2dc0884f3cac82bc42925c19_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_7a8f757b2dc0884f3cac82bc42925c19_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..f9e2eb1ed31de5fd09b2c7aaa7ebf2940d2d3d8d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_7a8f757b2dc0884f3cac82bc42925c19_dep.md5
@@ -0,0 +1 @@
+745ef7744ca489da21ed7691faa0212c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_c4a2560cb67fbf4e24d3d775f040b990_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_c4a2560cb67fbf4e24d3d775f040b990_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..cfe1c8ee52a4ae26260317aafe79138ccf79e05e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_c4a2560cb67fbf4e24d3d775f040b990_dep.md5
@@ -0,0 +1 @@
+967b903efe8e35a1abf88512737004c9
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_e972dae4cc8aee063a6567ed2b9b6a51_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_e972dae4cc8aee063a6567ed2b9b6a51_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..72258663accb70ee8da8b46e209f27748b37f1d5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_e972dae4cc8aee063a6567ed2b9b6a51_dep.md5
@@ -0,0 +1 @@
+ed9638dbd77585a13721350e425fc40b
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ed1948a6da781e7f72c597b5619a522d.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ed1948a6da781e7f72c597b5619a522d.html
new file mode 100644
index 0000000000000000000000000000000000000000..f57f7a0e6c0e948d17fcebcd1bb3e5e568b1d11a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ed1948a6da781e7f72c597b5619a522d.html
@@ -0,0 +1,123 @@
+
+
+
+
+
+
+CUTLASS: thread Directory Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+file thread/matrix.h [code]
+ Defines a matrix object intended for storing data in registers and operations within a CUDA thread.
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ff60863f958a43c892071bb1f8a4c81a_dep.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ff60863f958a43c892071bb1f8a4c81a_dep.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a515cbd54ee0338e94893a5841d1219b0072d4c5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/dir_ff60863f958a43c892071bb1f8a4c81a_dep.md5
@@ -0,0 +1 @@
+f17150f5a7012e6c5710a619c258d3df
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/distribution_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/distribution_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ab0b066bd9cb969d59ec015828f648cdf4a3c0b2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/distribution_8h__dep__incl.md5
@@ -0,0 +1 @@
+ca63af360bef83340b07f5a01b606380
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__base_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__base_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..24c1b74ef0410d34fc176f548c440c347ded6699
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__base_8h.html
@@ -0,0 +1,163 @@
+
+
+
+
+
+
+CUTLASS: epilogue_base.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Epilogue for threadblock scoped GEMMs using Tensor Ops.
+More...
+
+
Go to the source code of this file.
+
+
+class cutlass::epilogue::threadblock::EpilogueBase< Shape_, WarpMmaOperator_, PartitionsK, AccumulatorFragmentIterator_, WarpTileIterator_, Padding_ >
+ Base class for epilogues defining warp-level. More...
+
+struct cutlass::epilogue::threadblock::EpilogueBase< Shape_, WarpMmaOperator_, PartitionsK, AccumulatorFragmentIterator_, WarpTileIterator_, Padding_ >::SharedStorage
+ Shared storage allocation needed by the epilogue. More...
+
+
+
+
The epilogue rearranges the result of a matrix product through shared memory to match canonical tensor layouts in global memory. Epilogues support conversion and reduction operations.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__workspace_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__workspace_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..7f4407d2e87781cf48a3e9a857b95377541c2380
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/epilogue__workspace_8h_source.html
@@ -0,0 +1,140 @@
+
+
+
+
+
+
+CUTLASS: epilogue_workspace.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 69 using ElementC =
typename FragmentC::value_type;
87 !(FragmentC::kElements % kElementsPerAccess),
88 "The number of accumulators must be divisible by the access size." );
118 ptr_C(ptr_C), stride_n(stride_n_ / kElementsPerAccess), stride_k(stride_k_ / kElementsPerAccess) {
130 struct alignas ((kAccessSizeInBits / 8)) AccessType {
131 Array<ElementC, kElementsPerAccess> storage;
135 AccessType *pointer_;
154 pointer_(reinterpret_cast<AccessType *>(params.
ptr_C )),
170 AccessType *pointer = pointer_ +
171 tb_tile_coord.
m () * kThreadblockAccesses +
172 tb_tile_coord.
n () * stride_n_ +
173 tb_tile_coord.
k () * stride_k_;
176 AccessType
const * src_pointer =
reinterpret_cast< AccessType
const *
> (&accum);
Definition: aligned_buffer.h:35
+
Shared storage allocation needed by the epilogue.
Definition: epilogue_workspace.h:124
+
static int const kAccessSizeInBits
Optimize for 128b accesses.
Definition: epilogue_workspace.h:74
+
Definition: include/cutlass/gemm/gemm.h:94
+
static int const kWarpAccesses
Total number of vectorized accesses in warp (in units of vector)
Definition: epilogue_workspace.h:91
+
CUTLASS_HOST_DEVICE Params(ElementC *ptr_C, int stride_n_, int stride_k_)
Definition: epilogue_workspace.h:113
+
CUTLASS_HOST_DEVICE Index const & n() const
Returns the GEMM N coordinate.
Definition: include/cutlass/gemm/gemm.h:137
+
static int const kIterations
Number of stores per thread.
Definition: epilogue_workspace.h:84
+
CUTLASS_DEVICE void operator()(cutlass::gemm::GemmCoord problem_size, cutlass::gemm::GemmCoord tb_tile_coord, FragmentC const &accum)
Streams the result to global memory.
Definition: epilogue_workspace.h:164
+
Shape_ Shape
Definition: epilogue_workspace.h:67
+
CUTLASS_HOST_DEVICE Index const & k() const
Returns the GEMM K coordinate.
Definition: include/cutlass/gemm/gemm.h:145
+
typename FragmentC::value_type ElementC
Definition: epilogue_workspace.h:69
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
Defines the size of an element in bits.
Definition: numeric_types.h:42
+
ElementC * ptr_C
Pointer to C matrix.
Definition: epilogue_workspace.h:100
+
FragmentC_ FragmentC
Definition: epilogue_workspace.h:68
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
CUTLASS_DEVICE EpilogueWorkspace(Params const ¶ms, SharedStorage &, int warp_idx, int lane_idx)
Constructor.
Definition: epilogue_workspace.h:147
+
+
static int const kWarpCount
Definition: epilogue_workspace.h:71
+
int stride_n
Stride between tiles along the GEMM N dimension (in units of vectors)
Definition: epilogue_workspace.h:103
+
static int const kElementsPerAccess
Vector length of accesses.
Definition: epilogue_workspace.h:80
+
CUTLASS_HOST_DEVICE Index const & m() const
Returns the GEMM M coordinate.
Definition: include/cutlass/gemm/gemm.h:129
+
int stride_k
Stride between tiles along the GEMM K dimension (in units of vectors)
Definition: epilogue_workspace.h:106
+
Parameters structure.
Definition: epilogue_workspace.h:97
+
Definition: epilogue_workspace.h:64
+
Basic include for CUTLASS.
+
static int const kWarpSize
Warp size from the perspective of memory operations.
Definition: epilogue_workspace.h:77
+
static int const kThreadblockAccesses
Total number of vectorized accesses in threadblock tile (in units of vector)
Definition: epilogue_workspace.h:94
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/exceptions_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/exceptions_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..beb74baf1fec280999f006a20a866f38bb702e53
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/exceptions_8h.html
@@ -0,0 +1,157 @@
+
+
+
+
+
+
+CUTLASS: exceptions.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
C++ exception semantics for CUDA error codes.
+More...
+
#include <cuda_runtime.h>
+
#include <iosfwd>
+
#include <stdexcept>
+
#include "cutlass/platform/platform.h "
+
+
Go to the source code of this file.
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__complex__tensor__op_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__complex__tensor__op_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2fee76d1ad297a0bc1fc417eec34638b81fded2d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__complex__tensor__op_8h__incl.md5
@@ -0,0 +1 @@
+0a89d12db8963953f11fefd433e5b5c3
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__tensor__op_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__tensor__op_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..915d2b9cfcce3a38995249f4eba454dd39d66eb4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/fragment__iterator__tensor__op_8h__dep__incl.md5
@@ -0,0 +1 @@
+1f725aae1b0bafb4bb2368210e38db49
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_func_g.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_func_g.html
new file mode 100644
index 0000000000000000000000000000000000000000..3916a8ab927f252a73167de256e4b00132927fb4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_func_g.html
@@ -0,0 +1,315 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Functions
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- g -
+Gemm()
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+, cutlass::reference::device::thread::Gemm< TensorRefA, TensorRefB, TensorRefC, ScalarType, AccumulatorType, OutputTile, InnerProductOp, ConvertOp >
+
+GemmBatched()
+: cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >
+
+GemmComplex()
+: cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+
+GemmCoord()
+: cutlass::gemm::GemmCoord
+
+GemmDescription()
+: cutlass::library::GemmDescription
+
+GemmHorizontalThreadblockSwizzle()
+: cutlass::gemm::threadblock::GemmHorizontalThreadblockSwizzle
+
+GemmIdentityThreadblockSwizzle()
+: cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle
+
+GemmSplitKParallel()
+: cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >
+
+Gemv()
+: cutlass::gemm::threadblock::Gemv< Core_ >
+
+GemvBatchedStridedEpilogueScaling()
+: cutlass::gemm::kernel::detail::GemvBatchedStridedEpilogueScaling< ElementAlphaBeta, BetaIsZero >
+
+GeneralMatrix()
+: cutlass::layout::GeneralMatrix
+
+get()
+: cutlass::Array< T, N, false >::const_reference
+, cutlass::Array< T, N, false >::reference
+, cutlass::ConstSubbyteReference< Element_, Storage_ >
+, cutlass::device_memory::allocation< T >
+, cutlass::platform::unique_ptr< T, Deleter >
+, cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::ConstIterator
+, cutlass::PredicateVector< kPredicates_, kPredicatesPerByte_, kPredicateStart_ >::Iterator
+, cutlass::ReferenceFactory< Element, false >
+, cutlass::ReferenceFactory< Element, true >
+, cutlass::SubbyteReference< Element_, Storage_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::ColumnMajorTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::RowMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::RowMajorTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::TensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >
+, cutlass::transform::threadblock::RegularTileAccessIterator< Shape_, Element_, layout::TensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, Crosswise >, AdvanceRank, ThreadMap_, Alignment >
+
+get_batch_idx()
+: cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemvBatchedStridedThreadblockDefaultSwizzle
+
+get_batch_tile_idx()
+: cutlass::gemm::threadblock::GemvBatchedStridedThreadblockDefaultSwizzle
+
+get_cmd_line_argument()
+: cutlass::CommandLine
+
+get_cmd_line_argument_pairs()
+: cutlass::CommandLine
+
+get_cmd_line_argument_ranges()
+: cutlass::CommandLine
+
+get_cmd_line_arguments()
+: cutlass::CommandLine
+
+get_deleter()
+: cutlass::device_memory::allocation< T >
+, cutlass::platform::unique_ptr< T, Deleter >
+
+get_device_workspace_size()
+: cutlass::library::Operation
+
+get_grid_layout()
+: cutlass::reduction::DefaultBlockSwizzle
+
+get_grid_shape()
+: cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemvBatchedStridedThreadblockDefaultSwizzle
+
+get_host_workspace_size()
+: cutlass::library::Operation
+
+get_lane_layout()
+: cutlass::gemm::warp::MmaSimtPolicy< WarpShape_, LaneLayout_, LaneMmaShape_ >
+
+get_mask()
+: cutlass::epilogue::threadblock::InterleavedPredicatedTileIterator< ThreadMap_, Element_, InterleavedK >
+, cutlass::epilogue::threadblock::PredicatedTileIterator< ThreadMap_, Element_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator2dThreadTile< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessType_ >
+, cutlass::transform::threadblock::PredicatedTileIterator2dThreadTile< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, Transpose_ >
+, cutlass::transform::threadblock::PredicatedTileIterator2dThreadTile< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, Transpose_ >
+, cutlass::transform::threadblock::PredicatedTileIterator2dThreadTile< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, Transpose_ >
+, cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessSize >
+, cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::ColumnMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+, cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessSize >
+, cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessSize >
+, cutlass::transform::threadblock::PredicatedTileIterator< Shape_, Element_, layout::RowMajorInterleaved< InterleavedK >, AdvanceRank, ThreadMap_, AccessSize >
+
+get_state()
+: cutlass::Semaphore
+
+get_threadblock_offset()
+: cutlass::reduction::DefaultBlockSwizzle
+
+get_tile_offset()
+: cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemvBatchedStridedThreadblockDefaultSwizzle
+
+get_tiled_shape()
+: cutlass::gemm::threadblock::GemmBatchedIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKHorizontalThreadblockSwizzle
+, cutlass::gemm::threadblock::GemmSplitKIdentityThreadblockSwizzle
+, cutlass::gemm::threadblock::GemvBatchedStridedThreadblockDefaultSwizzle
+
+get_workspace_size()
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+
+good()
+: cutlass::TensorRef< Element_, Layout_ >
+
+grid_shape()
+: cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_h.html
new file mode 100644
index 0000000000000000000000000000000000000000..43d14199cad952ff8bdb91b8d75cfcafae07f8e3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_h.html
@@ -0,0 +1,197 @@
+
+
+
+
+
+
+CUTLASS: Class Members
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Here is a list of all class members with links to the classes they belong to:
+
+
- h -
+h()
+: cutlass::Tensor4DCoord
+
+half_t()
+: cutlass::half_t
+
+has_denorm
+: std::numeric_limits< cutlass::half_t >
+
+has_denorm_loss
+: std::numeric_limits< cutlass::half_t >
+
+has_infinity
+: std::numeric_limits< cutlass::half_t >
+
+has_quiet_NaN
+: std::numeric_limits< cutlass::half_t >
+
+has_signaling_NaN
+: std::numeric_limits< cutlass::half_t >
+
+host_data()
+: cutlass::HostTensor< Element_, Layout_ >
+
+host_data_ptr_offset()
+: cutlass::HostTensor< Element_, Layout_ >
+
+host_ref()
+: cutlass::HostTensor< Element_, Layout_ >
+
+host_type
+: cutlass::TypeTraits< T >
+, cutlass::TypeTraits< complex< double > >
+, cutlass::TypeTraits< complex< float > >
+, cutlass::TypeTraits< complex< half > >
+, cutlass::TypeTraits< complex< half_t > >
+, cutlass::TypeTraits< double >
+, cutlass::TypeTraits< float >
+, cutlass::TypeTraits< half_t >
+, cutlass::TypeTraits< int >
+, cutlass::TypeTraits< int64_t >
+, cutlass::TypeTraits< int8_t >
+, cutlass::TypeTraits< uint64_t >
+, cutlass::TypeTraits< uint8_t >
+, cutlass::TypeTraits< unsigned >
+
+host_view()
+: cutlass::HostTensor< Element_, Layout_ >
+
+HostTensor()
+: cutlass::HostTensor< Element_, Layout_ >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_o.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_o.html
new file mode 100644
index 0000000000000000000000000000000000000000..a99ec6d98e5db2d1f980ee7c7a1c1c7936b3bdef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_o.html
@@ -0,0 +1,343 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Typedefs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- o -
+OpDelta
+: cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator< Shape_, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_ >
+, cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator< Shape_, Element_, cutlass::layout::ColumnMajorInterleaved< InterleavedN >, InstructionShape_, OpDelta_ >
+, cutlass::gemm::warp::MmaTensorOpAccumulatorTileIterator< Shape_, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_ >
+, cutlass::gemm::warp::MmaTensorOpPolicy< Operator_, OpDelta_ >
+, cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >
+
+Operator
+: cutlass::arch::Mma< gemm::GemmShape< 16, 8, 8 >, 32, half_t, layout::RowMajor, half_t, layout::ColumnMajor, float, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 16, 8, 8 >, 32, half_t, layout::RowMajor, half_t, layout::ColumnMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 128 >, 32, uint1b_t, layout::RowMajor, uint1b_t, layout::ColumnMajor, int, layout::RowMajor, OpXorPopc >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, uint8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, uint8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, uint8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, uint8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, uint4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, uint4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, uint4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, uint4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAddSaturate >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::ColumnMajor, float, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::ColumnMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, float, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::RowMajor, half_t, layout::ColumnMajor, float, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::RowMajor, half_t, layout::ColumnMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::RowMajor, half_t, layout::RowMajor, float, layout::RowMajor, OpMultiplyAdd >
+, cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::RowMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+, cutlass::epilogue::thread::ReductionOpPlus< Element_, Count >
+, cutlass::epilogue::threadblock::DirectEpilogueTensorOp< Shape_, Operator_, PartitionsK, Element_, OutputOp_, ConvertOp_ >
+, cutlass::epilogue::warp::FragmentIteratorSimt< WarpShape_, Operator_, layout::RowMajor, MmaSimtPolicy_ >
+, cutlass::epilogue::warp::SimtPolicy< WarpShape_, Operator_, layout::RowMajor, MmaSimtPolicy_ >
+, cutlass::epilogue::warp::TileIteratorSimt< WarpShape_, Operator_, Element_, layout::RowMajor, MmaSimtPolicy_ >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassSimt, ArchTag, ElementA, ElementB, ElementC, ElementAccumulator >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassSimt, ArchTag, int8_t, int8_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm70, ElementA, ElementB, ElementC, ElementAccumulator >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, ElementA, ElementB, ElementC, ElementAccumulator >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, int4b_t, int4b_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, int4b_t, uint4b_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, int8_t, int8_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, int8_t, uint8_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint4b_t, int4b_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint4b_t, uint4b_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint8_t, int8_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint8_t, uint8_t, ElementC, int32_t >
+, cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassWmmaTensorOp, ArchTag, ElementA, ElementB, ElementC, ElementAccumulator >
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::thread::Mma< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, arch::OpMultiplyAdd, bool >
+, cutlass::gemm::thread::Mma< Shape_, half_t, LayoutA, half_t, LayoutB, half_t, LayoutC, arch::OpMultiplyAdd >
+, cutlass::gemm::thread::Mma< Shape_, half_t, LayoutA_, half_t, LayoutB_, half_t, layout::RowMajor, arch::OpMultiplyAdd, typename platform::enable_if< detail::EnableMma_Crow_SM60< LayoutA_, LayoutB_ >::value >::type >
+, cutlass::gemm::thread::Mma< Shape_, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, int32_t, LayoutC_, arch::OpMultiplyAdd, int8_t >
+, cutlass::gemm::thread::Mma< Shape_, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int32_t, LayoutC_, arch::OpMultiplyAdd, bool >
+, cutlass::gemm::thread::MmaGeneric< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, Operator_ >
+, cutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajorInterleaved< InterleavedK >, ElementB_, layout::RowMajorInterleaved< InterleavedK >, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_, AccumulatorsInRowMajor >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::Gemv< Core_ >
+, cutlass::gemm::threadblock::MmaBase< Shape_, Policy_, Stages, Enable >
+, cutlass::gemm::threadblock::MmaPipelined< Shape_, IteratorA_, SmemIteratorA_, IteratorB_, SmemIteratorB_, ElementC_, LayoutC_, Policy_, TransformA_, TransformB_, Enable >
+, cutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK >
+, cutlass::gemm::threadblock::MmaSingleStage< Shape_, IteratorA_, SmemIteratorA_, IteratorB_, SmemIteratorB_, ElementC_, LayoutC_, Policy_, Enable >
+, cutlass::gemm::warp::MmaTensorOpPolicy< Operator_, OpDelta_ >
+
+OperatorClass
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::kernel::DefaultGemm< int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape< 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >
+, cutlass::gemm::threadblock::DefaultMma< int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementAccumulator, layout::RowMajor, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape< 1, 1, 4 >, 2, Operator, false >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_, >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajorInterleaved< InterleavedK >, ElementB_, layout::RowMajorInterleaved< InterleavedK >, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_, AccumulatorsInRowMajor >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+, cutlass::gemm::warp::MmaComplexTensorOp< Shape_, complex< RealElementA >, LayoutA_, complex< RealElementB >, LayoutB_, complex< RealElementC >, LayoutC_, Policy_, TransformA, TransformB, Enable >
+, cutlass::gemm::warp::MmaSimt< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, Policy_, PartitionsK, Enable >
+, cutlass::gemm::warp::MmaTensorOp< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, Policy_, PartitionsK_, AccumulatorsInRowMajor, PartitionsN_, Enable >
+, cutlass::gemm::warp::MmaVoltaTensorOp< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, Policy_, Enable >
+
+OperatorCount
+: cutlass::epilogue::warp::TensorOpPolicy< WarpShape, OperatorShape, layout::ColumnMajorInterleaved< InterleavedK > >
+, cutlass::epilogue::warp::TensorOpPolicy< WarpShape, OperatorShape, layout::RowMajor >
+
+OperatorElementC
+: cutlass::epilogue::warp::FragmentIteratorComplexTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+
+OperatorFragment
+: cutlass::epilogue::warp::TileIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorFragment_, layout::RowMajor >
+
+OperatorFragmentC
+: cutlass::epilogue::warp::FragmentIteratorComplexTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+
+OperatorShape
+: cutlass::epilogue::warp::FragmentIteratorComplexTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::ColumnMajorInterleaved< InterleavedK > >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::TileIteratorTensorOp< WarpShape_, OperatorShape_, Element_, layout::RowMajor >
+, cutlass::epilogue::warp::TileIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorFragment_, layout::RowMajor >
+
+OutputAccessType
+: cutlass::epilogue::threadblock::Epilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, WarpTileIterator_, SharedLoadIterator_, OutputOp_, Padding_ >
+, cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+
+OutputAccumulatorTile
+: cutlass::epilogue::warp::FragmentIteratorComplexTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorSimt< WarpShape_, Operator_, layout::RowMajor, MmaSimtPolicy_ >
+, cutlass::epilogue::warp::FragmentIteratorTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, half_t, layout::RowMajor >
+, cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp< WarpShape_, OperatorShape_, OperatorElementC_, OperatorFragmentC_, layout::RowMajor >
+
+OutputOp
+: cutlass::epilogue::threadblock::DefaultEpilogueComplexTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueVoltaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueWmmaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+, cutlass::epilogue::threadblock::DirectEpilogueTensorOp< Shape_, Operator_, PartitionsK, Element_, OutputOp_, ConvertOp_ >
+, cutlass::epilogue::threadblock::Epilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, WarpTileIterator_, SharedLoadIterator_, OutputOp_, Padding_ >
+, cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >
+, cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >
+
+OutputTensorRef
+: cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >
+
+OutputTile
+: cutlass::reduction::BatchedReductionTraits< ScalarA_, ScalarC_, ScalarD_, ScalarAlphaBeta_, ScalarAccum_, ReductionSize_, OutputTile_, SubTile_, ThreadShape_, Index_, BlockSwizzle_, maxInReg_, maxOutReg_, Functor_ >
+
+OutputTileIterator
+: cutlass::epilogue::threadblock::DefaultEpilogueComplexTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueVoltaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueWmmaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+, cutlass::epilogue::threadblock::Epilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, WarpTileIterator_, SharedLoadIterator_, OutputOp_, Padding_ >
+, cutlass::epilogue::threadblock::InterleavedEpilogue< Shape_, WarpMmaOperator_, PartitionsK, OutputTileIterator_, AccumulatorFragmentIterator_, OutputOp_, InterleavedK, IsBetaZero >
+
+OutputTileThreadMap
+: cutlass::epilogue::threadblock::DefaultEpilogueComplexTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueVoltaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultEpilogueWmmaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >
+, cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_r.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_r.html
new file mode 100644
index 0000000000000000000000000000000000000000..f100ddadddba9dbba7c6566431e369db3a732ac0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_type_r.html
@@ -0,0 +1,187 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Typedefs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- r -
+RandomFunc
+: cutlass::reference::device::detail::TensorFillRandomGaussianFunc< Element, Layout >
+, cutlass::reference::device::detail::TensorFillRandomUniformFunc< Element, Layout >
+
+Real
+: cutlass::reference::host::detail::RandomUniformFunc< Element >
+, cutlass::reference::host::detail::RandomUniformFunc< complex< Element > >
+
+ReductionKernel
+: cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+
+ReductionOp
+: cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >
+, cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >
+
+reference
+: cutlass::AlignedBuffer< T, N, Align >
+, cutlass::Array< T, N, true >
+
+Reference
+: cutlass::HostTensor< Element_, Layout_ >
+, cutlass::TensorRef< Element_, Layout_ >
+, cutlass::TensorView< Element_, Layout_ >
+, cutlass::thread::Matrix< Element, Rows, Columns, Layout >
+
+result_type
+: cutlass::NumericArrayConverter< T, S, N, Round >
+, cutlass::NumericArrayConverter< float, half_t, 2, Round >
+, cutlass::NumericArrayConverter< float, half_t, N, Round >
+, cutlass::NumericArrayConverter< half_t, float, 2, FloatRoundStyle::round_to_nearest >
+, cutlass::NumericArrayConverter< half_t, float, N, Round >
+, cutlass::NumericConverter< T, S, Round >
+, cutlass::NumericConverter< float, half_t, Round >
+, cutlass::NumericConverter< half_t, float, FloatRoundStyle::round_to_nearest >
+, cutlass::NumericConverter< half_t, float, FloatRoundStyle::round_toward_zero >
+, cutlass::NumericConverter< int8_t, float, Round >
+, cutlass::NumericConverter< T, T, Round >
+, cutlass::NumericConverterClamp< T, S >
+
+RowArrangement
+: cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_c.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_c.html
new file mode 100644
index 0000000000000000000000000000000000000000..6dc37083486ae9f9e008f2238334ec70afb0b0ef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_c.html
@@ -0,0 +1,176 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Variables
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- c -
+C
+: cutlass::library::GemmArguments
+, cutlass::library::GemmArrayArguments
+, cutlass::library::GemmDescription
+
+capacity
+: cutlass::device_memory::allocation< T >
+
+contains
+: cutlass::reference::host::detail::TensorContainsFunc< Element, Layout >
+
+convert
+: cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::reference::host::detail::TensorCopyIf< DstElement, DstLayout, SrcElement, SrcLayout, F >
+
+convert_op
+: cutlass::epilogue::threadblock::DirectEpilogueTensorOp< Shape_, Operator_, PartitionsK, Element_, OutputOp_, ConvertOp_ >::Params
+
+cublas_type
+: cutlass::TypeTraits< complex< double > >
+, cutlass::TypeTraits< complex< float > >
+, cutlass::TypeTraits< complex< half > >
+, cutlass::TypeTraits< complex< half_t > >
+, cutlass::TypeTraits< double >
+, cutlass::TypeTraits< float >
+, cutlass::TypeTraits< half_t >
+, cutlass::TypeTraits< int >
+, cutlass::TypeTraits< int64_t >
+, cutlass::TypeTraits< int8_t >
+, cutlass::TypeTraits< uint64_t >
+, cutlass::TypeTraits< uint8_t >
+, cutlass::TypeTraits< unsigned >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_n.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_n.html
new file mode 100644
index 0000000000000000000000000000000000000000..9269b2594917a5119badd72920f059ffb81ccc59
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_n.html
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Variables
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- n -
+name
+: cutlass::library::OperationDescription
+
+numElementsA
+: cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+
+numElementsB
+: cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 1 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+, cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::RowMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_o.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_o.html
new file mode 100644
index 0000000000000000000000000000000000000000..c998fa9eb74368561f032f32b46de841ed316844
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_o.html
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Variables
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- o -
+opcode_class
+: cutlass::library::MathInstructionDescription
+
+operand_A
+: cutlass::gemm::threadblock::MmaBase< Shape_, Policy_, Stages, Enable >::SharedStorage
+
+operand_B
+: cutlass::gemm::threadblock::MmaBase< Shape_, Policy_, Stages, Enable >::SharedStorage
+
+other
+: cutlass::reference::device::detail::TensorFillDiagonalFunc< Element, Layout >::Params
+, cutlass::reference::device::detail::TensorUpdateOffDiagonalFunc< Element, Layout >::Params
+, cutlass::reference::host::detail::TensorFillDiagonalFunc< Element, Layout >
+, cutlass::reference::host::detail::TensorUpdateOffDiagonalFunc< Element, Layout >
+
+output
+: cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >::Params
+
+output_op
+: cutlass::epilogue::threadblock::DirectEpilogueTensorOp< Shape_, Operator_, PartitionsK, Element_, OutputOp_, ConvertOp_ >::Params
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >::Params
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_r.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_r.html
new file mode 100644
index 0000000000000000000000000000000000000000..8cc684715bb72e7582d76a0a121720b34b9bbaa0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/functions_vars_r.html
@@ -0,0 +1,249 @@
+
+
+
+
+
+
+CUTLASS: Class Members - Variables
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- r -
+random
+: cutlass::reference::device::detail::TensorFillRandomGaussianFunc< Element, Layout >::Params
+, cutlass::reference::device::detail::TensorFillRandomGaussianFunc< Element, Layout >
+, cutlass::reference::device::detail::TensorFillRandomUniformFunc< Element, Layout >::Params
+, cutlass::reference::device::detail::TensorFillRandomUniformFunc< Element, Layout >
+
+range
+: cutlass::reference::device::detail::RandomUniformFunc< Element >::Params
+, cutlass::reference::host::detail::RandomUniformFunc< Element >
+, cutlass::reference::host::detail::RandomUniformFunc< complex< Element > >
+
+real
+: cutlass::TypeTraits< complex< double > >::integer_type
+, cutlass::TypeTraits< complex< double > >::unsigned_type
+
+reduction
+: cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >::Params
+
+reduction_stride
+: cutlass::reduction::BatchedReductionTraits< ScalarA_, ScalarC_, ScalarD_, ScalarAlphaBeta_, ScalarAccum_, ReductionSize_, OutputTile_, SubTile_, ThreadShape_, Index_, BlockSwizzle_, maxInReg_, maxOutReg_, Functor_ >::Params
+
+ReductionSize
+: cutlass::reduction::BatchedReductionTraits< ScalarA_, ScalarC_, ScalarD_, ScalarAlphaBeta_, ScalarAccum_, ReductionSize_, OutputTile_, SubTile_, ThreadShape_, Index_, BlockSwizzle_, maxInReg_, maxOutReg_, Functor_ >
+
+ref_A
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >::Params
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+ref_a
+: cutlass::reference::host::detail::TensorFuncBinaryOp< ElementA, LayoutA, ElementB, LayoutB, ElementD, LayoutD, BinaryFunc >
+
+ref_B
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >::Params
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+ref_b
+: cutlass::reference::host::detail::TensorFuncBinaryOp< ElementA, LayoutA, ElementB, LayoutB, ElementD, LayoutD, BinaryFunc >
+
+ref_C
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >::Params
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+ref_D
+: cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::Gemm< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, SplitKSerial, Operator_, IsBetaZero >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmBatched< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, AlignmentA, AlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmComplex< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ThreadblockSwizzle_, Stages, TransformA, TransformB, SplitKSerial >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::device::GemmSplitKParallel< ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, layout::ColumnMajor, ElementAccumulator_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, EpilogueOutputOp_, ConvertScaledOp_, ReductionOp_, ThreadblockSwizzle_, Stages, kAlignmentA, kAlignmentB, Operator_ >::Arguments
+, cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >::Params
+, cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+, cutlass::gemm::kernel::GemmSplitKParallel< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+result
+: cutlass::reference::host::detail::TensorEqualsFunc< Element, Layout >
+
+rhs
+: cutlass::reference::host::detail::TensorEqualsFunc< Element, Layout >
+
+rng_state
+: cutlass::reference::device::detail::RandomGaussianFunc< Element >
+, cutlass::reference::device::detail::RandomUniformFunc< Element >
+
+round_style
+: cutlass::NumericArrayConverter< T, S, N, Round >
+, cutlass::NumericArrayConverter< float, half_t, 2, Round >
+, cutlass::NumericArrayConverter< float, half_t, N, Round >
+, cutlass::NumericArrayConverter< half_t, float, 2, FloatRoundStyle::round_to_nearest >
+, cutlass::NumericArrayConverter< half_t, float, N, Round >
+, cutlass::NumericConverter< T, S, Round >
+, cutlass::NumericConverter< float, half_t, Round >
+, cutlass::NumericConverter< half_t, float, FloatRoundStyle::round_to_nearest >
+, cutlass::NumericConverter< half_t, float, FloatRoundStyle::round_toward_zero >
+, cutlass::NumericConverter< int8_t, float, Round >
+, cutlass::NumericConverter< T, T, Round >
+, std::numeric_limits< cutlass::half_t >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm50_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm50_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..63e40ec0b1f9a6d97a7aefd87238e0d1bd122b43
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm50_8h__dep__incl.md5
@@ -0,0 +1 @@
+9e7182cd0ca2a441ac60383a4d56b04b
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..0505be33494aa9365837eb808e1f70510217a76a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h__dep__incl.md5
@@ -0,0 +1 @@
+9d4f3ae18e5c1675caf7f1abbe230457
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..856e127936296f31ff3e7fc16517b879f9dc205a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2thread_2mma__sm61_8h_source.html
@@ -0,0 +1,145 @@
+
+
+
+
+
+
+CUTLASS: mma_sm61.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 109 reinterpret_cast<ElementC *>(&D), LayoutC::packed({ Shape::kM, Shape::kN }));
124 arch::OpMultiplyAdd>;
130 for (
int k = 0; k < Shape::kK / Mma::Shape::kK; ++k) {
133 for (
int n = 0; n < Shape::kN; ++n) {
136 for (
int m = 0; m < Shape::kM; ++m) {
139 Array<int8_t, 4>
const *ptr_A =
reinterpret_cast< Array<int8_t, 4>
const *
> (&A);
140 Array<int8_t, 4>
const *ptr_B =
reinterpret_cast< Array<int8_t, 4>
const *
> (&B);
142 Array<int32_t, 1> tmp =
reinterpret_cast< Array<int32_t, 1> &
> (d.
at (mn));
146 ptr_A[m * Shape::kK / Mma::Shape::kK + k],
147 ptr_B[n * Shape::kK / Mma::Shape::kK + k],
150 d.
at (mn) =
reinterpret_cast< int32_t &
> (tmp);
222 reinterpret_cast<ElementC *>(&D), LayoutC::packed({ Shape::kM, Shape::kN }));
237 arch::OpMultiplyAdd>;
240 Array<int8_t, 4>
const *ptr_A =
reinterpret_cast< Array<int8_t, 4>
const *
> (&A);
241 Array<int8_t, 4>
const *ptr_B =
reinterpret_cast< Array<int8_t, 4>
const *
> (&B);
245 for (
int k = 0; k < Shape::kK / Mma::Shape::kK; ++k) {
248 for (
int n = 0; n < Shape::kN; ++n) {
251 for (
int m = 0; m < Shape::kM; ++m) {
254 Array<int32_t, 1> tmp =
reinterpret_cast< Array<int32_t, 1> &
> (d.
at (mn));
258 ptr_A[m + k * Shape::kM],
259 ptr_B[n + k * Shape::kN],
262 d.
at (mn) =
reinterpret_cast< int32_t &
> (tmp);
Definition: aligned_buffer.h:35
+
Defines a structure containing strides, bounds, and a pointer to tensor data.
+
CUTLASS_HOST_DEVICE void operator()(FragmentC &D, FragmentA const &A, FragmentB const &B, FragmentC const &C)
Computes a matrix product D = A * B + C.
Definition: gemm/thread/mma_sm61.h:102
+
Array< ElementB, Shape::kKN > FragmentB
B operand storage.
Definition: gemm/thread/mma_sm61.h:204
+
Shape_ Shape
Size of the Gemm problem - concept: gemm::GemmShape<>
Definition: gemm/thread/mma_sm61.h:64
+
CUTLASS_HOST_DEVICE void operator()(FragmentC &D, FragmentA const &A, FragmentB const &B, FragmentC const &C)
Computes a matrix product D = A * B + C.
Definition: gemm/thread/mma_sm61.h:215
+
arch::OpMultiplyAdd Operator
Underlying mathematical operator.
Definition: gemm/thread/mma_sm61.h:85
+
Array< ElementC, Shape::kMN > FragmentC
C operand storage.
Definition: gemm/thread/mma_sm61.h:207
+
Defines common types used for all GEMM-like operators.
+
arch::OpMultiplyAdd Operator
Underlying mathematical operator.
Definition: gemm/thread/mma_sm61.h:198
+
int8_t ElementB
Data type of operand B.
Definition: gemm/thread/mma_sm61.h:73
+
Array< ElementA, Shape::kMK > FragmentA
A operand storage.
Definition: gemm/thread/mma_sm61.h:88
+
Mapping function for column-major matrices.
Definition: layout/matrix.h:142
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
+
int8_t ElementB
Data type of operand B.
Definition: gemm/thread/mma_sm61.h:186
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Templates exposing architecture support for warp-level multiply-add operations.
+
Array< ElementA, Shape::kMK > FragmentA
A operand storage.
Definition: gemm/thread/mma_sm61.h:201
+
Shape of a matrix multiply-add operation.
Definition: include/cutlass/gemm/gemm.h:57
+
int8_t ElementA
Data type of operand A.
Definition: gemm/thread/mma_sm61.h:67
+
int32_t ElementC
Element type of operand C.
Definition: gemm/thread/mma_sm61.h:192
+
Mapping function for row-major matrices.
Definition: layout/matrix.h:50
+
LayoutC_ LayoutC
Layout of C matrix (concept: layout::MapFunc)
Definition: gemm/thread/mma_sm61.h:195
+
CUTLASS_HOST_DEVICE Reference at(TensorCoord const &coord) const
Returns a reference to the element at a given Coord.
Definition: tensor_ref.h:307
+
Structure to compute the matrix product.
Definition: gemm/thread/mma.h:66
+
LayoutC_ LayoutC
Layout of C matrix (concept: layout::MapFunc)
Definition: gemm/thread/mma_sm61.h:82
+
Defines layout functions used by TensorRef and derived classes.
+
int32_t ElementC
Element type of operand C.
Definition: gemm/thread/mma_sm61.h:79
+
Array< ElementB, Shape::kKN > FragmentB
B operand storage.
Definition: gemm/thread/mma_sm61.h:91
+
Array< ElementC, Shape::kMN > FragmentC
C operand storage.
Definition: gemm/thread/mma_sm61.h:94
+
Matrix multiply-add operation.
Definition: arch/mma.h:92
+
Basic include for CUTLASS.
+
Definition: matrix_coord.h:39
+
Shape_ Shape
Size of the Gemm problem - concept: gemm::GemmShape<>
Definition: gemm/thread/mma_sm61.h:177
+
int8_t ElementA
Data type of operand A.
Definition: gemm/thread/mma_sm61.h:180
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2warp_2mma_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2warp_2mma_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..bd1b2b5352131ba8b4062a06fc1f46e4dd1fab81
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/gemm_2warp_2mma_8h.html
@@ -0,0 +1,148 @@
+
+
+
+
+
+
+CUTLASS: mma.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Templates exposing architecture support for warp-level multiply-add operations.
+More...
+
+
Go to the source code of this file.
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/graph_legend.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/graph_legend.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a06ed050cbb5398b6f149c32c29006e39f00d56a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/graph_legend.md5
@@ -0,0 +1 @@
+387ff8eb65306fa251338d3c9bd7bfff
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/group__predicate__iterator__concept.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/group__predicate__iterator__concept.html
new file mode 100644
index 0000000000000000000000000000000000000000..32c4b8018ec6b21dd2c9a0f64017031b4ca51aca
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/group__predicate__iterator__concept.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+CUTLASS: Predicate Iterator Concept
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Implementations of Predicate Iterator Concept enables accessing and traversing elements of a bit vector.
+
Const Predicate Iterator A const Predicate Iterator Concept satisfies the following expressions
+++it increments the iterator to the next predicate
+*it returns the value of the currently pointed-to predicate
+
+
+
Mutable Predicate Iterator A Predicate Iterator Concept that is non-const also satisfies the following expressions
+it.set(bool value) sets the value of the currently pointed-to predicate
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__elementwise_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__elementwise_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..da56d7a093bbae97241d441cf4c70ff05c8c20d0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__elementwise_8h.html
@@ -0,0 +1,187 @@
+
+
+
+
+
+
+CUTLASS: tensor_elementwise.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the source code of this file.
+
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorAdd (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a, TensorRef< ElementB, LayoutB > b)
+ Adds two tensors and stores in the destination tensor: d = a + b. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA >
+void cutlass::reference::host::TensorAdd (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a)
+ Adds a tensor in place: d = d .+ a. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorSub (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a, TensorRef< ElementB, LayoutB > b)
+ Subtracts two tensors and stores in the destination tensor: d = a - b. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorSub (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a)
+ Subtracts two tensors in place: d = d .- a. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorMul (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a, TensorRef< ElementB, LayoutB > b)
+ Multiplies two tensors and stores in the destination tensor: d = a .* b. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA >
+void cutlass::reference::host::TensorMul (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a)
+ Multiplies tensors in place: d = d .* a. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorDiv (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a, TensorRef< ElementB, LayoutB > b)
+ Divides two tensors and stores in the destination tensor: d = a ./ b. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA >
+void cutlass::reference::host::TensorDiv (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a)
+ Divides tensors in place: d = d ./ a. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA , typename ElementB , typename LayoutB >
+void cutlass::reference::host::TensorModulus (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a, TensorRef< ElementB, LayoutB > b)
+ Divides two tensors and stores in the destination tensor: d = a ./ b. More...
+
+template<typename ElementD , typename LayoutD , typename ElementA , typename LayoutA >
+void cutlass::reference::host::TensorModulus (TensorView< ElementD, LayoutD > d, TensorRef< ElementA, LayoutA > a)
+ Divides tensors in place: d = d ./ a. More...
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__fill_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__fill_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..12919ee0c835de3b04faa6357c7f5f33ca2a3f3f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__fill_8h_source.html
@@ -0,0 +1,217 @@
+
+
+
+
+
+
+CUTLASS: tensor_fill.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 76 Element value_ = Element(0)
77 ): view(view_), value(value_) { }
80 view.at(coord) =
value ;
94 Element val = Element(0)) {
109 template <
typename Element>
127 seed(seed_), mean(mean_), stddev(stddev_), int_scale(int_scale_), pi(
std ::acos(-1)) {
128 std::srand((
unsigned )seed);
135 double u1 = double(std::rand()) / double(RAND_MAX);
136 double u2 = double(std::rand()) / double(RAND_MAX);
140 rnd = mean + stddev * rnd;
145 if (int_scale >= 0) {
146 rnd = double(int64_t(rnd *
double (1 << int_scale))) / double(1 << int_scale);
147 result =
static_cast< Element
> (rnd);
150 result =
static_cast< Element
> (rnd);
158 template <
typename Element>
176 seed(seed_), mean(mean_), stddev(stddev_), int_scale(int_scale_), pi(
std ::acos(-1)) {
177 std::srand((
unsigned )seed);
185 for (
int i = 0; i < 2; ++i) {
187 double u1 = double(std::rand()) / double(RAND_MAX);
188 double u2 = double(std::rand()) / double(RAND_MAX);
192 rnd = mean + stddev * rnd;
194 if (int_scale >= 0) {
195 rnd = double(
int (rnd *
double (1 << int_scale)));
196 reals[i] = from_real<Element>(rnd / double(1 << int_scale));
199 reals[i] = from_real<Element>(rnd);
231 view(view_), func(func_) {
237 view.
at (coord) = func();
290 for (
size_t i = 0; i < capacity; ++i) {
291 ptr[i] = random_func();
300 template <
typename Element>
320 seed(seed_), range(
max - min_), min(min_), int_scale(int_scale_) {
321 std::srand((
unsigned )seed);
328 double rnd = double(std::rand()) / double(RAND_MAX);
330 rnd = min + range * rnd;
336 if (int_scale >= 0) {
337 rnd = double(int64_t(rnd *
double (1 << int_scale))) / double(1 << int_scale);
338 result =
static_cast< Element
> (
Real (rnd));
341 result =
static_cast< Element
> (
Real (rnd));
349 template <
typename Element>
369 seed(seed_), range(
max - min_), min(min_), int_scale(int_scale_) {
370 std::srand((
unsigned )seed);
379 for (
int i = 0; i < 2; ++i) {
380 double rnd = double(std::rand()) / double(RAND_MAX);
382 rnd = min + range * rnd;
387 if (int_scale >= 0) {
388 rnd = double(
int (rnd *
double (1 << int_scale)));
389 reals[i] = from_real<Element>(
Real (rnd /
double (1 << int_scale)));
392 reals[i] = from_real<Element>(
Real (rnd));
396 return complex<Element>(reals[0], reals[1]);
424 view(view_), func(func_) {
431 view.
at (coord) = func();
481 for (
size_t i = 0; i < capacity; ++i) {
482 ptr[i] = random_func();
512 Element diag_ = Element(1),
513 Element other_ = Element(0)
515 view(view_), diag(diag_), other(other_) { }
521 for (
int i = 1; i < Layout::kRank; ++i) {
522 if (coord[i] != coord[i - 1]) {
528 view.
at (coord) = (is_diag ? diag : other);
542 Element diag = Element(1),
543 Element other = Element(0)) {
579 Element val = Element(1)) {
581 typename Layout::Index extent = dst.
extent ().min();
583 for (
typename Layout::Index i = 0; i < extent; ++i) {
614 Element other_ = Element(0)
616 view(view_), other(other_) { }
622 for (
int i = 1; i < Layout::kRank; ++i) {
623 if (coord[i] != coord[i - 1]) {
630 view.
at (coord) = other;
645 Element other = Element(1)) {
676 Array<Element, Layout::kRank>
v ;
688 Array<Element, Layout::kRank>
const & v_,
689 Element s_ = Element(0)
691 view(view_), v(v_), s(s_) { }
699 for (
int i = 0; i < Layout::kRank; ++i) {
700 sum += Element(coord[i]) * v[i];
703 view.
at (coord) = sum;
717 Array<Element, Layout::kRank>
const & v,
718 Element s = Element(0)) {
740 Element s = Element(0)) {
742 Array<Element, Layout::kRank> stride;
744 stride[0] = Element(1);
747 for (
int i = 1; i < Layout::kRank; ++i) {
748 stride[i] = stride[i - 1] * Element(dst.
extent ()[i - 1]);
764 Element v = Element(1),
765 Element s = Element(0)) {
768 while (i < capacity) {
770 8)>::
get (ptr, i) = s;
791 BlockFillRandomGaussian<Element>(
800 BlockFillRandomUniform<Element>(
819 Element
const *ptr) {
821 typename Layout::Index extent = dst.
extent ().min();
823 for (
typename Layout::Index i = 0; i < extent; ++i) {
825 dst.
at (coord) = ptr[i];
840 typename Layout::Index extent = src.
extent ().min();
842 for (
typename Layout::Index i = 0; i < extent; ++i) {
844 ptr[i] = src.
at (coord);
uint64_t seed
Definition: host/tensor_fill.h:112
+
+
CUTLASS_HOST_DEVICE complex< T > cos(complex< T > const &z)
Computes the cosine of complex z.
Definition: complex.h:401
+
+
+
+
void TensorCopyDiagonalOut(Element *ptr, TensorView< Element, Layout > src)
Copies the diagonal of a tensor into a dense buffer in host memory.
Definition: host/tensor_fill.h:836
+
Definition: aligned_buffer.h:35
+
Definition: distribution.h:40
+
< Layout function
Definition: host/tensor_fill.h:494
+
+
+
Definition: distribution.h:40
+
struct cutlass::Distribution::@18::@20 uniform
Uniform distribution.
+
TensorView< Element, Layout > TensorView
Definition: host/tensor_fill.h:61
+
void operator()(Coord< Layout::kRank > const &coord) const
Definition: host/tensor_fill.h:517
+
Element diag
Definition: host/tensor_fill.h:503
+
Element operator()() const
Compute random value and update RNG state.
Definition: host/tensor_fill.h:132
+
T Type
Definition: real.h:32
+
Kind kind
Active variant kind.
Definition: distribution.h:64
+
void TensorFill(TensorView< Element, Layout > dst, Element val=Element(0))
Fills a tensor with a uniform value.
Definition: host/tensor_fill.h:92
+
CUTLASS_HOST_DEVICE TensorCoord const & extent() const
Returns the extent of the view (the size along each logical dimension).
Definition: tensor_view.h:167
+
+
RandomGaussianFunc(uint64_t seed_=0, double mean_=0, double stddev_=1, int int_scale_=-1)
Definition: host/tensor_fill.h:170
+
struct cutlass::Distribution::@18::@21 gaussian
Gaussian distribution.
+
int int_scale
Definition: host/tensor_fill.h:164
+
void operator()(Coord< Layout::kRank > const &coord) const
Definition: host/tensor_fill.h:79
+
+
TensorView view
Definition: host/tensor_fill.h:605
+
void TensorFillDiagonal(TensorView< Element, Layout > dst, Element diag=Element(1), Element other=Element(0))
Fills a tensor everywhere with a unique value for its diagonal.
Definition: host/tensor_fill.h:540
+
< Layout function
Definition: host/tensor_fill.h:667
+
int int_scale
Definition: host/tensor_fill.h:115
+
< Layout function
Definition: host/tensor_fill.h:597
+
+
void TensorFillIdentity(TensorView< Element, Layout > dst)
Helper to fill a tensor's diagonal with 1 and 0 everywhere else.
Definition: host/tensor_fill.h:564
+
+
CUTLASS_HOST_DEVICE complex< T > log(complex< T > const &z)
Computes the complex exponential of z.
Definition: complex.h:381
+
void operator()(Coord< Layout::kRank > const &coord) const
Compute random value and update RNG state.
Definition: host/tensor_fill.h:236
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
double mean
Definition: host/tensor_fill.h:113
+
void TensorUpdateOffDiagonal(TensorView< Element, Layout > dst, Element other=Element(1))
Writes a uniform value to all elements in the tensor without modifying diagonal elements.
Definition: host/tensor_fill.h:643
+
Element s
Definition: host/tensor_fill.h:677
+
Array< Element, Layout::kRank > v
Definition: host/tensor_fill.h:676
+
+
+
TensorView view
Definition: host/tensor_fill.h:219
+
void TensorFillRandomGaussian(TensorView< Element, Layout > dst, uint64_t seed, double mean=0, double stddev=1, int bits=-1)
Fills a tensor with random values with a Gaussian distribution.
Definition: host/tensor_fill.h:249
+
double stddev
Definition: host/tensor_fill.h:163
+
complex< Element > operator()() const
Compute random value and update RNG state.
Definition: host/tensor_fill.h:181
+
void TensorFillLinear(TensorView< Element, Layout > dst, Array< Element, Layout::kRank > const &v, Element s=Element(0))
Fills tensor with a linear combination of its coordinate and another vector.
Definition: host/tensor_fill.h:715
+
Computes a random Gaussian distribution.
Definition: host/tensor_fill.h:211
+
void TensorUpdateDiagonal(TensorView< Element, Layout > dst, Element val=Element(1))
Writes a uniform value to the diagonal of a tensor without modifying off-diagonal elements...
Definition: host/tensor_fill.h:577
+
+
Definition: subbyte_reference.h:557
+
void operator()(Coord< Layout::kRank > const &coord) const
Updates the tensor.
Definition: host/tensor_fill.h:694
+
void BlockFillRandomGaussian(Element *ptr, size_t capacity, uint64_t seed, double mean=0, double stddev=1, int bits=-1)
Fills a tensor with random values with a Gaussian distribution.
Definition: host/tensor_fill.h:277
+
This header contains a class to parametrize a statistical distribution function.
+
TensorView view
Definition: host/tensor_fill.h:502
+
Element value
Definition: host/tensor_fill.h:68
+
+
+
Top-level include for all CUTLASS numeric types.
+
TensorFillLinearFunc(TensorView const &view_, Array< Element, Layout::kRank > const &v_, Element s_=Element(0))
Constructs functor.
Definition: host/tensor_fill.h:686
+
+
double pi
Definition: host/tensor_fill.h:116
+
void operator()(Coord< Layout::kRank > const &coord) const
Definition: host/tensor_fill.h:618
+
+
void BlockFillSequential(Element *ptr, int64_t capacity, Element v=Element(1), Element s=Element(0))
Fills a block of data with sequential elements.
Definition: host/tensor_fill.h:761
+
double stddev
Definition: host/tensor_fill.h:114
+
double pi
Definition: host/tensor_fill.h:165
+
TensorUpdateOffDiagonalFunc(TensorView const &view_=TensorView(), Element other_=Element(0))
Definition: host/tensor_fill.h:612
+
Definition: host/tensor_fill.h:110
+
uint64_t seed
Definition: host/tensor_fill.h:161
+
+
TensorFillGaussianFunc(TensorView view_=TensorView(), RandomGaussianFunc< Element > func_=RandomGaussianFunc< Element >())
Construction of Gaussian RNG functor.
Definition: host/tensor_fill.h:227
+
Element other
Definition: host/tensor_fill.h:606
+
TensorFillDiagonalFunc(TensorView const &view_=TensorView(), Element diag_=Element(1), Element other_=Element(0))
Definition: host/tensor_fill.h:510
+
RandomGaussianFunc(uint64_t seed_=0, double mean_=0, double stddev_=1, int int_scale_=-1)
Definition: host/tensor_fill.h:121
+
TensorView view
Definition: host/tensor_fill.h:67
+
+
+
CUTLASS_HOST_DEVICE Reference at(TensorCoord const &coord) const
Returns a reference to the element at a given Coord.
Definition: tensor_ref.h:307
+
+
TensorFillLinearFunc()
Definition: host/tensor_fill.h:683
+
void BlockFillRandomUniform(Element *ptr, size_t capacity, uint64_t seed, double max=1, double min=0, int bits=-1)
Fills a tensor with random values with a uniform random distribution.
Definition: host/tensor_fill.h:470
+
+
void TensorForEach(Coord< Rank > extent, Func &func)
Iterates over the index space of a tensor.
Definition: host/tensor_foreach.h:87
+
void TensorFillRandomUniform(TensorView< Element, Layout > dst, uint64_t seed, double max=1, double min=0, int bits=-1)
Fills a tensor with random values with a uniform random distribution.
Definition: host/tensor_fill.h:443
+
void TensorCopyDiagonalIn(TensorView< Element, Layout > dst, Element const *ptr)
Copies a diagonal in from host memory without modifying off-diagonal elements.
Definition: host/tensor_fill.h:817
+
+
Distribution type.
Definition: distribution.h:38
+
RandomGaussianFunc< Element > func
Definition: host/tensor_fill.h:220
+
void TensorFillSequential(TensorView< Element, Layout > dst, Element s=Element(0))
Fills tensor with a linear combination of its coordinate and another vector.
Definition: host/tensor_fill.h:738
+
< Layout function
Definition: host/tensor_fill.h:59
+
int int_scale
Random values are cast to integer after scaling by this power of two.
Definition: distribution.h:67
+
TensorFillFunc(TensorView const &view_=TensorView(), Element value_=Element(0))
Definition: host/tensor_fill.h:74
+
+
Basic include for CUTLASS.
+
double mean
Definition: host/tensor_fill.h:162
+
TensorView view
Definition: host/tensor_fill.h:675
+
+
+
CUTLASS_HOST_DEVICE complex< T > sqrt(complex< T > const &z)
Computes the square root of complex number z.
Definition: complex.h:393
+
+
Element other
Definition: host/tensor_fill.h:504
+
void BlockFillRandom(Element *ptr, size_t capacity, uint64_t seed, Distribution dist)
Fills a block of data with sequential elements.
Definition: host/tensor_fill.h:784
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__foreach_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__foreach_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..4dee3539a55c436b1d767a4f1abaa6a5262d529d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/host_2tensor__foreach_8h_source.html
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+CUTLASS: tensor_foreach.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 40 template <
typename Func,
int Rank,
int RankRemaining>
52 for (
int i = 0; i < extent.
at (kActiveRank); ++i) {
60 template <
typename Func,
int Rank>
72 for (
int i = 0; i < extent.
at (kActiveRank); ++i) {
105 template <
typename Element,
typename Func>
112 typename Func::Params params =
typename Func::Params()) {
116 for (
size_t index = 0; index < capacity; ++index) {
Definition: host/tensor_foreach.h:106
+
Definition: aligned_buffer.h:35
+
BlockForEach(Element *ptr, size_t capacity, typename Func::Params params=typename Func::Params())
Constructor performs the operation.
Definition: host/tensor_foreach.h:109
+
static int const kActiveRank
Index of the active rank.
Definition: host/tensor_foreach.h:44
+
TensorForEachHelper(Func &func, Coord< Rank > const &extent, Coord< Rank > &coord)
Constructor for general rank.
Definition: host/tensor_foreach.h:47
+
Helper to perform for-each operation.
Definition: host/tensor_foreach.h:41
+
TensorForEachHelper(Func &func, Coord< Rank > const &extent, Coord< Rank > &coord)
Constructor for fastest changing rank.
Definition: host/tensor_foreach.h:67
+
Statically-sized array specifying Coords within a tensor.
Definition: coord.h:43
+
void TensorForEachLambda(Coord< Rank > extent, Func func)
Iterates over the index space of a tensor and calls a C++ lambda.
Definition: host/tensor_foreach.h:98
+
void TensorForEach(Coord< Rank > extent, Func &func)
Iterates over the index space of a tensor.
Definition: host/tensor_foreach.h:87
+
CUTLASS_HOST_DEVICE Index & at()
Gets the index of a given Coord element.
Definition: coord.h:255
+
Basic include for CUTLASS.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2device_2gemm__complex_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2device_2gemm__complex_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..eca770e65902da617738a33775331159877e1fa2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2device_2gemm__complex_8h__incl.md5
@@ -0,0 +1 @@
+f30c5ee8150f93807fffe9c68f4e3156
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..bfeab4749c920ede9706e498cd4ed2e5dc822c68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h__dep__incl.md5
@@ -0,0 +1 @@
+4c9c8bbf167d1cccb09177ceb410626e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..de98a76d642ece5458d3dacb9ec75ea50e2450f1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/include_2cutlass_2gemm_2gemm_8h_source.html
@@ -0,0 +1,178 @@
+
+
+
+
+
+
+CUTLASS: gemm.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 58 static int const kM = M;
59 static int const kN = N;
60 static int const kK = K;
62 static int const kMN = M * N;
63 static int const kMK = M * K;
64 static int const kKN = N * K;
65 static int const kMNK = M * N * K;
67 static int const kCount = kMNK;
103 static int const kM = 0;
106 static int const kN = 1;
109 static int const kK = 2;
129 Index
const &
m ()
const {
return this->at(kM); }
133 Index &
m () {
return this->at(kM); }
137 Index
const &
n ()
const {
return this->at(kN); }
141 Index &
n () {
return this->at(kN); }
145 Index
const &
k ()
const {
return this->at(kK); }
149 Index &
k () {
return this->at(kK); }
269 static int const kM = 0;
272 static int const kN = 1;
275 static int const kK = 2;
278 static int const kBatch = 3;
298 Index
const &
m ()
const {
return this->at(kM); }
302 Index &
m () {
return this->at(kM); }
306 Index
const &
n ()
const {
return this->at(kN); }
310 Index &
n () {
return this->at(kN); }
314 Index
const &
k ()
const {
return this->at(kK); }
318 Index &
k () {
return this->at(kK); }
322 Index
const &
batch ()
const {
return this->at(kBatch); }
326 Index &
batch () {
return this->at(kBatch); }
CUTLASS_HOST_DEVICE Coord< 4 > mnkb() const
Obtains a Coord<4> from BatchedGemmCoord.
Definition: include/cutlass/gemm/gemm.h:336
+
Coord< 4, Index > Base
Base type is a Coord of rank=4.
Definition: include/cutlass/gemm/gemm.h:266
+
CUTLASS_HOST_DEVICE Index & m()
Returns reference to the GEMM M coordinate.
Definition: include/cutlass/gemm/gemm.h:302
+
Definition: aligned_buffer.h:35
+
CUTLASS_HOST_DEVICE BatchedGemmCoord operator/(Base const &b) const
Element-wise division.
Definition: include/cutlass/gemm/gemm.h:364
+
CUTLASS_HOST_DEVICE GemmCoord & operator/=(Base const &b)
In-place division.
Definition: include/cutlass/gemm/gemm.h:250
+
int Index
Integer-valued index.
Definition: include/cutlass/gemm/gemm.h:97
+
CUTLASS_HOST_DEVICE GemmCoord(Coord< 3, Index > const &coord)
Constructs from Coord<3> and a batch.
Definition: include/cutlass/gemm/gemm.h:121
+
CUTLASS_HOST_DEVICE GemmCoord mnk() const
Obtains a GemmCoord from BatchedGemmCoord.
Definition: include/cutlass/gemm/gemm.h:330
+
CUTLASS_HOST_DEVICE GemmCoord operator+(Base const &b) const
Element-wise addition.
Definition: include/cutlass/gemm/gemm.h:205
+
A Coord is a coordinate of arbitrary rank into a tensor or matrix.
+
CUTLASS_HOST_DEVICE Coord< 1 > make_Coord(int _0)
Helper to make a 2-element coordinate.
Definition: coord.h:387
+
CUTLASS_HOST_DEVICE Index & m()
Returns reference to the GEMM M coordinate.
Definition: include/cutlass/gemm/gemm.h:133
+
Operand
GEMM operand enumeration: D = A * B + C.
Definition: include/cutlass/gemm/gemm.h:39
+
Definition: include/cutlass/gemm/gemm.h:94
+
CUTLASS_HOST_DEVICE Coord< 2 > mn() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:171
+
CUTLASS_HOST_DEVICE half_t & operator/=(half_t &lhs, half_t const &rhs)
Definition: half.h:684
+
CUTLASS_HOST_DEVICE BatchedGemmCoord operator-(Base const &b) const
Element-wise subtraction.
Definition: include/cutlass/gemm/gemm.h:352
+
CUTLASS_HOST_DEVICE Index & batch()
Returns reference to the GEMM batch coordinate.
Definition: include/cutlass/gemm/gemm.h:326
+
CUTLASS_HOST_DEVICE Index const & n() const
Returns the GEMM N coordinate.
Definition: include/cutlass/gemm/gemm.h:137
+
CUTLASS_HOST_DEVICE Coord< 2 > nm() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:165
+
CUTLASS_HOST_DEVICE BatchedGemmCoord operator+(Base const &b) const
Element-wise addition.
Definition: include/cutlass/gemm/gemm.h:346
+
CUTLASS_HOST_DEVICE Index & k()
Returns reference to the GEMM K coordinate.
Definition: include/cutlass/gemm/gemm.h:149
+
CUTLASS_HOST_DEVICE Index & n()
Returns reference to the GEMM N coordinate.
Definition: include/cutlass/gemm/gemm.h:310
+
CUTLASS_HOST_DEVICE GemmCoord operator/(Base const &b) const
Element-wise division.
Definition: include/cutlass/gemm/gemm.h:223
+
CUTLASS_HOST_DEVICE GemmCoord(Index m, Index n, Index k)
Helper to construct from a K, N, M, batch variables.
Definition: include/cutlass/gemm/gemm.h:125
+
int Index
Integer-valued index.
Definition: include/cutlass/gemm/gemm.h:263
+
CUTLASS_HOST_DEVICE half_t & operator+=(half_t &lhs, half_t const &rhs)
Definition: half.h:654
+
CUTLASS_HOST_DEVICE Coord< 2 > nk() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:189
+
CUTLASS_HOST_DEVICE BatchedGemmCoord(Base const &coord)
Constructs from Coord<4>
Definition: include/cutlass/gemm/gemm.h:290
+
CUTLASS_HOST_DEVICE Index const & k() const
Returns the GEMM K coordinate.
Definition: include/cutlass/gemm/gemm.h:145
+
+
CUTLASS_HOST_DEVICE half_t & operator-=(half_t &lhs, half_t const &rhs)
Definition: half.h:664
+
Coord< 3, Index > Base
Base type is a Coord of rank=4.
Definition: include/cutlass/gemm/gemm.h:100
+
+
static CUTLASS_HOST_DEVICE Coord< 3 > toCoord()
Returns a Coord object.
Definition: include/cutlass/gemm/gemm.h:76
+
CUTLASS_HOST_DEVICE Coord< 2 > km() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:183
+
Definition: include/cutlass/gemm/gemm.h:260
+
CUTLASS_HOST_DEVICE Coord< 3 > mnk() const
Obtains a Coord<3> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:153
+
CUTLASS_HOST_DEVICE GemmCoord operator-(Base const &b) const
Element-wise subtraction.
Definition: include/cutlass/gemm/gemm.h:211
+
CUTLASS_HOST_DEVICE Index const & batch() const
Returns the GEMM batch coordinate.
Definition: include/cutlass/gemm/gemm.h:322
+
CUTLASS_HOST_DEVICE BatchedGemmCoord & operator*=(Base const &b)
In-place multiplication.
Definition: include/cutlass/gemm/gemm.h:384
+
CUTLASS_HOST_DEVICE BatchedGemmCoord operator*(Base const &b) const
Element-wise multiplication.
Definition: include/cutlass/gemm/gemm.h:358
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
CUTLASS_HOST_DEVICE Index const & k() const
Returns the GEMM K coordinate.
Definition: include/cutlass/gemm/gemm.h:314
+
Shape of a matrix multiply-add operation.
Definition: include/cutlass/gemm/gemm.h:57
+
CUTLASS_HOST_DEVICE Coord< 2 > mk() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:177
+
CUTLASS_HOST_DEVICE BatchedGemmCoord()
Default ctor.
Definition: include/cutlass/gemm/gemm.h:286
+
CUTLASS_HOST_DEVICE Index & k()
Returns reference to the GEMM K coordinate.
Definition: include/cutlass/gemm/gemm.h:318
+
+
CUTLASS_HOST_DEVICE Coord< 3 > knm() const
Obtains a Coord<3> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:159
+
CUTLASS_HOST_DEVICE GemmCoord & operator+=(Base const &b)
In-place addition.
Definition: include/cutlass/gemm/gemm.h:229
+
CUTLASS_HOST_DEVICE half_t & operator*=(half_t &lhs, half_t const &rhs)
Definition: half.h:674
+
+
CUTLASS_HOST_DEVICE GemmCoord()
Default ctor.
Definition: include/cutlass/gemm/gemm.h:117
+
CUTLASS_HOST_DEVICE BatchedGemmCoord & operator/=(Base const &b)
In-place division.
Definition: include/cutlass/gemm/gemm.h:391
+
CUTLASS_HOST_DEVICE GemmCoord & operator-=(Base const &b)
In-place subtraction.
Definition: include/cutlass/gemm/gemm.h:236
+
CUTLASS_HOST_DEVICE BatchedGemmCoord & operator+=(Base const &b)
In-place addition.
Definition: include/cutlass/gemm/gemm.h:370
+
CUTLASS_HOST_DEVICE Coord< 2 > kn() const
Obtains a Coord<2> from GemmCoord.
Definition: include/cutlass/gemm/gemm.h:195
+
CUTLASS_HOST_DEVICE Index const & n() const
Returns the GEMM N coordinate.
Definition: include/cutlass/gemm/gemm.h:306
+
CUTLASS_HOST_DEVICE BatchedGemmCoord(Index m, Index n, Index k, Index b)
Helper to construct from a K, N, M, and batch variables.
Definition: include/cutlass/gemm/gemm.h:294
+
CUTLASS_HOST_DEVICE Index const & m() const
Returns the GEMM M coordinate.
Definition: include/cutlass/gemm/gemm.h:129
+
CUTLASS_HOST_DEVICE GemmCoord & operator*=(Base const &b)
In-place multiplication.
Definition: include/cutlass/gemm/gemm.h:243
+
+
CUTLASS_HOST_DEVICE BatchedGemmCoord & operator-=(Base const &b)
In-place subtraction.
Definition: include/cutlass/gemm/gemm.h:377
+
Basic include for CUTLASS.
+
CUTLASS_HOST_DEVICE Index & n()
Returns reference to the GEMM N coordinate.
Definition: include/cutlass/gemm/gemm.h:141
+
CUTLASS_HOST_DEVICE GemmCoord operator*(Base const &b) const
Element-wise multiplication.
Definition: include/cutlass/gemm/gemm.h:217
+
CUTLASS_HOST_DEVICE Index const & m() const
Returns the GEMM M coordinate.
Definition: include/cutlass/gemm/gemm.h:298
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_0.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_0.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1bc3a38363385c59b5e778145537842b52650d34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_0.md5
@@ -0,0 +1 @@
+379f50dfa3d9991a2e4c1a5d475ae9a0
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_103.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_103.md5
new file mode 100644
index 0000000000000000000000000000000000000000..45d4fdc4e136a27ca5d69f1cb574a98270417b0b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_103.md5
@@ -0,0 +1 @@
+d927174dd1266b4702fba2628114cb2a
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_106.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_106.md5
new file mode 100644
index 0000000000000000000000000000000000000000..94f2259a599b31c6b11a449d13c68b9d9ec1cc60
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_106.md5
@@ -0,0 +1 @@
+19b709d412ac2a1ff738049a7eb5b354
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_124.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_124.md5
new file mode 100644
index 0000000000000000000000000000000000000000..e550f2ea99ec1fc1d8a210bb1336189b96a3a7ef
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_124.md5
@@ -0,0 +1 @@
+8ac27405f306b4a15d48e374057e80f3
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_13.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_13.md5
new file mode 100644
index 0000000000000000000000000000000000000000..c63ad1a7ecc276ee4823f43de1bf01eb7caf306d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_13.md5
@@ -0,0 +1 @@
+cc05a003d740b83b1782e07bcfbf0a4f
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_152.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_152.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ddd2c4fabbb169c46d5fabf9fb0e3aafee6c799b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_152.md5
@@ -0,0 +1 @@
+dc116a047d0bf904718a100df947f014
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_155.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_155.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3aa9f9f44d88df64eda6ce914f53730af23cdfa9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_155.md5
@@ -0,0 +1 @@
+2a93e9cd60b26a0e54100c8a924234fa
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_157.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_157.md5
new file mode 100644
index 0000000000000000000000000000000000000000..f6c77a388883726664b65abc74c44d3ebebecfd6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_157.md5
@@ -0,0 +1 @@
+87a6b103eb6b6dd7f8ecb5c03ce456e8
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_161.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_161.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2ce71d8c5aae025e03398ca1f9e2e4e8b0d752df
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_161.md5
@@ -0,0 +1 @@
+67434d089d9e5bfc37ceb77a5cafd809
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_2.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_2.md5
new file mode 100644
index 0000000000000000000000000000000000000000..f9dae7896348f775989a11e636c38bba4ff6e3fb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_2.md5
@@ -0,0 +1 @@
+df0604dc3d94f1fc6361cdeaccce07b2
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_210.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_210.md5
new file mode 100644
index 0000000000000000000000000000000000000000..5a9a1923613b72a2d56b1223887bded3c3250fe3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_210.md5
@@ -0,0 +1 @@
+5c6ea7755f0c6ac19b0f863ffa26f5fb
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_211.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_211.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ed17c2b02f741d97690da04f36adfd05d4b964c3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_211.md5
@@ -0,0 +1 @@
+43af3245b2c7f3aedbcca6b3fb530953
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_217.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_217.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b2a988e44058bb2387092a5c7365c2e866f42d43
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_217.md5
@@ -0,0 +1 @@
+ddd49fce99df47ef80965bbaf248231c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_220.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_220.md5
new file mode 100644
index 0000000000000000000000000000000000000000..e5e6fd7acec7cd93daab20145687af4f531a2db6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_220.md5
@@ -0,0 +1 @@
+7541392b1e663fb9df112226ef6b9d7f
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_229.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_229.md5
new file mode 100644
index 0000000000000000000000000000000000000000..dd47ca6e27aa3737e412dbe4d6efd5e7bf241225
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_229.md5
@@ -0,0 +1 @@
+1515ba4f7372d2e31b86a606c1a87205
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_240.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_240.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ec022859fe438760133f7464a5fdfe19cae1b4dd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_240.md5
@@ -0,0 +1 @@
+73b99c6807696a29537f76dfd8eb7d6f
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_253.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_253.md5
new file mode 100644
index 0000000000000000000000000000000000000000..51125458ce63639e5043b3cc8befd48be7114985
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_253.md5
@@ -0,0 +1 @@
+01c96f6a8aef29c3703e789f1fd22f0c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_259.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_259.md5
new file mode 100644
index 0000000000000000000000000000000000000000..31e27832a8784d4f90b202b3ecf55ae77df2c072
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_259.md5
@@ -0,0 +1 @@
+36e83858f2147d67c1843851ad897e60
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_274.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_274.md5
new file mode 100644
index 0000000000000000000000000000000000000000..c9c5cb960c40c567eefa510db6d3d9bc24a7b1a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_274.md5
@@ -0,0 +1 @@
+170e8523fcd50552b361f28a3ee07c70
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_277.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_277.md5
new file mode 100644
index 0000000000000000000000000000000000000000..92867a49faa4bbb219a7bf906ecb3c9469942573
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_277.md5
@@ -0,0 +1 @@
+7b7e182798e1dadb466b1013e00e4a03
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_278.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_278.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a79ed504d154fb1bfbc5ab22b976a9ab0ed55ff6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_278.md5
@@ -0,0 +1 @@
+4ff4c9615f52ac9cca79013c5996ca1e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_284.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_284.md5
new file mode 100644
index 0000000000000000000000000000000000000000..cb3414faeeb11b91df328ca166ebb59213211119
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_284.md5
@@ -0,0 +1 @@
+f9e4ea0c6d6738fd71075f3382e6e19f
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_286.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_286.md5
new file mode 100644
index 0000000000000000000000000000000000000000..4652e026cb5f32b4aef049d8096e31050a5e43ab
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_286.md5
@@ -0,0 +1 @@
+e0cc28cdc1eb4dc53225aa9e11aa8ad5
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_294.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_294.md5
new file mode 100644
index 0000000000000000000000000000000000000000..c80fa6408718eabdd9ff630328375105c7b77a43
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_294.md5
@@ -0,0 +1 @@
+6e0496e142f42d34d3bc59fc846e2407
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_298.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_298.md5
new file mode 100644
index 0000000000000000000000000000000000000000..afa73dad2446eb63c18799159fbb532bd9caca79
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_298.md5
@@ -0,0 +1 @@
+b5641604f27eb367168d85b4419d6b28
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_312.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_312.md5
new file mode 100644
index 0000000000000000000000000000000000000000..bfcd3759dd2a3bfab768ed267d40c8d4c4be3e8c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_312.md5
@@ -0,0 +1 @@
+68ac8f0dccbf52e42f1d35db102fb0c3
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_320.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_320.md5
new file mode 100644
index 0000000000000000000000000000000000000000..4d490871e2c065461b3f5b0526c662b7666ec2d8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_320.md5
@@ -0,0 +1 @@
+e0cce870e9a4b11cb5c8715cbc2d220d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_321.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_321.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d8843d0914eebd668ba8e48653e166cfe191f220
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_321.md5
@@ -0,0 +1 @@
+36b3d7bf547df9eeb95efe5493277d2e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_322.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_322.md5
new file mode 100644
index 0000000000000000000000000000000000000000..168724602fb2dbe2a444480b118cbdc7c6d6c6d8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_322.md5
@@ -0,0 +1 @@
+3a6ecc75fc12d47394a64c6dc1da533a
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_325.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_325.md5
new file mode 100644
index 0000000000000000000000000000000000000000..5015c120865de0aec1fe07a45aad5ec11f0da33a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_325.md5
@@ -0,0 +1 @@
+8d811b6b599ed9e5af81fe4b5bda1367
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_334.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_334.md5
new file mode 100644
index 0000000000000000000000000000000000000000..02d9f0e82a2729e0e39ab2b3b1a1ed581ace7aac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_334.md5
@@ -0,0 +1 @@
+7a0c9808edf766db4a7767488399e5b8
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_348.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_348.md5
new file mode 100644
index 0000000000000000000000000000000000000000..36b8faf48672a116b3ad1f8ec33eba8190624fce
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_348.md5
@@ -0,0 +1 @@
+9443888a6a4687921661bd3fbfde1b8d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_349.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_349.md5
new file mode 100644
index 0000000000000000000000000000000000000000..137a369cc820cb9927e0346207fb8b66dedb9663
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_349.md5
@@ -0,0 +1 @@
+dedf049e6cfaf3f5220c50dbc847f247
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_350.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_350.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2da6656be054d67afcfa0b31528d0a6f7e54e9c5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_350.md5
@@ -0,0 +1 @@
+5251cd39df0ec64d056a9ce96c05a09d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_352.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_352.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b3ff8fde4c6ad6f0a828f8963f2e937441dc9cb9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_352.md5
@@ -0,0 +1 @@
+ec9ca994c325f6d577ace35984b413be
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_353.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_353.md5
new file mode 100644
index 0000000000000000000000000000000000000000..70a98cde812d46f50ecc689c834f03b3c844ed9f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_353.md5
@@ -0,0 +1 @@
+4269f35cd535e978b50c3f6956d0e51b
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_397.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_397.md5
new file mode 100644
index 0000000000000000000000000000000000000000..39a8b18defa6bc51f4ee7e0e744872d23712b74f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_397.md5
@@ -0,0 +1 @@
+ed6607cc4864fdcc1dfd5b0746e3f57f
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_40.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_40.md5
new file mode 100644
index 0000000000000000000000000000000000000000..56d9a9de873c9c98b5d26c156d9e25964972f85a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_40.md5
@@ -0,0 +1 @@
+ed59f95e9104f4e97cd679dc8821fbfa
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_406.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_406.md5
new file mode 100644
index 0000000000000000000000000000000000000000..45029a85555fedf647573ce064b358996f3c20ae
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_406.md5
@@ -0,0 +1 @@
+7edc141c1f04b51cb9621595c98b50b2
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_407.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_407.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a63dac70935743590fab856ca2b45f69ef66ac02
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_407.md5
@@ -0,0 +1 @@
+0386a1aa63285b417e732970eed51147
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_411.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_411.md5
new file mode 100644
index 0000000000000000000000000000000000000000..08905596bf66c40561ed36d912638f189d9babf0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_411.md5
@@ -0,0 +1 @@
+c8d161df63f0e8923e86a18e60a739cf
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_416.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_416.md5
new file mode 100644
index 0000000000000000000000000000000000000000..fb6c1e3f6ab17fe4c8cfffed8adb6f1db2b617a1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_416.md5
@@ -0,0 +1 @@
+8385695e8c5f27538bab7c72ed675841
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_419.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_419.md5
new file mode 100644
index 0000000000000000000000000000000000000000..5d6b94cb260df6e1ab58f8e9ec14d62c542a4eb1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_419.md5
@@ -0,0 +1 @@
+8b2a4fc0b43fbb5e053de762cd768d5e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_423.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_423.md5
new file mode 100644
index 0000000000000000000000000000000000000000..95dad657102ee0d7b0367b9d3611dcacdc4acf9d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_423.md5
@@ -0,0 +1 @@
+e122ec0dbf91664dc848b2bfad750997
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_436.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_436.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d00ff088720dde7bc768d6dfcdd3cd32a58a5675
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_436.md5
@@ -0,0 +1 @@
+d512b6d72d054bd9d680a55730c2d413
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_452.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_452.md5
new file mode 100644
index 0000000000000000000000000000000000000000..66841eb28139e70c9c29d20a928ce102039afcd3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_452.md5
@@ -0,0 +1 @@
+23e80d322ebf7586789e07f6808a59c3
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_458.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_458.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ce34eb2c26d6e0aa52768a8065d7143dc621c6b3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_458.md5
@@ -0,0 +1 @@
+b65bbe96e0af01922c4ed53505d6b0a0
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_462.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_462.md5
new file mode 100644
index 0000000000000000000000000000000000000000..f62bc3d8d81737495880eebc2d477913de51bfd5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_462.md5
@@ -0,0 +1 @@
+1ed27c15af5c16edfd6621adade698f7
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_474.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_474.md5
new file mode 100644
index 0000000000000000000000000000000000000000..830444bf0be85209ce7b720fb5f348107873ee35
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_474.md5
@@ -0,0 +1 @@
+0117863321da7aa69a76620a73fee260
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_476.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_476.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1c27219ce41eddd43ec96992333568b2cac9f6f8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_476.md5
@@ -0,0 +1 @@
+b192e384a4f915d0bd27bca6236d3382
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_479.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_479.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9b47b742632ca1f9718e88ef26dc89796ee9494f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_479.md5
@@ -0,0 +1 @@
+3c721b474ac5d8193a7ec1dfeda43207
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_492.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_492.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1e2f0669e4ed605bd459095b14e8b27876a99080
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_492.md5
@@ -0,0 +1 @@
+4f6793d1ad3e6b859f70abf4d67348c1
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_495.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_495.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d543cd358ea2e2aafa747f865b51539d9ff706df
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_495.md5
@@ -0,0 +1 @@
+3ab6de731d4d3fa67b727368638ef1b8
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_498.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_498.md5
new file mode 100644
index 0000000000000000000000000000000000000000..89d5bd4abf136017a203f7687d93c18b553c60c5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_498.md5
@@ -0,0 +1 @@
+72b109142b198a061316d4076d19a7f6
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_504.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_504.md5
new file mode 100644
index 0000000000000000000000000000000000000000..759057a652444137e9a956fdf92ff2d67039a0a1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_504.md5
@@ -0,0 +1 @@
+d3bfccb487ade8caea405ab98ae8eb39
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_508.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_508.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2aab9ccc60de2ce07e0f1509706333534287a2e8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_508.md5
@@ -0,0 +1 @@
+acfe63ee1a1eaa4aa8f1b04cf09d84b5
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_512.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_512.md5
new file mode 100644
index 0000000000000000000000000000000000000000..df20e81f625254bae298af7c555239b98ca8624b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_512.md5
@@ -0,0 +1 @@
+bdd01e8bd1b5ee9c06a650d4c4b2a4e3
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_518.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_518.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1555e38b29ded371e2ec3d325e7aac51e9428206
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_518.md5
@@ -0,0 +1 @@
+f35293a703b508a8eba1dd361b3251a2
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_549.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_549.md5
new file mode 100644
index 0000000000000000000000000000000000000000..48af84a4ab6ccafd4442d0f1756af232fb1444ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_549.md5
@@ -0,0 +1 @@
+f87027cd70349c03ab514e28252910e7
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_553.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_553.md5
new file mode 100644
index 0000000000000000000000000000000000000000..7f22779b98d7c10f592752505d3fa34623afc063
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_553.md5
@@ -0,0 +1 @@
+95ff12e1d97998f9c80b4941a76d7bac
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_563.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_563.md5
new file mode 100644
index 0000000000000000000000000000000000000000..8d56abbbf86ecfbf50bed4301ee457cbc535c189
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_563.md5
@@ -0,0 +1 @@
+aa9b23b4789f4519eab25aa596c8125e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_577.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_577.md5
new file mode 100644
index 0000000000000000000000000000000000000000..dd9bb40fb9e45ac9f70fc3d76b07f95f299feb14
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_577.md5
@@ -0,0 +1 @@
+59a3633ccf256362f25d127ec846b973
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_58.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_58.md5
new file mode 100644
index 0000000000000000000000000000000000000000..4b0c72752c1092d235ed22dff2f57f496caefea3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_58.md5
@@ -0,0 +1 @@
+d5f600b20abe7566ecd56d69cb290d4d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_590.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_590.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9d050ef0bf600f5e0bf1714c1e0635763a3f47e3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_590.md5
@@ -0,0 +1 @@
+6fbb2dced1403d31e847e54008b596da
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_592.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_592.md5
new file mode 100644
index 0000000000000000000000000000000000000000..5f442aa7ecaf7bc08301f60f1d16e51c9e8a3d9e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_592.md5
@@ -0,0 +1 @@
+07bb689b7cee45ff7f701b7c58ff3aa7
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_598.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_598.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9446a4f6281d42333772e37c34ff28b2a952e01d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_598.md5
@@ -0,0 +1 @@
+23738a37b964e370c6c0e7ecb3b44704
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_60.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_60.md5
new file mode 100644
index 0000000000000000000000000000000000000000..86b71c9ebddcf5b9aebe1032790f640505bee10b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_60.md5
@@ -0,0 +1 @@
+a9fa72935474ed4a65a947c45a676fdc
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_604.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_604.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a05249de9830a9d80a78ae5794d9526de142e68b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_604.md5
@@ -0,0 +1 @@
+2873888796b9287448571c7402f3a342
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_608.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_608.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1e92f26e985c264c281389342802544e9a9e5c63
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_608.md5
@@ -0,0 +1 @@
+5f537d6b6354b81a75ac8e0b283c0a8e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_61.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_61.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ca76d861b08f91df77113ebe1bca178bffd837f1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_61.md5
@@ -0,0 +1 @@
+fa586a68514c61be5d338d5b09512c66
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_611.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_611.md5
new file mode 100644
index 0000000000000000000000000000000000000000..85939d23f6ecda5a9831ffb5e2c6537f3ffcd31b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_611.md5
@@ -0,0 +1 @@
+35d6a1b3b3e18ecad0deedd5f544b4fd
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_612.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_612.md5
new file mode 100644
index 0000000000000000000000000000000000000000..416ef39de1e516e48cb1008691aad9955fddd72a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_612.md5
@@ -0,0 +1 @@
+5d7f2556d037f92672883bfc41bdf548
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_62.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_62.md5
new file mode 100644
index 0000000000000000000000000000000000000000..fe4f5a56afc9b9090e06df73a51396e1adc1738e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_62.md5
@@ -0,0 +1 @@
+593464be6896a4cea38d1ee1d5da2126
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_625.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_625.md5
new file mode 100644
index 0000000000000000000000000000000000000000..96e96a3a39f199c409727a3c855780b877b7c527
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_625.md5
@@ -0,0 +1 @@
+225e057854cb6d96385f16225c48aaa7
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_64.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_64.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9ab397316af63ea5136c9f58377d332de9816c22
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_64.md5
@@ -0,0 +1 @@
+669047b4f7e4840b231be2c326a0cdff
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_643.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_643.md5
new file mode 100644
index 0000000000000000000000000000000000000000..16b35412dd5d0642a597f8c0bfb1a82d1a1beb9e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_643.md5
@@ -0,0 +1 @@
+6f4a2beec7ea5d10b4fa6fcd5f34f296
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_647.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_647.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3c526a01a368a30f4153f4e0fc675a982d7f98d5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_647.md5
@@ -0,0 +1 @@
+80d7f81f98e30408712d0dd95955e859
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_653.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_653.md5
new file mode 100644
index 0000000000000000000000000000000000000000..835ec72e86f19e64ee9bcc9bf40892dc076370da
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_653.md5
@@ -0,0 +1 @@
+ceecba04818d435319e1f78ce39b3438
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_657.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_657.md5
new file mode 100644
index 0000000000000000000000000000000000000000..58ef88dd1c5d00ae59ec52f1be082ae1efefc128
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_657.md5
@@ -0,0 +1 @@
+b84e58475c9f069b3b62838e0cd3e93c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_661.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_661.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a8866cf9892ed9301e71ddf0342a93da677f69fc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_661.md5
@@ -0,0 +1 @@
+2faf9b1ad47cd2b25cc5104f7673c5cc
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_662.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_662.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ed5845b03e8c50a9077f29bba6fa59b519ee9c0d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_662.md5
@@ -0,0 +1 @@
+cb7f805be5971acbeaabcdad87596015
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_674.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_674.md5
new file mode 100644
index 0000000000000000000000000000000000000000..09cbba6fa0648a829d1797ef70f9fbdc8f38ff71
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_674.md5
@@ -0,0 +1 @@
+74f37d3951c050dd79e4d786d049fba9
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_685.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_685.md5
new file mode 100644
index 0000000000000000000000000000000000000000..6e18f6d2119589dece719d0b048247f43bb8af73
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_685.md5
@@ -0,0 +1 @@
+f7178af3ebb3d5c937f490d50f6ce299
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_699.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_699.md5
new file mode 100644
index 0000000000000000000000000000000000000000..91f834694bc121a329a80b7979652c5ba634d076
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_699.md5
@@ -0,0 +1 @@
+85620a25c6e5a1b2097d3aff2eda268e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_7.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_7.md5
new file mode 100644
index 0000000000000000000000000000000000000000..2afd2b1701c06c09b3addfd3af8106671ce495d3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_7.md5
@@ -0,0 +1 @@
+500d2b6511f912ce11dd60908660ae73
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_708.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_708.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3a6d1ae2296d89d6e399a0e3db9ffdd080d21f03
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_708.md5
@@ -0,0 +1 @@
+c2085a77f333599b3e287604435136c4
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_714.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_714.md5
new file mode 100644
index 0000000000000000000000000000000000000000..63ac93df8b73fc20687f34e081d58c2c0fdac09d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_714.md5
@@ -0,0 +1 @@
+571d7e3f9581952cdc7d20a736eb7059
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_715.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_715.md5
new file mode 100644
index 0000000000000000000000000000000000000000..8dc21a6c3ac9ab2d363cbbaf6c6a1964ae0cf15e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_715.md5
@@ -0,0 +1 @@
+022c7d6684f89c39a4ade4a4dcffee7e
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_724.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_724.md5
new file mode 100644
index 0000000000000000000000000000000000000000..9e094d544e6f4b697327fd312cfa5faba0efdaaa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_724.md5
@@ -0,0 +1 @@
+dc7073c46acd2d2afad7f3fcdaf95fdf
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_758.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_758.md5
new file mode 100644
index 0000000000000000000000000000000000000000..cd9dd6fd876f093fea10e64c38eda5ad7d393c1e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_758.md5
@@ -0,0 +1 @@
+41b2c09ef14a8596d46c72efda62f54c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_85.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_85.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b702c07e83fd52419f087bdc2751ba6c17c50031
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inherit_graph_85.md5
@@ -0,0 +1 @@
+c67414e16e800e23f8b98373e6116ddf
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inner__product_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inner__product_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..9eac70c804418bdefea828bfe5a84136dbaaac25
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/inner__product_8h.html
@@ -0,0 +1,157 @@
+
+
+
+
+
+
+CUTLASS: inner_product.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Reference implementation for GEMM in host-side code.
+More...
+
+
Go to the source code of this file.
+
+
+template<typename Atype , typename Btype , typename Ctype >
+CUTLASS_HOST_DEVICE Ctype cutlass::reference::detail::inner_product (Atype a, Btype b, Ctype c)
+ Template function to compute an inner product. More...
+
+template<>
+CUTLASS_HOST_DEVICE int cutlass::reference::detail::inner_product< Array< bin1_t, 32 >, Array< bin1_t, 32 >, int > (Array< bin1_t, 32 > a, Array< bin1_t, 32 > b, int c)
+ Specialization for matrix multiplication with binary operands. More...
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/integer__subbyte_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/integer__subbyte_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..1ba72fa187ffab4355dcff9220bfe3ffc7914657
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/integer__subbyte_8h__dep__incl.md5
@@ -0,0 +1 @@
+668633bcafd462d287ca8accb6a3796b
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..9afe8bed2dc6cd67b2fa3e305f3b20b13b13ac28
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h.html
@@ -0,0 +1,398 @@
+
+
+
+
+
+
+CUTLASS: library.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
CUTLASS Library is an object-oriented approach to managing operations implemented by CUTLASS.
+More...
+
#include <vector>
+
#include <string>
+
#include <cstdint>
+
#include <cuda_runtime.h>
+
#include "cutlass/cutlass.h "
+
#include "cutlass/matrix_coord.h "
+
#include "cutlass/tensor_coord.h "
+
#include "cutlass/layout/tensor.h "
+
#include "cutlass/gemm/gemm.h "
+
+
Go to the source code of this file.
+
+
+enum cutlass::library::LayoutTypeID {
+ cutlass::library::LayoutTypeID::kUnknown ,
+cutlass::library::LayoutTypeID::kColumnMajor ,
+cutlass::library::LayoutTypeID::kRowMajor ,
+cutlass::library::LayoutTypeID::kColumnMajorInterleavedK4 ,
+
+ cutlass::library::LayoutTypeID::kRowMajorInterleavedK4 ,
+cutlass::library::LayoutTypeID::kColumnMajorInterleavedK16 ,
+cutlass::library::LayoutTypeID::kRowMajorInterleavedK16 ,
+cutlass::library::LayoutTypeID::kTensorNCHW ,
+
+ cutlass::library::LayoutTypeID::kTensorNHWC ,
+cutlass::library::LayoutTypeID::kInvalid
+
+ } Layout type identifier. More...
+
+
+enum cutlass::library::NumericTypeID {
+ cutlass::library::NumericTypeID::kUnknown ,
+cutlass::library::NumericTypeID::kVoid ,
+cutlass::library::NumericTypeID::kB1 ,
+cutlass::library::NumericTypeID::kU4 ,
+
+ cutlass::library::NumericTypeID::kU8 ,
+cutlass::library::NumericTypeID::kU16 ,
+cutlass::library::NumericTypeID::kU32 ,
+cutlass::library::NumericTypeID::kU64 ,
+
+ cutlass::library::NumericTypeID::kS4 ,
+cutlass::library::NumericTypeID::kS8 ,
+cutlass::library::NumericTypeID::kS16 ,
+cutlass::library::NumericTypeID::kS32 ,
+
+ cutlass::library::NumericTypeID::kS64 ,
+cutlass::library::NumericTypeID::kF16 ,
+cutlass::library::NumericTypeID::kF32 ,
+cutlass::library::NumericTypeID::kF64 ,
+
+ cutlass::library::NumericTypeID::kCF16 ,
+cutlass::library::NumericTypeID::kCF32 ,
+cutlass::library::NumericTypeID::kCF64 ,
+cutlass::library::NumericTypeID::kCS4 ,
+
+ cutlass::library::NumericTypeID::kCS8 ,
+cutlass::library::NumericTypeID::kCS16 ,
+cutlass::library::NumericTypeID::kCS32 ,
+cutlass::library::NumericTypeID::kCS64 ,
+
+ cutlass::library::NumericTypeID::kCU4 ,
+cutlass::library::NumericTypeID::kCU8 ,
+cutlass::library::NumericTypeID::kCU16 ,
+cutlass::library::NumericTypeID::kCU32 ,
+
+ cutlass::library::NumericTypeID::kCU64 ,
+cutlass::library::NumericTypeID::kInvalid
+
+ } Numeric data type. More...
+
+
+enum cutlass::library::ComplexTransform { cutlass::library::ComplexTransform::kNone ,
+cutlass::library::ComplexTransform::kConjugate
+ } Enumeraed type describing a transformation on a complex value. More...
+
+
+enum cutlass::library::OperationKind { cutlass::library::OperationKind::kGemm ,
+cutlass::library::OperationKind::kInvalid
+ } Enumeration indicating the kind of operation. More...
+
+
+enum cutlass::library::ScalarPointerMode { cutlass::library::ScalarPointerMode::kHost ,
+cutlass::library::ScalarPointerMode::kDevice ,
+cutlass::library::ScalarPointerMode::kInvalid
+ } Enumeration indicating whether scalars are in host or device memory. More...
+
+
+enum cutlass::library::SplitKMode {
+ cutlass::library::SplitKMode::kNone ,
+cutlass::library::SplitKMode::kSerial ,
+cutlass::library::SplitKMode::kParallel ,
+cutlass::library::SplitKMode::kParallelSerial ,
+
+ cutlass::library::SplitKMode::kInvalid
+
+ } Describes how reductions are performed across threadblocks. More...
+
+
+enum cutlass::library::OpcodeClassID { cutlass::library::OpcodeClassID::kSimt ,
+cutlass::library::OpcodeClassID::kTensorOp ,
+cutlass::library::OpcodeClassID::kWmmaTensorOp ,
+cutlass::library::OpcodeClassID::kInvalid
+ } Indicates the classificaition of the math instruction. More...
+
+
+enum cutlass::library::GemmKind {
+ cutlass::library::GemmKind::kGemm ,
+cutlass::library::GemmKind::kBatched ,
+cutlass::library::GemmKind::kArray ,
+cutlass::library::GemmKind::kPlanarComplex ,
+
+ cutlass::library::GemmKind::kPlanarComplexBatched ,
+cutlass::library::GemmKind::kInvalid
+
+ } Enumeration indicating what kind of GEMM operation to perform. More...
+
+
+
+
+template<typename T >
+T cutlass::library::from_string (std::string const &)
+ Lexical cast from string. More...
+
+char const * cutlass::library::to_string (OperationKind type, bool pretty=false)
+ Converts a NumericType enumerant to a string. More...
+
+template<>
+OperationKind cutlass::library::from_string< OperationKind > (std::string const &str)
+ Parses a NumericType enumerant from a string. More...
+
+char const * cutlass::library::to_string (NumericTypeID type, bool pretty=false)
+ Converts a NumericType enumerant to a string. More...
+
+template<>
+NumericTypeID cutlass::library::from_string< NumericTypeID > (std::string const &str)
+ Parses a NumericType enumerant from a string. More...
+
+int cutlass::library::sizeof_bits (NumericTypeID type)
+ Returns the size of a data type in bits. More...
+
+bool cutlass::library::is_complex_type (NumericTypeID type)
+ Returns true if the numeric type is a complex data type or false if real-valued. More...
+
+NumericTypeID cutlass::library::get_real_type (NumericTypeID type)
+ Returns the real-valued type underlying a type (only different from 'type' if complex) More...
+
+bool cutlass::library::is_integer_type (NumericTypeID type)
+ Returns true if numeric type is integer. More...
+
+bool cutlass::library::is_signed_type (NumericTypeID type)
+ Returns true if numeric type is signed. More...
+
+bool cutlass::library::is_signed_integer (NumericTypeID type)
+ Returns true if numeric type is a signed integer. More...
+
+bool cutlass::library::is_unsigned_integer (NumericTypeID type)
+ returns true if numeric type is an unsigned integer More...
+
+bool cutlass::library::is_float_type (NumericTypeID type)
+ Returns true if numeric type is floating-point type. More...
+
+char const * cutlass::library::to_string (Status status, bool pretty=false)
+ To string method for cutlass::Status . More...
+
+char const * cutlass::library::to_string (LayoutTypeID layout, bool pretty=false)
+ Converts a LayoutTypeID enumerant to a string. More...
+
+template<>
+LayoutTypeID cutlass::library::from_string< LayoutTypeID > (std::string const &str)
+ Parses a LayoutType enumerant from a string. More...
+
+int cutlass::library::get_layout_stride_rank (LayoutTypeID layout_id)
+ Returns the rank of a layout's stride base on the LayoutTypeID. More...
+
+char const * cutlass::library::to_string (OpcodeClassID type, bool pretty=false)
+ Converts a OpcodeClassID enumerant to a string. More...
+
+template<>
+OpcodeClassID cutlass::library::from_string< OpcodeClassID > (std::string const &str)
+ Converts a OpcodeClassID enumerant from a string. More...
+
+std::string cutlass::library::lexical_cast (int64_t int_value)
+ Lexical cast from int64_t to string. More...
+
+bool cutlass::library::lexical_cast (std::vector< uint8_t > &bytes, NumericTypeID type, std::string const &str)
+ Lexical cast a string to a byte array. Returns true if cast is successful or false if invalid. More...
+
+std::string cutlass::library::lexical_cast (std::vector< uint8_t > &bytes, NumericTypeID type)
+ Lexical cast TO a string FROM a byte array. Returns true if cast is successful or false if invalid. More...
+
+bool cutlass::library::cast_from_int64 (std::vector< uint8_t > &bytes, NumericTypeID type, int64_t src)
+ Casts from a signed int64 to the destination type. Returns true if successful. More...
+
+bool cutlass::library::cast_from_uint64 (std::vector< uint8_t > &bytes, NumericTypeID type, uint64_t src)
+ Casts from an unsigned int64 to the destination type. Returns true if successful. More...
+
+bool cutlass::library::cast_from_double (std::vector< uint8_t > &bytes, NumericTypeID type, double src)
+ Casts from a real value represented as a double to the destination type. Returns true if successful. More...
+
+
+
+
Generally,
+
description - compile-time constant parameters used to instantiate an operation
+
configuration - runtime parameters with computationally expensive initialization
+
arguments - runtime parameters that may be passed to an initialized operation with low computational overhead
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..b8633aecfb432667f0cfd88d6da03bc75bd65347
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/library_8h_source.html
@@ -0,0 +1,299 @@
+
+
+
+
+
+
+CUTLASS: library.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 47 #include <cuda_runtime.h> 161 template <
typename T> T
from_string (std::string
const &);
258 instruction_shape(instruction_shape), element_accumulator(element_accumulator), opcode_class(opcode_class) {}
289 int threadblock_stages = 0,
292 int minimum_compute_capability = 0,
293 int maximum_compute_capability = 0
295 threadblock_shape(threadblock_shape),
296 threadblock_stages(threadblock_stages),
297 warp_count(warp_count),
298 math_instruction(math_instruction),
299 minimum_compute_capability(minimum_compute_capability),
300 maximum_compute_capability(maximum_compute_capability) { }
319 char const * name =
"unknown" ,
323 name(name), kind(kind), tile_description(tile_description) { }
351 int log_extent_range = 24,
352 int log_stride_range = 24
356 alignment(alignment),
357 log_extent_range(log_extent_range),
358 log_stride_range(log_stride_range) { }
404 gemm_kind(gemm_kind),
408 element_epilogue(element_epilogue),
409 split_k_mode(split_k_mode),
410 transform_A(transform_A),
411 transform_B(transform_B) {}
425 virtual Status can_implement(
426 void const *configuration,
427 void const *arguments)
const = 0;
429 virtual uint64_t get_host_workspace_size(
430 void const *configuration)
const = 0;
432 virtual uint64_t get_device_workspace_size(
433 void const *configuration)
const = 0;
435 virtual Status initialize(
436 void const *configuration,
437 void *host_workspace,
438 void *device_workspace,
439 cudaStream_t stream =
nullptr )
const = 0;
442 void const *arguments,
443 void *host_workspace,
444 void *device_workspace =
nullptr ,
445 cudaStream_t stream =
nullptr )
const = 0;
565 void const *
const *
A ;
566 void const *
const *
B ;
567 void const *
const *
C ;
int64_t lda
Definition: library.h:609
+
+
int alignment
Alignment restriction on pointers, strides, and extents.
Definition: library.h:336
+
+
void const *const * A
Definition: library.h:565
+
+
+
+
virtual ~Operation()
Definition: library.h:421
+
High-level description of an operation.
Definition: library.h:304
+
+
+
char const * to_string(OperationKind type, bool pretty=false)
Converts a NumericType enumerant to a string.
+
Definition: aligned_buffer.h:35
+
bool is_complex_type(NumericTypeID type)
Returns true if the numeric type is a complex data type or false if real-valued.
+
void *const * D
Definition: library.h:568
+
LayoutTypeID layout
Enumerant identifying the layout function for the tensor.
Definition: library.h:333
+
GemmKind gemm_kind
Indicates the kind of GEMM performed.
Definition: library.h:367
+
int64_t ldc
Definition: library.h:587
+
Arguments for GEMM.
Definition: library.h:477
+
+
int batch_count
Definition: library.h:560
+
ComplexTransform
Enumeraed type describing a transformation on a complex value.
Definition: library.h:111
+
+
void const *const * C
Definition: library.h:567
+
gemm::GemmCoord problem_size
Definition: library.h:583
+
Configuration for batched GEMM in which multiple matrix products are computed.
Definition: library.h:551
+
bool is_signed_integer(NumericTypeID type)
Returns true if numeric type is a signed integer.
+
GemmKind
Enumeration indicating what kind of GEMM operation to perform.
Definition: library.h:149
+
+
+
NumericTypeID get_real_type(NumericTypeID type)
Returns the real-valued type underlying a type (only different from 'type' if complex) ...
+
OperationKind from_string< OperationKind >(std::string const &str)
Parses a NumericType enumerant from a string.
+
Definition: include/cutlass/gemm/gemm.h:94
+
int get_layout_stride_rank(LayoutTypeID layout_id)
Returns the rank of a layout's stride base on the LayoutTypeID.
+
int64_t ldb
Leading dimension of B matrix.
Definition: library.h:517
+
+
+
+
int64_t const * ldc
Definition: library.h:557
+
+
+
int64_t batched_stride_B
Definition: library.h:620
+
Complex valued GEMM in which real and imaginary parts are separated by a stride.
Definition: library.h:581
+
int log_stride_range
log2() of the maximum value each relevant stride may have
Definition: library.h:342
+
+
+
Defines common types used for all GEMM-like operators.
+
ComplexTransform transform_A
Transformation on A operand.
Definition: library.h:385
+
+
+
int64_t imag_stride_B
Definition: library.h:615
+
GemmDescription(GemmKind gemm_kind=GemmKind::kGemm, TensorDescription const &A=TensorDescription(), TensorDescription const &B=TensorDescription(), TensorDescription const &C=TensorDescription(), NumericTypeID element_epilogue=NumericTypeID::kInvalid, SplitKMode split_k_mode=SplitKMode::kNone, ComplexTransform transform_A=ComplexTransform::kNone, ComplexTransform transform_B=ComplexTransform::kNone)
Definition: library.h:394
+
int sizeof_bits(NumericTypeID type)
Returns the size of a data type in bits.
+
Base class for all device-wide operations.
Definition: library.h:418
+
int64_t imag_stride_A
Definition: library.h:590
+
+
NumericTypeID from_string< NumericTypeID >(std::string const &str)
Parses a NumericType enumerant from a string.
+
LayoutTypeID
Layout type identifier.
Definition: library.h:63
+
OpcodeClassID
Indicates the classificaition of the math instruction.
Definition: library.h:139
+
int64_t ldc
Definition: library.h:611
+
std::string lexical_cast(int64_t int_value)
Lexical cast from int64_t to string.
+
ScalarPointerMode pointer_mode
Enumerant indicating whether alpha/beta point to host or device memory.
Definition: library.h:498
+
int64_t const * ldb
Definition: library.h:556
+
gemm::GemmCoord problem_size
Definition: library.h:553
+
int64_t batched_stride_C
Definition: library.h:621
+
OperationDescription(char const *name="unknown", OperationKind kind=OperationKind::kInvalid, TileDescription const &tile_description=TileDescription())
Definition: library.h:318
+
int maximum_compute_capability
Minimum compute capability (e.g. 70, 75) of a device eligible to run the operation.
Definition: library.h:281
+
+
Configuration for basic GEMM operations.
Definition: library.h:455
+
int64_t imag_stride_D
Definition: library.h:617
+
Definition: library.h:238
+
void const * B
Pointer to B matrix.
Definition: library.h:483
+
int64_t imag_stride_A
Definition: library.h:614
+
+
+
TensorDescription A
Describes the A operand.
Definition: library.h:370
+
Structure describing the tiled structure of a GEMM-like computation.
Definition: library.h:263
+
int split_k_slices
Number of partitions of K dimension.
Definition: library.h:473
+
int64_t imag_stride_B
Definition: library.h:591
+
OpcodeClassID from_string< OpcodeClassID >(std::string const &str)
Converts a OpcodeClassID enumerant from a string.
+
+
void const * A
Pointer to A matrix.
Definition: library.h:480
+
Defines layout functions used by TensorRef and derived classes for common 4-D and 5-D tensor formats...
+
int64_t ldd
Leading dimension of D matrix.
Definition: library.h:470
+
ComplexTransform transform_B
Transformation on B operand.
Definition: library.h:388
+
int64_t ldb
Definition: library.h:610
+
bool is_signed_type(NumericTypeID type)
Returns true if numeric type is signed.
+
+
NumericTypeID element_epilogue
Describes the data type of the scalars passed to the epilogue.
Definition: library.h:379
+
int64_t const * lda
Definition: library.h:555
+
+
int64_t const * ldd
Definition: library.h:558
+
int minimum_compute_capability
Minimum compute capability (e.g. 70, 75) of a device eligible to run the operation.
Definition: library.h:278
+
int64_t ldd
Definition: library.h:588
+
int64_t batch_stride_C
Stride between instances of the C matrix in memory.
Definition: library.h:532
+
void const *const * B
Definition: library.h:566
+
NumericTypeID
Numeric data type.
Definition: library.h:77
+
int64_t lda
Definition: library.h:585
+
cutlass::gemm::GemmCoord warp_count
Number of warps in each logical dimension.
Definition: library.h:272
+
int64_t lda
Leading dimension of A matrix.
Definition: library.h:461
+
bool is_float_type(NumericTypeID type)
Returns true if numeric type is floating-point type.
+
+
TileDescription(cutlass::gemm::GemmCoord threadblock_shape=cutlass::gemm::GemmCoord(), int threadblock_stages=0, cutlass::gemm::GemmCoord warp_count=cutlass::gemm::GemmCoord(), MathInstructionDescription math_instruction=MathInstructionDescription(), int minimum_compute_capability=0, int maximum_compute_capability=0)
Definition: library.h:287
+
bool cast_from_double(std::vector< uint8_t > &bytes, NumericTypeID type, double src)
Casts from a real value represented as a double to the destination type. Returns true if successful...
+
+
NumericTypeID element_accumulator
Describes the data type of the internal accumulator.
Definition: library.h:244
+
Defines a canonical coordinate for rank=4 tensors offering named indices.
+
TensorDescription B
Describes the B operand.
Definition: library.h:373
+
+
void const * alpha
Definition: library.h:569
+
+
void const * beta
Host or device pointer to beta scalar.
Definition: library.h:495
+
+
int64_t ldd
Leading dimension of D matrix.
Definition: library.h:523
+
OpcodeClassID opcode_class
Classification of math instruction.
Definition: library.h:247
+
+
gemm::GemmCoord problem_size
GEMM problem size.
Definition: library.h:511
+
int64_t ldc
Leading dimension of C matrix.
Definition: library.h:467
+
+
+
void * D
Pointer to D matrix.
Definition: library.h:489
+
bool cast_from_uint64(std::vector< uint8_t > &bytes, NumericTypeID type, uint64_t src)
Casts from an unsigned int64 to the destination type. Returns true if successful. ...
+
TensorDescription C
Describes the source and destination matrices.
Definition: library.h:376
+
int64_t ldb
Definition: library.h:586
+
int64_t imag_stride_C
Definition: library.h:616
+
Batched complex valued GEMM in which real and imaginary parts are separated by a stride.
Definition: library.h:605
+
+
int64_t batched_stride_D
Definition: library.h:622
+
Configuration for batched GEMM in which multiple matrix products are computed.
Definition: library.h:508
+
+
+
int64_t batch_stride_A
Stride between instances of the A matrix in memory.
Definition: library.h:526
+
bool is_integer_type(NumericTypeID type)
Returns true if numeric type is integer.
+
ScalarPointerMode
Enumeration indicating whether scalars are in host or device memory.
Definition: library.h:123
+
NumericTypeID element
Numeric type of an individual element.
Definition: library.h:330
+
+
int batch_count
Number of GEMMs in batch.
Definition: library.h:538
+
void const * C
Pointer to C matrix.
Definition: library.h:486
+
T from_string(std::string const &)
Lexical cast from string.
+
int threadblock_stages
Describes the number of pipeline stages in the threadblock-scoped mainloop.
Definition: library.h:269
+
Defines a canonical coordinate for rank=2 matrices offering named indices.
+
int64_t imag_stride_D
Definition: library.h:593
+
+
+
LayoutTypeID from_string< LayoutTypeID >(std::string const &str)
Parses a LayoutType enumerant from a string.
+
ScalarPointerMode pointer_mode
Definition: library.h:571
+
MathInstructionDescription(cutlass::gemm::GemmCoord instruction_shape=cutlass::gemm::GemmCoord(), NumericTypeID element_accumulator=NumericTypeID::kInvalid, OpcodeClassID opcode_class=OpcodeClassID::kInvalid)
Definition: library.h:253
+
int64_t batched_stride_A
Definition: library.h:619
+
Description of all GEMM computations.
Definition: library.h:364
+
int64_t lda
Leading dimension of A matrix.
Definition: library.h:514
+
gemm::GemmCoord problem_size
GEMM problem size.
Definition: library.h:458
+
SplitKMode split_k_mode
Describes the structure of parallel reductions.
Definition: library.h:382
+
bool cast_from_int64(std::vector< uint8_t > &bytes, NumericTypeID type, int64_t src)
Casts from a signed int64 to the destination type. Returns true if successful.
+
int log_extent_range
log2() of the maximum extent of each dimension
Definition: library.h:339
+
char const * name
Unique identifier describing the operation.
Definition: library.h:307
+
int64_t batch_stride_B
Stride between instances of the B matrix in memory.
Definition: library.h:529
+
cutlass::gemm::GemmCoord instruction_shape
Shape of the target math instruction.
Definition: library.h:241
+
void const * beta
Definition: library.h:570
+
TileDescription tile_description
Describes the tiled structure of a GEMM-like computation.
Definition: library.h:313
+
+
+
int64_t ldc
Leading dimension of C matrix.
Definition: library.h:520
+
Structure describing the properties of a tensor.
Definition: library.h:327
+
int64_t ldb
Leading dimension of B matrix.
Definition: library.h:464
+
gemm::GemmCoord problem_size
Definition: library.h:607
+
bool is_unsigned_integer(NumericTypeID type)
returns true if numeric type is an unsigned integer
+
Arguments for GEMM - used by all the GEMM operations.
Definition: library.h:564
+
+
+
+
OperationKind
Enumeration indicating the kind of operation.
Definition: library.h:117
+
void const * alpha
Host or device pointer to alpha scalar.
Definition: library.h:492
+
+
OperationKind kind
Kind of operation.
Definition: library.h:310
+
cutlass::gemm::GemmCoord threadblock_shape
Describes the shape of a threadblock (in elements)
Definition: library.h:266
+
int64_t ldd
Definition: library.h:612
+
+
+
+
int64_t imag_stride_C
Definition: library.h:592
+
MathInstructionDescription math_instruction
Core math instruction.
Definition: library.h:275
+
Basic include for CUTLASS.
+
SplitKMode
Describes how reductions are performed across threadblocks.
Definition: library.h:130
+
+
+
Status
Status code returned by CUTLASS operations.
Definition: cutlass.h:39
+
int64_t batch_stride_D
Stride between instances of the D matrix in memory.
Definition: library.h:535
+
+
TensorDescription(NumericTypeID element=NumericTypeID::kInvalid, LayoutTypeID layout=LayoutTypeID::kInvalid, int alignment=1, int log_extent_range=24, int log_stride_range=24)
Definition: library.h:347
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/linear__combination_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/linear__combination_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..521f6c62a9d6b88440821b901d79e2a15bfcd43b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/linear__combination_8h_source.html
@@ -0,0 +1,143 @@
+
+
+
+
+
+
+CUTLASS: linear_combination.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 50 typename ElementOutput_,
52 typename ElementAccumulator_ = ElementOutput_,
53 typename ElementCompute_ = ElementOutput_,
94 ): alpha(alpha), beta(beta), alpha_ptr(
nullptr ), beta_ptr(
nullptr ) {
102 ): alpha(0), beta(0), alpha_ptr(alpha_ptr), beta_ptr(beta_ptr) {
151 ComputeFragment converted_accumulator = accumulator_converter(accumulator);
160 intermediate = mul_add_source(beta_, converted_source);
161 intermediate = mul_add_accumulator(alpha_, converted_accumulator, intermediate);
166 return destination_converter(intermediate);
Fused multiply-add.
Definition: functional.h:92
+
Definition: aligned_buffer.h:35
+
Definition: linear_combination.h:56
+
static int const kCount
Definition: linear_combination.h:63
+
ElementCompute alpha
scales accumulators
Definition: linear_combination.h:74
+
ElementCompute const * alpha_ptr
pointer to accumulator scalar - if not null, loads it from memory
Definition: linear_combination.h:76
+
Array< ElementAccumulator, kCount > FragmentAccumulator
Definition: linear_combination.h:66
+
CUTLASS_HOST_DEVICE void set_k_partition(int k_partition)
Functionally required for serial reduction in the epilogue.
Definition: linear_combination.h:134
+
Array< ElementCompute, kCount > ComputeFragment
Definition: linear_combination.h:67
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
static FloatRoundStyle const kRound
Definition: linear_combination.h:69
+
ElementAccumulator_ ElementAccumulator
Definition: linear_combination.h:60
+
CUTLASS_HOST_DEVICE FragmentOutput operator()(FragmentAccumulator const &accumulator, FragmentOutput const &source) const
Computes linear scaling: D = alpha * accumulator + beta * source.
Definition: linear_combination.h:142
+
ElementOutput_ ElementOutput
Definition: linear_combination.h:59
+
Boost-like numeric conversion operator for CUTLASS numeric types.
+
+
CUTLASS_HOST_DEVICE Params()
Definition: linear_combination.h:84
+
CUTLASS_HOST_DEVICE LinearCombination(Params const ¶ms)
Constructs the function object, possibly loading from pointers in host memory.
Definition: linear_combination.h:120
+
Definition: functional.h:64
+
CUTLASS_HOST_DEVICE Params(ElementCompute alpha, ElementCompute beta)
Definition: linear_combination.h:91
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
Array< ElementOutput, kCount > FragmentOutput
Definition: linear_combination.h:65
+
+
ElementCompute beta
scales source tensor
Definition: linear_combination.h:75
+
CUTLASS_HOST_DEVICE Params(ElementCompute const *alpha_ptr, ElementCompute const *beta_ptr)
Definition: linear_combination.h:99
+
FloatRoundStyle
Definition: numeric_conversion.h:43
+
ElementCompute_ ElementCompute
Definition: linear_combination.h:61
+
Conversion operator for Array.
Definition: numeric_conversion.h:294
+
Basic include for CUTLASS.
+
Host-constructable parameters structure.
Definition: linear_combination.h:72
+
Define basic numeric operators with specializations for Array<T, N>. SIMD-ize where possible...
+
CUTLASS_HOST_DEVICE bool is_source_needed() const
Returns true if source is needed.
Definition: linear_combination.h:128
+
ElementCompute const * beta_ptr
pointer to source scalar - if not null, loads it from memory
Definition: linear_combination.h:77
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/manifest_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/manifest_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..48690a250037ec80c0da5026cd58c482b55299a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/manifest_8h_source.html
@@ -0,0 +1,122 @@
+
+
+
+
+
+
+CUTLASS: manifest.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 67 void reserve (
size_t operation_count);
79 OperationVector::const_iterator
begin ()
const ;
82 OperationVector::const_iterator
end ()
const ;
Definition: aligned_buffer.h:35
+
void append(Operation *operation_ptr)
Appends an operation and takes ownership.
+
Base class for all device-wide operations.
Definition: library.h:418
+
Manifest of CUTLASS Library.
Definition: manifest.h:55
+
CUTLASS Library is an object-oriented approach to managing operations implemented by CUTLASS...
+
OperationVector const & operations() const
Returns an iterator to the first operation.
+
std::vector< std::unique_ptr< Operation >> OperationVector
List of operations.
Definition: manifest.h:50
+
Status release()
Graceful shutdown.
+
Status initialize()
Top-level initialization.
+
void reserve(size_t operation_count)
Used for initialization.
+
OperationVector::const_iterator end() const
Returns a const iterator.
+
Status
Status code returned by CUTLASS operations.
Definition: cutlass.h:39
+
OperationVector::const_iterator begin() const
Returns a const iterator.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/memory_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/memory_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..8276a8939e1ea234b993f866788f24b515f777d9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/memory_8h__incl.md5
@@ -0,0 +1 @@
+8ff643e52a1d0d31036b2ecaed2392c0
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b2d034b4179de959379358877eb51aaa7abea302
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h__incl.md5
@@ -0,0 +1 @@
+e305f10dc66e47db305400fedef3a425
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..08ea72e92ed2e522f4ffc92c113726f26d9b3700
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__pipelined_8h_source.html
@@ -0,0 +1,147 @@
+
+
+
+
+
+
+CUTLASS: mma_pipelined.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 46 namespace threadblock {
59 typename SmemIteratorA_,
65 typename SmemIteratorB_,
73 typename TransformA_ = NumericArrayConverter<
74 typename SmemIteratorA_::Element,
75 typename IteratorA_::Element,
76 IteratorA_::Fragment::kElements>,
79 typename TransformB_ = NumericArrayConverter<
80 typename SmemIteratorB_::Element,
81 typename IteratorB_::Element,
82 IteratorB_::Fragment::kElements>,
84 typename Enable =
bool 126 using WarpFragmentA =
typename Operator::FragmentA;
127 using WarpFragmentB =
typename Operator::FragmentB;
142 typename Base::SharedStorage &shared_storage,
147 Base (shared_storage, thread_idx, warp_idx, lane_idx),
148 smem_iterator_A_(shared_storage.operand_A_ref(), thread_idx),
149 smem_iterator_B_(shared_storage.operand_B_ref(), thread_idx) {
171 int gemm_k_iterations,
193 iterator_A.load(tb_frag_A);
194 iterator_B.load(tb_frag_B);
199 this->smem_iterator_A_.store(transform_A(tb_frag_A));
200 this->smem_iterator_B_.store(transform_B(tb_frag_B));
208 WarpFragmentA warp_frag_A[2];
209 WarpFragmentB warp_frag_B[2];
222 int smem_write_stage_idx = 1;
225 if (gemm_k_iterations <= 1) {
226 iterator_A.clear_mask();
227 iterator_B.clear_mask();
239 for (; gemm_k_iterations > 0; --gemm_k_iterations) {
250 if (warp_mma_k == Base::kWarpGemmIterations - 1) {
253 this->smem_iterator_A_.store(transform_A(tb_frag_A));
255 this->smem_iterator_B_.store(transform_B(tb_frag_B));
263 if (smem_write_stage_idx == 1) {
269 {0, -
Base::kStages * Policy::kPartitionsK * Base::kWarpGemmIterations});
275 smem_write_stage_idx ^= 1;
287 if (warp_mma_k == 0) {
289 iterator_A.load(tb_frag_A);
290 iterator_B.load(tb_frag_B);
296 if (gemm_k_iterations <= 2) {
297 iterator_A.clear_mask();
298 iterator_B.clear_mask();
302 warp_mma(accum, warp_frag_A[warp_mma_k % 2], warp_frag_B[warp_mma_k % 2], accum);
static int const kM
Definition: include/cutlass/gemm/gemm.h:58
+
LayoutC_ LayoutC
Layout of accumulator matrix.
Definition: mma_pipelined.h:96
+
TransformB_ TransformB
Definition: mma_pipelined.h:103
+
Definition: aligned_buffer.h:35
+
Policy_ Policy
Policy describing tuning details.
Definition: mma_pipelined.h:97
+
Operator::IteratorB warp_tile_iterator_B_
Iterator to load a warp-scoped tile of B operand from shared memory.
Definition: mma_base.h:193
+
Structure to compute the matrix product targeting CUDA cores and SIMT math instructions.
Definition: mma_pipelined.h:86
+
IteratorB_ IteratorB
Iterates over tiles of B operand in global memory.
Definition: mma_pipelined.h:94
+
Defines common types used for all GEMM-like operators.
+
CUTLASS_DEVICE void operator()(int gemm_k_iterations, FragmentC &accum, IteratorA iterator_A, IteratorB iterator_B, FragmentC const &src_accum, TransformA transform_A=TransformA(), TransformB transform_B=TransformB())
Perform a threadblock-scoped matrix multiply-accumulate.
Definition: mma_pipelined.h:170
+
IteratorA_ IteratorA
Iterates over tiles of A operand in global memory.
Definition: mma_pipelined.h:93
+
typename IteratorB::Fragment FragmentB
Fragment of operand B loaded from global memory.
Definition: mma_pipelined.h:113
+
SmemIteratorA_ SmemIteratorA
Definition: mma_pipelined.h:99
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
Boost-like numeric conversion operator for CUTLASS numeric types.
+
Defines a Shape template for matrix tiles.
+
static int const kWarpGemmIterations
Number of warp-level GEMM oeprations.
Definition: mma_base.h:108
+
Template for a double-buffered threadblock-scoped GEMM kernel.
+
AlignedBuffer is a container for trivially copyable elements suitable for use in unions and shared me...
+
Shape_ Shape
Size of the Gemm problem - concept: gemm::GemmShape<>
Definition: mma_pipelined.h:92
+
static int const kStages
Number of stages.
Definition: mma_base.h:112
+
typename IteratorA::Fragment FragmentA
Fragment of operand A loaded from global memory.
Definition: mma_pipelined.h:110
+
Top-level include for all CUTLASS numeric types.
+
+
Definition: mma_base.h:83
+
typename Policy::Operator::FragmentC FragmentC
Fragment of accumulator tile.
Definition: mma_pipelined.h:116
+
Operator::IteratorA warp_tile_iterator_A_
Iterator to load a warp-scoped tile of A operand from shared memory.
Definition: mma_base.h:190
+
#define CUTLASS_GEMM_LOOP
Definition: cutlass.h:112
+
ElementC_ ElementC
Data type of accumulator matrix.
Definition: mma_pipelined.h:95
+
SmemIteratorA smem_iterator_A_
Iterator to write threadblock-scoped tile of A operand to shared memory.
Definition: mma_pipelined.h:132
+
SmemIteratorB_ SmemIteratorB
Definition: mma_pipelined.h:100
+
SmemIteratorB smem_iterator_B_
Iterator to write threadblock-scoped tile of B operand to shared memory.
Definition: mma_pipelined.h:135
+
CUTLASS_DEVICE MmaPipelined(typename Base::SharedStorage &shared_storage, int thread_idx, int warp_idx, int lane_idx)
Construct from tensor references.
Definition: mma_pipelined.h:141
+
Basic include for CUTLASS.
+
TransformA_ TransformA
Definition: mma_pipelined.h:102
+
typename Policy::Operator Operator
Warp-level Mma.
Definition: mma_pipelined.h:119
+
static int const kN
Definition: include/cutlass/gemm/gemm.h:59
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__simt__policy_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__simt__policy_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..30f1ad0a46902fce2cd0e8d3dc737e6b670b3460
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__simt__policy_8h__dep__incl.md5
@@ -0,0 +1 @@
+b8ccdb3a33f98ea6ad1ab7c4011e8506
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..12803530181ebd460663bea7922b08b51048e35f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h.html
@@ -0,0 +1,157 @@
+
+
+
+
+
+
+CUTLASS: mma_tensor_op.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Templates implementing warp-level matrix multiply-accumulate operations targeting Tensor Cores.
+More...
+
+
Go to the source code of this file.
+
+
+class cutlass::gemm::warp::MmaTensorOp< Shape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_, Policy_, PartitionsK_, AccumulatorsInRowMajor, PartitionsN_, Enable >
+ Structure to compute the matrix product targeting CUDA cores and SIMT math instructions. More...
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..fdc52c640fdb671a9d1a20a37b439b42443606a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op_8h__incl.md5
@@ -0,0 +1 @@
+0784d947b64ec9842a0a6669698539f5
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__policy_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__policy_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..98e98aad71962fd6780d6631a2c8460d06d8175a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__policy_8h_source.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: mma_tensor_op_policy.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. typename Operator::Shape MmaShape
Definition: mma_tensor_op_policy.h:52
+
Definition: aligned_buffer.h:35
+
Operator_ Operator
hardware instruction(s) performing TensorOp (concept: arch::Mma)
Definition: mma_tensor_op_policy.h:50
+
Defines common types used for all GEMM-like operators.
+
Defines a Shape template for matrix tiles.
+
Policy.
Definition: mma_tensor_op_policy.h:48
+
Basic include for CUTLASS.
+
OpDelta_ OpDelta
distance between operations (concept: MatrixShape)
Definition: mma_tensor_op_policy.h:51
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ccf43eff9ec4a641b9151a05de4da13afad1b8cd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__dep__incl.md5
@@ -0,0 +1 @@
+8e88225a1789cbee478e59a6cfbd2886
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..b2260012cfcdf6cfaedf4d54a9cccf26546fe17d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__sm70_8h__incl.md5
@@ -0,0 +1 @@
+5603f4b30bd3006330848bdc8164a218
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__tile__iterator__sm70_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__tile__iterator__sm70_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..e89713365d0688cdfd352b8eb24965fa30f4af6c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/mma__tensor__op__tile__iterator__sm70_8h.html
@@ -0,0 +1,184 @@
+
+
+
+
+
+
+CUTLASS: mma_tensor_op_tile_iterator_sm70.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Defines iterators used by warp-level matrix multiply operations targeting Tensor Cores.
+More...
+
+
Go to the source code of this file.
+
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand, Element_, Layout_, InstructionShape_, OpDelta_, Threads >
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >
+
+struct cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >::Policy
+ Internal structure of iterator - made public to enable introspection. More...
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::VoltaTensorOpMultiplicandBCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >
+
+struct cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::VoltaTensorOpMultiplicandBCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >::Policy
+ Internal structure of iterator - made public to enable introspection. More...
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::RowMajorVoltaTensorOpMultiplicandBCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >
+
+class cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >
+
+struct cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >::Policy
+ Internal structure of iterator - made public to enable introspection. More...
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::VoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >
+
+struct cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::VoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >::Policy
+ Internal structure of iterator - made public to enable introspection. More...
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >
+
+class cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::RowMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits< Element_ >::value, KBlock >, InstructionShape_, OpDelta_, 32 >
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/modules.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/modules.html
new file mode 100644
index 0000000000000000000000000000000000000000..dbcf45741776086173571d725245345571796b27
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/modules.html
@@ -0,0 +1,106 @@
+
+
+
+
+
+
+CUTLASS: Modules
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Here is a list of all modules:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1device__memory.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1device__memory.html
new file mode 100644
index 0000000000000000000000000000000000000000..6514090b7a4c307e1afbe70669ebb508e0bf11d5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1device__memory.html
@@ -0,0 +1,434 @@
+
+
+
+
+
+
+CUTLASS: cutlass::device_memory Namespace Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+struct allocation
+ Device allocation abstraction that tracks size and capacity. More...
+
+
+
+template<typename T >
+T * allocate (size_t count=1)
+ Allocate a buffer of count elements of type T on the current CUDA device. More...
+
+template<typename T >
+void free (T *ptr)
+ Free the buffer pointed to by ptr. More...
+
+template<typename T >
+void copy (T *dst, T const *src, size_t count, cudaMemcpyKind kind)
+
+template<typename T >
+void copy_to_device (T *dst, T const *src, size_t count=1)
+
+template<typename T >
+void copy_to_host (T *dst, T const *src, size_t count=1)
+
+template<typename T >
+void copy_device_to_device (T *dst, T const *src, size_t count=1)
+
+template<typename T >
+void copy_host_to_host (T *dst, T const *src, size_t count=1)
+
+template<typename OutputIterator , typename T >
+void insert_to_host (OutputIterator begin, OutputIterator end, T const *device_begin)
+ Copies elements from device memory to host-side range. More...
+
+template<typename T , typename InputIterator >
+void insert_to_device (T *device_begin, InputIterator begin, InputIterator end)
+ Copies elements to device memory from host-side range. More...
+
+
+
+
+
+
+
+template<typename T >
+
+
+ T* cutlass::device_memory::allocate
+ (
+ size_t
+ count = 1)
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::copy
+ (
+ T *
+ dst ,
+
+
+
+
+ T const *
+ src ,
+
+
+
+
+ size_t
+ count ,
+
+
+
+
+ cudaMemcpyKind
+ kind
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::copy_device_to_device
+ (
+ T *
+ dst ,
+
+
+
+
+ T const *
+ src ,
+
+
+
+
+ size_t
+ count = 1
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::copy_host_to_host
+ (
+ T *
+ dst ,
+
+
+
+
+ T const *
+ src ,
+
+
+
+
+ size_t
+ count = 1
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::copy_to_device
+ (
+ T *
+ dst ,
+
+
+
+
+ T const *
+ src ,
+
+
+
+
+ size_t
+ count = 1
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::copy_to_host
+ (
+ T *
+ dst ,
+
+
+
+
+ T const *
+ src ,
+
+
+
+
+ size_t
+ count = 1
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T >
+
+
+ void cutlass::device_memory::free
+ (
+ T *
+ ptr )
+
+
+
+
+
+
+
+
+
+
+
+template<typename T , typename InputIterator >
+
+
+ void cutlass::device_memory::insert_to_device
+ (
+ T *
+ device_begin ,
+
+
+
+
+ InputIterator
+ begin ,
+
+
+
+
+ InputIterator
+ end
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+template<typename OutputIterator , typename T >
+
+
+ void cutlass::device_memory::insert_to_host
+ (
+ OutputIterator
+ begin ,
+
+
+
+
+ OutputIterator
+ end ,
+
+
+
+
+ T const *
+ device_begin
+
+
+
+ )
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1epilogue_1_1thread.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1epilogue_1_1thread.html
new file mode 100644
index 0000000000000000000000000000000000000000..6cf166b34c0e283796617482de1c6c22b5f12a93
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1epilogue_1_1thread.html
@@ -0,0 +1,127 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::thread Namespace Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1layout.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1layout.html
new file mode 100644
index 0000000000000000000000000000000000000000..2cb9acb92378062ec5da5fe9924d0bcd7b564ed5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1layout.html
@@ -0,0 +1,250 @@
+
+
+
+
+
+
+CUTLASS: cutlass::layout Namespace Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Enumerator kColumnMajor
+leading dimension refers to stride between columns; stride along rows is 1
+
+ kRowMajor
+leading dimension refers to stride between rows; stride along columns is 1
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1reduction_1_1kernel.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1reduction_1_1kernel.html
new file mode 100644
index 0000000000000000000000000000000000000000..6b6b6bcd2c3f29f0ee0fa61b5e70e8457afee461
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacecutlass_1_1reduction_1_1kernel.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reduction::kernel Namespace Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacemembers_type.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacemembers_type.html
new file mode 100644
index 0000000000000000000000000000000000000000..838dc341d3ac96ce52d17fd7bffb3ccf22c8ca85
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespacemembers_type.html
@@ -0,0 +1,150 @@
+
+
+
+
+
+
+CUTLASS: Namespace Members
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespaces.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespaces.html
new file mode 100644
index 0000000000000000000000000000000000000000..615ad00453ade72a0899e7648f29666f29f78801
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/namespaces.html
@@ -0,0 +1,147 @@
+
+
+
+
+
+
+CUTLASS: Namespace List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Here is a list of all namespaces with brief descriptions:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/output__tile__thread__map_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/output__tile__thread__map_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..34d1770fe0d176ea7441f362ca87685fbc78db7d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/output__tile__thread__map_8h_source.html
@@ -0,0 +1,156 @@
+
+
+
+
+
+
+CUTLASS: output_tile_thread_map.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 45 namespace threadblock {
59 static int const kRow = Row;
64 static int const kCount = kColumn * kRow * kGroup * kCluster *
kTile ;
82 static int const kThreads = ThreadMap::kThreads;
85 static int const kElementsPerAccess = ThreadMap::kElementsPerAccess;
107 Index cluster = coord.
strided () / (Shape::kGroup * Shape::kRow);
108 Index cluster_residual = coord.
strided () % (Shape::kGroup * Shape::kRow);
110 Index group = cluster_residual / (Shape::kRow);
111 Index row = cluster_residual % (Shape::kRow);
114 row + group * Shape::kRow * Count::kRow
115 + cluster * Shape::kGroup * Count::kGroup * Shape::kRow * Count::kRow,
129 int ElementsPerAccess,
139 int ElementsPerAccess,
142 struct RowArrangement <Shape, WarpsRemaining, ElementsPerAccess, ElementSize, false> {
143 static int const kWarpSize = 32;
144 static int const kElementsPerAccess = ElementsPerAccess;
145 static int const kElementSize = ElementSize;
147 static int const kIterationsRow = 1;
148 static int const kDeltaRow = 1;
149 static int const kIterationsColumn = Shape::kColumn / kElementsPerAccess / kWarpSize;
150 static int const kDeltaColumn = kWarpSize * kElementsPerAccess;
152 static int const kAccessWidth = kWarpSize;
153 static int const kAccessRows = 1;
154 static int const kWarpPartitionsRow = 1;
155 static int const kWarpPartitionsColumn = WarpsRemaining;
162 int ElementsPerAccess,
165 struct RowArrangement <Shape, WarpsRemaining, ElementsPerAccess, ElementSize, true> {
167 static int const kMemoryAccessSize = 128;
168 static int const kWarpSize = 32;
170 static int const kElementsPerAccess = ElementsPerAccess;
171 static int const kElementSize = ElementSize;
174 static int const kShapeRow = Shape::kRow / WarpsRemaining;
175 static int const kShapeWidth = Shape::kColumn / kElementsPerAccess;
177 static int const kTargetMemoryAccessWidth =
178 kMemoryAccessSize / (kElementsPerAccess * kElementSize / 8);
180 static int const kTargetAccessRows = kWarpSize / kTargetMemoryAccessWidth;
183 static int const kAccessWidth =
184 (Detail::kTargetAccessRows > Detail::kShapeRow ?
185 kWarpSize / Detail::kShapeRow
188 const_min (kWarpSize, kMemoryAccessSize / (kElementsPerAccess * kElementSize / 8))
191 static int const kAccessRows =
192 (Detail::kTargetAccessRows > Detail::kShapeRow ?
194 :
const_min (Shape::kRow, kWarpSize / kAccessWidth));
196 static int const kIterationsRow = Detail::kShapeRow / kAccessRows;
197 static int const kDeltaRow = kAccessRows;
199 static int const kIterationsColumn = Detail::kShapeWidth / kAccessWidth;
200 static int const kDeltaColumn = kAccessWidth * kElementsPerAccess;
202 static_assert ( kAccessWidth * kElementsPerAccess <= Shape::kColumn,
"Accessing too many elements per access" );
203 static_assert ( kIterationsColumn > 0,
"Iteration Count Column must be > 0" );
204 static_assert ( kIterationsRow > 0,
"Iteration Count Row must be > 0" );
206 static int const kWarpPartitionsRow = 1;
207 static int const kWarpPartitionsColumn = 1;
225 int ElementsPerAccess,
233 static int const kWarpSize = 32;
234 static int const kThreads = Threads;
235 static int const kWarpCount = kThreads / kWarpSize;
237 static int const kElementsPerAccess = ElementsPerAccess;
238 static int const kElementSize = ElementSize;
247 static int const kIterationsCluster =
248 ((Shape::kCluster > kWarpCount) ?
249 Shape::kCluster / kWarpCount
252 static int const kDeltaCluster =
253 ((Shape::kCluster > kWarpCount) ?
254 Shape::kRow * Count::kRow * Shape::kGroup * Count::kGroup * Shape::kCluster / kIterationsCluster
257 static int const kCompactedDeltaCluster =
258 ((Shape::kCluster > kWarpCount) ?
259 Shape::kRow * Shape::kGroup * Shape::kCluster / kIterationsCluster
262 static int const kWarpPartitionsCluster =
263 ((Shape::kCluster > kWarpCount) ?
265 : kWarpCount / Shape::kCluster);
267 static int const kWarpsRemainingForGroups =
268 ((Shape::kCluster > kWarpCount) ? 1 : kWarpCount / Shape::kCluster);
271 static int const kIterationsGroup =
272 ((Shape::kGroup > kWarpsRemainingForGroups) ?
273 Shape::kGroup / kWarpsRemainingForGroups
276 static int const kDeltaGroup =
277 ((Shape::kGroup > kWarpsRemainingForGroups) ?
278 Shape::kRow * Count::kRow * Shape::kGroup / kIterationsGroup
281 static int const kCompactedDeltaGroup =
282 ((Shape::kGroup > kWarpsRemainingForGroups) ?
283 Shape::kRow * Shape::kGroup / kIterationsGroup
286 static int const kWarpPartitionsGroup =
287 ((Shape::kGroup > kWarpsRemainingForGroups) ?
289 : kWarpsRemainingForGroups / Shape::kGroup);
291 static int const kWarpsRemainingForRows =
292 ((Shape::kGroup > kWarpsRemainingForGroups) ?
294 : kWarpsRemainingForGroups / Shape::kGroup);
299 kWarpsRemainingForRows,
302 (Shape::kRow > kWarpsRemainingForRows)
307 RowArrangement::kWarpPartitionsColumn,
308 RowArrangement::kWarpPartitionsRow,
309 kWarpPartitionsGroup,
310 kWarpPartitionsCluster,
313 static int const kAccessWidth = RowArrangement::kAccessWidth;
314 static int const kAccessRows = RowArrangement::kAccessRows;
322 Detail::RowArrangement::kIterationsColumn,
323 Detail::RowArrangement::kIterationsRow,
324 Detail::kIterationsGroup,
325 Detail::kIterationsCluster,
329 Detail::RowArrangement::kDeltaColumn,
330 Detail::RowArrangement::kDeltaRow,
332 Detail::kDeltaCluster,
339 int warp_idx = thread_idx / kWarpSize;
340 int lane_idx = thread_idx % kWarpSize;
343 int cluster_idx = warp_idx / Detail::WarpPartitions::kCluster;
344 int residual_cluster = warp_idx % Detail::WarpPartitions::kCluster;
346 int group_idx = residual_cluster / Detail::WarpPartitions::kGroup;
347 int residual_group = residual_cluster % Detail::WarpPartitions::kGroup;
349 int row_idx = residual_group / Detail::WarpPartitions::kRow;
350 int col_idx = residual_group % Detail::WarpPartitions::kRow;
353 int lane_row_offset = lane_idx / Detail::kAccessWidth;
354 int lane_col_offset = lane_idx % Detail::kAccessWidth;
357 int cluster_offset = cluster_idx * Shape::kRow * Count::kRow * Shape::kGroup * Count::kGroup;
358 int group_offset = group_idx * Shape::kRow * Count::kRow;
359 int row_offset = row_idx * Iterations::kRow * Detail::kAccessRows;
360 int column_offset = col_idx * Iterations::kColumn * Detail::kAccessWidth * kElementsPerAccess;
363 cluster_offset + group_offset + row_offset + lane_row_offset,
364 (column_offset + lane_col_offset) * kElementsPerAccess
375 Detail::RowArrangement::kIterationsColumn,
376 Detail::RowArrangement::kIterationsRow,
377 Detail::kIterationsGroup,
378 Detail::kIterationsCluster,
382 Detail::RowArrangement::kDeltaColumn,
383 Detail::RowArrangement::kDeltaRow,
384 Detail::kCompactedDeltaGroup,
385 Detail::kCompactedDeltaCluster,
389 static int const kElementsPerAccess = ElementsPerAccess;
392 static int const kThreads = Threads;
398 int warp_idx = thread_idx / kWarpSize;
399 int lane_idx = thread_idx % kWarpSize;
402 int cluster_idx = warp_idx / Detail::WarpPartitions::kCluster;
403 int residual_cluster = warp_idx % Detail::WarpPartitions::kCluster;
405 int group_idx = residual_cluster / Detail::WarpPartitions::kGroup;
406 int residual_group = residual_cluster % Detail::WarpPartitions::kGroup;
408 int row_idx = residual_group / Detail::WarpPartitions::kRow;
409 int col_idx = residual_group % Detail::WarpPartitions::kRow;
412 int lane_row_offset = lane_idx / Detail::kAccessWidth;
413 int lane_col_offset = lane_idx % Detail::kAccessWidth;
416 int cluster_offset = cluster_idx * Shape::kRow * Shape::kGroup;
417 int group_offset = group_idx * Shape::kRow;
418 int row_offset = row_idx * Iterations::kRow * Detail::kAccessRows;
419 int column_offset = col_idx * Iterations::kColumn * Detail::kAccessWidth * kElementsPerAccess;
422 cluster_offset + group_offset + row_offset + lane_row_offset,
423 (column_offset + lane_col_offset) * kElementsPerAccess
440 template <
typename WarpCount_,
typename MmaCount_,
int Threads,
441 int ElementsPerAccess,
int ElementSize>
446 static int const kWarpSize = 32;
447 static int const kThreads = Threads;
448 static int const kWarpCount = kThreads / kWarpSize;
450 static int const kElementsPerAccess = ElementsPerAccess;
451 static int const kElementSize = ElementSize;
470 int warp_idx = thread_idx / kWarpSize;
471 int lane_idx = thread_idx % kWarpSize;
475 Delta::kContiguous * Iterations::kContiguous,
476 Delta::kStrided * Iterations::kStrided};
479 warp_idx / WarpCount::kContiguous};
483 lane_idx * kElementsPerAccess, 0};
486 warp_footprint * warp_offset + thread_offset_in_warp;
488 return thread_offset_in_threadblock_tile;
int Index
Integer-valued index.
Definition: pitch_linear.h:56
+
ThreadMap_ ThreadMap
Conventional thread map (concept: ThreadMap)
Definition: output_tile_thread_map.h:79
+
Definition: output_tile_thread_map.h:228
+
Definition: aligned_buffer.h:35
+
Coordinate in pitch-linear space.
Definition: pitch_linear.h:52
+
Defines a structure containing strides, bounds, and a pointer to tensor data.
+
Count_ Count
Definition: output_tile_thread_map.h:231
+
static int const kGroup
Definition: output_tile_thread_map.h:60
+
Tuple defining point in output tile.
Definition: output_tile_thread_map.h:57
+
WarpCount_ WarpCount
Definition: output_tile_thread_map.h:443
+
Iterations_ Iterations
Iterations performed by each thread.
Definition: output_tile_thread_map.h:91
+
static int const kColumn
Definition: output_tile_thread_map.h:58
+
RowArrangement determines how one or more warps cover a region of consecutive rows.
Definition: output_tile_thread_map.h:133
+
Definition: output_tile_thread_map.h:442
+
Template defining a shape used by pitch-linear operators.
Definition: pitch_linear.h:43
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
Compacted thread map in which the 4D region is contiguous.
Definition: output_tile_thread_map.h:369
+
Count_ Count
Number of iterator iterations.
Definition: output_tile_thread_map.h:97
+
static CUTLASS_HOST_DEVICE MatrixCoord initial_offset(int thread_idx)
Function to compute each thread's initial offset.
Definition: output_tile_thread_map.h:396
+
Defines a Shape template for matrix tiles.
+
Shape_ Shape
Definition: output_tile_thread_map.h:230
+
static CUTLASS_HOST_DEVICE layout::PitchLinearCoord initial_offset(int thread_idx)
Initial offset function.
Definition: output_tile_thread_map.h:469
+
detail::RowArrangement< Shape, kWarpsRemainingForRows, kElementsPerAccess, kElementSize,(Shape::kRow > kWarpsRemainingForRows) > RowArrangement
Definition: output_tile_thread_map.h:303
+
MmaCount Iterations
Definition: output_tile_thread_map.h:463
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
CUTLASS_HOST_DEVICE Index const & contiguous() const
Returns the contiguous dimension.
Definition: pitch_linear.h:89
+
+
Shape_ Shape
Definition: output_tile_thread_map.h:372
+
Delta_ Delta
Delta between accesses.
Definition: output_tile_thread_map.h:94
+
static CUTLASS_HOST_DEVICE MatrixCoord initial_offset(int thread_idx)
Initial offset function.
Definition: output_tile_thread_map.h:101
+
Definition: output_tile_thread_map.h:457
+
static int const kRow
Definition: output_tile_thread_map.h:59
+
Defines layout functions used by TensorRef and derived classes.
+
+
Definition: output_tile_thread_map.h:76
+
Shape_ Shape
Shape of the tile.
Definition: output_tile_thread_map.h:88
+
static int const kTile
Definition: output_tile_thread_map.h:62
+
static int const kCount
Definition: output_tile_thread_map.h:64
+
MmaCount_ MmaCount
Definition: output_tile_thread_map.h:444
+
static CUTLASS_HOST_DEVICE MatrixCoord initial_offset(int thread_idx)
Initial offset function.
Definition: output_tile_thread_map.h:337
+
CUTLASS_HOST_DEVICE constexpr int const_min(int a, int b)
Definition: fast_math.h:219
+
Basic include for CUTLASS.
+
Definition: matrix_coord.h:39
+
Definition: output_tile_thread_map.h:244
+
static int const kCluster
Definition: output_tile_thread_map.h:61
+
CUTLASS_HOST_DEVICE Index const & strided() const
Returns the column of the coordinate.
Definition: pitch_linear.h:97
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/pitch__linear__thread__map_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/pitch__linear__thread__map_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..81a49ccca939a0c42c8450ee454e221d82e8b50b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/pitch__linear__thread__map_8h__incl.md5
@@ -0,0 +1 @@
+7b53b5fc6a0b83df4492fee08ba7c584
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/platform_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/platform_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ca81e2916ec0abd70279da8fe0c45ff4faf84bb9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/platform_8h__dep__incl.md5
@@ -0,0 +1 @@
+b3c7bb37b6eaf978bed7b20a9b7dbe75
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduce__split__k_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduce__split__k_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..9cc19bfd16c1dc90bc4e33d1be53287d769f3b87
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduce__split__k_8h_source.html
@@ -0,0 +1,153 @@
+
+
+
+
+
+
+CUTLASS: reduce_split_k.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 52 typename ReductionOp_,
53 int PartitionsPerStage = 4
102 size_t partition_stride_,
106 typename OutputOp::Params output_ =
typename OutputOp::Params(),
107 typename ReductionOp::Params reduction_ =
typename ReductionOp::Params()
109 problem_size(problem_size_),
110 partitions(partitions_),
111 partition_stride(sizeof(
FragmentWorkspace ) * partition_stride_ / kElementsPerAccess),
112 workspace(workspace_),
113 destination(destination_),
116 reduction(reduction_) {
132 (problem_size.
column () + Shape::kColumn - 1) / Shape::kColumn,
133 (problem_size.
row () + Shape::kRow -1) / Shape::kRow);
139 return dim3(Shape::kColumn / kElementsPerAccess, Shape::kRow);
148 int (blockIdx.y) * Shape::kRow + threadIdx.y,
149 int (blockIdx.x) * Shape::kColumn + threadIdx.x * kElementsPerAccess
170 char const *workspace_ptr =
171 reinterpret_cast< char const *
> (
200 accumulator = reduction_op(accumulator, workspace_frag[i]);
216 if (output_op.is_source_needed()) {
224 typename OutputOp::FragmentOutput output_frag = output_op(accumulator, source_frag);
233 *dest_ptr =
reinterpret_cast< FragmentOutput const &
> (output_frag);
typename ReductionOp::Element ElementWorkspace
Definition: reduce_split_k.h:64
+
typename ReductionOp::ElementAccumulator ElementAccumulator
Definition: reduce_split_k.h:65
+
CUTLASS_HOST_DEVICE Index const & column() const
Returns the column of the coordinate.
Definition: matrix_coord.h:85
+
OutputTensorRef source
Definition: reduce_split_k.h:87
+
Definition: aligned_buffer.h:35
+
OutputTensorRef destination
Definition: reduce_split_k.h:86
+
Defines a structure containing strides, bounds, and a pointer to tensor data.
+
size_t partition_stride
Definition: reduce_split_k.h:84
+
CUTLASS_HOST_DEVICE Element * data() const
Returns the pointer to referenced data.
Definition: tensor_ref.h:254
+
static CUTLASS_HOST_DEVICE dim3 block_shape()
Determines the threadblock shape.
Definition: reduce_split_k.h:138
+
Aligned array type.
Definition: array.h:511
+
typename OutputOp::ElementOutput ElementOutput
Definition: reduce_split_k.h:66
+
CUTLASS_HOST_DEVICE Index const & row() const
Returns the row of the coordinate.
Definition: matrix_coord.h:77
+
int partitions
Definition: reduce_split_k.h:83
+
CUTLASS_HOST_DEVICE Params(MatrixCoord problem_size_, int partitions_, size_t partition_stride_, WorkspaceTensorRef workspace_, OutputTensorRef destination_, OutputTensorRef source_, typename OutputOp::Params output_=typename OutputOp::Params(), typename ReductionOp::Params reduction_=typename ReductionOp::Params())
Definition: reduce_split_k.h:99
+
CUTLASS_HOST_DEVICE Params()
Definition: reduce_split_k.h:96
+
Params structure.
Definition: reduce_split_k.h:80
+
ReductionOp_ ReductionOp
Definition: reduce_split_k.h:59
+
CUTLASS_DEVICE void operator()(Params const ¶ms, SharedStorage &storage)
Perform a reduction.
Definition: reduce_split_k.h:144
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
Shape_ Shape
Definition: reduce_split_k.h:58
+
Boost-like numeric conversion operator for CUTLASS numeric types.
+
Defines a Shape template for matrix tiles.
+
WorkspaceTensorRef workspace
Definition: reduce_split_k.h:85
+
+
ReductionOp::Params reduction
Definition: reduce_split_k.h:89
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
CUTLASS_HOST_DEVICE LongIndex offset(TensorCoord const &coord) const
Computes the offset of an index from the origin of the tensor.
Definition: tensor_ref.h:301
+
Definition: reduce_split_k.h:55
+
#define CUTLASS_PRAGMA_NO_UNROLL
Definition: cutlass.h:111
+
static int const kPartitionsPerStage
Definition: reduce_split_k.h:62
+
static CUTLASS_HOST_DEVICE dim3 grid_shape(cutlass::MatrixCoord problem_size)
Computes the grid size given a chosen threadblock shape.
Definition: reduce_split_k.h:128
+
static int const kElementsPerAccess
Definition: reduce_split_k.h:61
+
Defines layout functions used by TensorRef and derived classes.
+
OutputOp_ OutputOp
Definition: reduce_split_k.h:60
+
MatrixCoord problem_size
Definition: reduce_split_k.h:82
+
Array< ElementAccumulator, kElementsPerAccess > FragmentAccumulator
Definition: reduce_split_k.h:72
+
Basic include for CUTLASS.
+
Definition: matrix_coord.h:39
+
Definition: reduce_split_k.h:121
+
OutputOp::Params output
Definition: reduce_split_k.h:88
+
Define basic numeric operators with specializations for Array<T, N>. SIMD-ize where possible...
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduction__op_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduction__op_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..8eee144db6d5c6df721f8dc4272a2bf3bc099661
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/reduction__op_8h_source.html
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+CUTLASS: reduction_op.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 83 return operator_(lhs, rhs);
Definition: aligned_buffer.h:35
+
Host-constructable parameters structure.
Definition: reduction_op.h:62
+
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
Boost-like numeric conversion operator for CUTLASS numeric types.
+
CUTLASS_HOST_DEVICE ReductionOpPlus(Params const ¶ms)
Constructs the function object, possibly loading from pointers in host memory.
Definition: reduction_op.h:73
+
Definition: reduction_op.h:52
+
static int const kCount
Definition: reduction_op.h:56
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
Top-level include for all CUTLASS numeric types.
+
CUTLASS_HOST_DEVICE Fragment operator()(Fragment const &lhs, Fragment const &rhs) const
Computes Compute =>
Definition: reduction_op.h:79
+
Element_ Element
Definition: reduction_op.h:55
+
Array< Element, kCount > Fragment
Definition: reduction_op.h:58
+
Basic include for CUTLASS.
+
Define basic numeric operators with specializations for Array<T, N>. SIMD-ize where possible...
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__access__iterator__tensor__op_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__access__iterator__tensor__op_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..56222f5c68a54f3691b1c6a69606df1fe60a5553
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__access__iterator__tensor__op_8h_source.html
@@ -0,0 +1,223 @@
+
+
+
+
+
+
+CUTLASS: regular_tile_access_iterator_tensor_op.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 45 namespace threadblock {
56 template <
typename Shape_,
typename Element_,
int AdvanceRank,
57 typename ThreadMap_,
int Alignment>
60 layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
61 int(128 / sizeof(Element_))>,
62 AdvanceRank, ThreadMap_, Alignment> {
65 AdvanceRank == 0 || AdvanceRank == 1,
66 "Specialization for pitch-linear iterator may along advance along the " 67 "contiguous(rank=0) or strided(rank=1) dimension." );
73 int(128 /
sizeof (Element_))>;
74 static int const kAdvanceRank = AdvanceRank;
75 static int const kAlignment = Alignment;
89 static int const kAccessSizeInBits = 128;
92 ThreadMap::kElementsPerAccess ==
94 "This iterator requires a policy whose access size is 128bs" );
97 static int const kPointerCount =
98 (ThreadMap::Iterations::kStrided > 1 ? 2 : 1);
102 using AccessType = Array<Element, Layout::kElementsPerAccess>;
119 int iteration_contiguous_;
122 int iteration_strided_;
130 : stride_(ref.stride(0) /
Layout ::kElementsPerAccess),
133 ThreadMap::initial_offset(thread_id);
136 for (
int i = 0; i < Detail::kPointerCount; ++i) {
142 0, ThreadMap::Detail::WarpThreadArrangement::kStrided * i};
146 ref.
data () + ref.
offset (thread_offset_in_threadblock_tile));
149 set_iteration_index(0);
155 iteration_contiguous_ = index % ThreadMap::Iterations::kContiguous;
156 iteration_strided_ = index / ThreadMap::Iterations::kContiguous;
162 byte_offset_ += pointer_offset *
sizeof (
Element );
168 AccessType *access_ptr = pointer_[iteration_strided_ & 1];
169 int stride_idx = (iteration_strided_ & ~1);
171 int access_offset = stride_idx * ThreadMap::Delta::kStrided * stride_ +
172 iteration_contiguous_ * ThreadMap::Delta::kContiguous /
173 ThreadMap::kElementsPerAccess;
175 char *access_byte_ptr =
176 reinterpret_cast< char *
> (access_ptr + access_offset);
177 return reinterpret_cast< AccessType *
> (access_byte_ptr + byte_offset_);
183 ++iteration_contiguous_;
185 if (iteration_contiguous_ < ThreadMap::Iterations::kContiguous)
190 iteration_contiguous_ = 0;
191 ++iteration_strided_;
193 if (iteration_strided_ < ThreadMap::Iterations::kStrided) {
199 iteration_strided_ = 0;
216 add_pointer_offset(coord.contiguous() * Shape::kContiguous +
217 coord.strided() * Shape::kStrided * stride_ *
218 Layout::kElementsPerAccess);
231 template <
typename Shape_,
typename Element_,
int AdvanceRank,
232 typename ThreadMap_,
int Alignment>
235 layout::ColumnMajorTensorOpMultiplicandCongruous<
236 sizeof_bits<Element_>::value, int(128 / sizeof(Element_))>,
237 AdvanceRank, ThreadMap_, Alignment> {
240 AdvanceRank == 0 || AdvanceRank == 1,
241 "Specialization for column-major iterator may along advance along the " 242 "columns(rank=0) or rows(rank=1) dimension." );
248 static int const kAdvanceRank = AdvanceRank;
249 static int const kAlignment = Alignment;
263 int(128 /
sizeof (Element_))>,
264 (kAdvanceRank == 0 ? 0 : 1), ThreadMap_>;
278 : iterator_({ref.
data (), ref.
stride ()}, thread_id) {}
287 iterator_.add_pointer_offset(pointer_offset);
293 return reinterpret_cast< AccessType *
> (iterator_.get());
299 iterator_.add_tile_offset({coord.row(), coord.column()});
328 template <
typename Shape_,
typename Element_,
int AdvanceRank,
329 typename ThreadMap_,
int Alignment>
332 layout::RowMajorTensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
333 int(128 / sizeof(Element_))>,
334 AdvanceRank, ThreadMap_, Alignment> {
337 AdvanceRank == 0 || AdvanceRank == 1,
338 "Specialization for row-major iterator may along advance along the " 339 "columns(rank=0) or rows(rank=1) dimension." );
342 using Element = Element_;
345 static int const kAdvanceRank = AdvanceRank;
346 static int const kAlignment = Alignment;
359 layout::TensorOpMultiplicandCongruous<sizeof_bits<Element_>::value,
360 int(128 /
sizeof (Element_))>,
361 (kAdvanceRank == 0 ? 1 : 0), ThreadMap_>;
375 : iterator_({ref.
data (), ref.
stride ()}, thread_id) {}
384 iterator_.add_pointer_offset(pointer_offset);
390 return reinterpret_cast< AccessType *
> (iterator_.get());
396 iterator_.add_tile_offset({coord.column(), coord.row()});
425 template <
typename Shape_,
typename Element_,
int AdvanceRank,
426 typename ThreadMap_,
int Alignment,
int Crosswise>
428 layout::TensorOpMultiplicandCrosswise<
429 sizeof_bits<Element_>::value, Crosswise>,
430 AdvanceRank, ThreadMap_, Alignment> {
433 AdvanceRank == 0 || AdvanceRank == 1,
434 "Specialization for pitch-linear iterator may along advance along the " 435 "contiguous(rank=0) or strided(rank=1) dimension." );
438 using Element = Element_;
442 static int const kAdvanceRank = AdvanceRank;
443 static int const kAlignment = Alignment;
444 static int const kCrosswise = Crosswise;
458 static int const kAccessSizeInBits = 128;
461 ThreadMap::kElementsPerAccess ==
463 "This iterator requires a policy whose access size is 128bs" );
469 static int const kPointerCount =
470 (ThreadMap::Iterations::kStrided > 1 ? 2 : 1);
474 using AccessType = Array<Element, Layout::kElementsPerAccess>;
488 int sections_per_stage_;
500 int iteration_contiguous_;
503 int iteration_strided_;
511 : sections_(ref.stride(0) / kCrosswise),
512 sections_per_stage_(
Shape ::kContiguous / kCrosswise),
514 stride_(ref.stride(0) *
Layout ::kFactor /
Layout ::kElementsPerAccess),
517 ThreadMap::initial_offset(thread_id);
520 for (
int i = 0; i < Detail::kPointerCount; ++i) {
526 0, ThreadMap::Detail::WarpThreadArrangement::kStrided * i};
529 ref.
offset (thread_offset_in_threadblock_tile) /
530 Layout::kElementsPerAccess;
533 set_iteration_index(0);
539 iteration_contiguous_ = index % ThreadMap::Iterations::kContiguous;
540 iteration_strided_ = index / ThreadMap::Iterations::kContiguous;
552 AccessType *access_ptr = pointer_[iteration_strided_ & 1];
553 int stride_idx = (iteration_strided_ & ~1);
556 stride_idx * ThreadMap::Delta::kStrided * stride_ / Layout::kFactor +
557 iteration_contiguous_ * ThreadMap::Delta::kContiguous /
558 ThreadMap::kElementsPerAccess;
559 char *access_byte_ptr =
560 reinterpret_cast< char *
> (access_ptr + access_offset);
561 return reinterpret_cast< AccessType *
> (access_byte_ptr + byte_offset_);
567 ++iteration_contiguous_;
569 if (iteration_contiguous_ < ThreadMap::Iterations::kContiguous)
574 iteration_contiguous_ = 0;
575 ++iteration_strided_;
577 if (iteration_strided_ < ThreadMap::Iterations::kStrided) {
583 iteration_strided_ = 0;
600 add_pointer_offset(coord.contiguous() * sections_per_stage_ * stride_ *
601 ThreadMap::kElementsPerAccess / sections_ +
602 coord.strided() * Shape::kStrided * stride_ *
603 Layout::kElementsPerAccess);
616 template <
typename Shape_,
typename Element_,
int AdvanceRank,
617 typename ThreadMap_,
int Alignment,
int Crosswise>
620 layout::ColumnMajorTensorOpMultiplicandCrosswise<
621 sizeof_bits<Element_>::value, Crosswise>,
622 AdvanceRank, ThreadMap_, Alignment> {
625 AdvanceRank == 0 || AdvanceRank == 1,
626 "Specialization for column-major iterator may along advance along the " 627 "columns(rank=0) or rows(rank=1) dimension." );
630 using Element = Element_;
633 static int const kAdvanceRank = AdvanceRank;
634 static int const kAlignment = Alignment;
646 layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, Element,
649 (kAdvanceRank == 0 ? 0 : 1), ThreadMap_>;
663 : iterator_({ref.
data (), ref.
stride ()}, thread_id) {}
672 iterator_.add_pointer_offset(pointer_offset);
678 return reinterpret_cast< AccessType *
> (iterator_.get());
684 iterator_.add_tile_offset({coord.row(), coord.column()});
713 template <
typename Shape_,
typename Element_,
int AdvanceRank,
714 typename ThreadMap_,
int Alignment,
int Crosswise>
716 layout::RowMajorTensorOpMultiplicandCrosswise<
717 sizeof_bits<Element_>::value, Crosswise>,
718 AdvanceRank, ThreadMap_, Alignment> {
721 AdvanceRank == 0 || AdvanceRank == 1,
722 "Specialization for row-major iterator may along advance along the " 723 "columns(rank=0) or rows(rank=1) dimension." );
726 using Element = Element_;
729 static int const kAdvanceRank = AdvanceRank;
730 static int const kAlignment = Alignment;
742 layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, Element,
745 (kAdvanceRank == 0 ? 1 : 0), ThreadMap_>;
759 : iterator_({ref.
data (), ref.
stride ()}, thread_id) {}
768 iterator_.add_pointer_offset(pointer_offset);
774 return reinterpret_cast< AccessType *
> (iterator_.get());
780 iterator_.add_tile_offset({coord.column(), coord.row()});
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:434
+
+
+
+
+
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:640
+
+
Definition: aligned_buffer.h:35
+
+
Coordinate in pitch-linear space.
Definition: pitch_linear.h:52
+
Defines a structure containing strides, bounds, and a pointer to tensor data.
+
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:431
+
+
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:536
+
Definition: tensor_op_multiplicand_sm75.h:734
+
CUTLASS_HOST_DEVICE Element * data() const
Returns the pointer to referenced data.
Definition: tensor_ref.h:254
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:539
+
+
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:221
+
+
+
Definition: tensor_op_multiplicand_sm75.h:422
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:843
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm75.h:742
+
+
Definition: tensor_op_multiplicand_sm75.h:835
+
+
+
Definition: tensor_op_multiplicand_sm75.h:213
+
+
+
+
+
+
+
+
+
+
+
+
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:224
+
+
+
+
Template defining a shape used by pitch-linear operators.
Definition: pitch_linear.h:43
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe ...
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
+
+
+
CUTLASS_HOST_DEVICE half_t & operator++(half_t &lhs)
Definition: half.h:694
+
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:846
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the layout object's stride vector.
Definition: tensor_ref.h:277
+
Defines a Shape template for matrix tiles.
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:745
+
+
Defines the size of an element in bits.
Definition: numeric_types.h:42
+
+
+
+
+
+
+
+
+
+
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
+
CUTLASS_HOST_DEVICE LongIndex offset(TensorCoord const &coord) const
Computes the offset of an index from the origin of the tensor.
Definition: tensor_ref.h:301
+
+
+
+
+
+
+
+
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm75.h:643
+
+
+
+
Templates implementing the address computation of storing of tiles from pitch-linear rank=2 tensors...
+
+
+
Defines a canonical coordinate for rank=2 matrices offering named indices.
+
+
+
+
+
+
+
+
+
Defines layout functions used by TensorRef and derived classes for pitch-linear memory.
+
+
Definition: tensor_op_multiplicand_sm75.h:632
+
+
+
+
Basic include for CUTLASS.
+
Definition: matrix_coord.h:39
+
+
+
+
+
+
Definition: tensor_op_multiplicand_sm75.h:527
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__iterator__pitch__linear_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__iterator__pitch__linear_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..5653aad1797e45e1a752fec1fe15320855422679
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/regular__tile__iterator__pitch__linear_8h__incl.md5
@@ -0,0 +1 @@
+c5be49e94f77091843935db2bcd40f94
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/semaphore_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/semaphore_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ff145b966e2481b9376cd05dc8655f764230653e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/semaphore_8h__dep__incl.md5
@@ -0,0 +1 @@
+55566fee6dc680f010eb417a6bb46031
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/shared__load__iterator_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/shared__load__iterator_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..12cd447262725294267b248f00aab03e4d2bdca3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/shared__load__iterator_8h.html
@@ -0,0 +1,155 @@
+
+
+
+
+
+
+CUTLASS: shared_load_iterator.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Epilogue for threadblock scoped GEMMs using Tensor Ops.
+More...
+
+
Go to the source code of this file.
+
+
+
The epilogue rearranges the result of a matrix product through shared memory to match canonical tensor layouts in global memory. Epilogues support conversion and reduction operations.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Coord-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Coord-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..677bf6b770e55f643f17ad76e3244c1b68d412eb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Coord-members.html
@@ -0,0 +1,149 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::Coord< Rank_, Index_, LongIndex_ > , including all inherited members.
+
+ at ()cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ at (int dim)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ at () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ at (int dim) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ clamp (Coord const &max, Coord const &min=Coord())cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ Coord (Index value=Index(0))cutlass::Coord< Rank_, Index_, LongIndex_ > inline explicit
+ Coord (Index const (&_idx)[kRank])cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ Coord (Coord< kRank, Index, LongIndex > const &coord)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ dot (Coord const &b, LongIndex sum=LongIndex(0)) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ Index typedefcutlass::Coord< Rank_, Index_, LongIndex_ >
+ kRank cutlass::Coord< Rank_, Index_, LongIndex_ > static
+ LongIndex typedefcutlass::Coord< Rank_, Index_, LongIndex_ >
+ max_dim_index () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ min_dim_index () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator bool () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline explicit
+ operator! () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator!= (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator* (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator*= (Coord const &b)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator+ (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator+= (Coord const &b)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator- (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator-= (Coord const &b)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator/ (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator/= (Coord const &b)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator< (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator<= (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator== (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator> (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator>= (Coord const &b) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator[] (int dim)cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ operator[] (int dim) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ product () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ slice (int start=0, Index identity=0) const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+ sum () const cutlass::Coord< Rank_, Index_, LongIndex_ > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Distribution.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Distribution.html
new file mode 100644
index 0000000000000000000000000000000000000000..172a1ccde7fa70bbb90cbb9119f42f70bda91261
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Distribution.html
@@ -0,0 +1,531 @@
+
+
+
+
+
+
+CUTLASS: cutlass::Distribution Struct Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Distribution type.
+
+
+
#include <distribution.h >
+
+
+
+
+
+
+Enumerator Invalid
+
+ Uniform
+
+ Gaussian
+
+ Identity
+
+ Sequential
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ cutlass::Distribution::Distribution
+ (
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Distribution & cutlass::Distribution::set_gaussian
+ (
+ double
+ _mean ,
+
+
+
+
+ double
+ _stddev ,
+
+
+
+
+ int
+ _int_scale = 0
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Distribution & cutlass::Distribution::set_identity
+ (
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Distribution & cutlass::Distribution::set_sequential
+ (
+ double
+ start ,
+
+
+
+
+ double
+ delta ,
+
+
+
+
+ int
+ _int_scale = 0
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Distribution & cutlass::Distribution::set_uniform
+ (
+ double
+ _min ,
+
+
+
+
+ double
+ _max ,
+
+
+
+
+ int
+ _int_scale = 0
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::delta
+
+
+
+
+
+
+
+
+
+
+
+ struct { ... } cutlass::Distribution::gaussian
+
+
+
+
+
+
+
+
+
+
+
+ int cutlass::Distribution::int_scale
+
+
+
+
+
+
+
+
+
+
+
+ Kind cutlass::Distribution::kind
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::max
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::mean
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::min
+
+
+
+
+
+
+
+
+
+
+
+ struct { ... } cutlass::Distribution::sequential
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::start
+
+
+
+
+
+
+
+
+
+
+
+ double cutlass::Distribution::stddev
+
+
+
+
+
+
+
+
+
+
+
+ struct { ... } cutlass::Distribution::uniform
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_014_00_01true_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_014_00_01true_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..c51b8d4017bc6d7168383572eb89edd4d31687e2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_014_00_01true_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::IntegerType< 4, true > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_0164_00_01true_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_0164_00_01true_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..4718500d4746fbea0db7ced3b04310b1f675dc0e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1IntegerType_3_0164_00_01true_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::IntegerType< 64, true > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixCoord-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixCoord-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..581aebac9a1910ccc7ac0c4c8d365c405d1bc409
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixCoord-members.html
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::MatrixCoord , including all inherited members.
+
+ at ()cutlass::Coord< 2, int > inline
+ at (int dim)cutlass::Coord< 2, int > inline
+ at () constcutlass::Coord< 2, int > inline
+ at (int dim) constcutlass::Coord< 2, int > inline
+ Base typedefcutlass::MatrixCoord
+ clamp (Coord const &max, Coord const &min=Coord())cutlass::Coord< 2, int > inline
+ column () const cutlass::MatrixCoord inline
+ column ()cutlass::MatrixCoord inline
+ Coord (Index value=Index(0))cutlass::Coord< 2, int > inline explicit
+ Coord (Index const (&_idx)[kRank])cutlass::Coord< 2, int > inline
+ Coord (Coord< kRank, Index, LongIndex > const &coord)cutlass::Coord< 2, int > inline
+ dot (Coord const &b, LongIndex sum=LongIndex(0)) constcutlass::Coord< 2, int > inline
+ Index typedefcutlass::MatrixCoord
+ kRank cutlass::Coord< 2, int > static
+ LongIndex typedefcutlass::Coord< 2, int >
+ MatrixCoord ()cutlass::MatrixCoord inline
+ MatrixCoord (Coord< 2, Index > const &coord)cutlass::MatrixCoord inline
+ MatrixCoord (Index row, Index column)cutlass::MatrixCoord inline
+ max_dim_index () constcutlass::Coord< 2, int > inline
+ min_dim_index () constcutlass::Coord< 2, int > inline
+ operator bool () constcutlass::Coord< 2, int > inline explicit
+ operator! () constcutlass::Coord< 2, int > inline
+ operator!= (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator* (Base const &b) const cutlass::MatrixCoord inline
+ Coord< 2, int >::operator* (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator*= (Base const &b)cutlass::MatrixCoord inline
+ Coord< 2, int >::operator*= (Coord const &b)cutlass::Coord< 2, int > inline
+ operator+ (Base const &b) const cutlass::MatrixCoord inline
+ Coord< 2, int >::operator+ (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator+= (Base const &b)cutlass::MatrixCoord inline
+ Coord< 2, int >::operator+= (Coord const &b)cutlass::Coord< 2, int > inline
+ operator- (Base const &b) const cutlass::MatrixCoord inline
+ Coord< 2, int >::operator- (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator-= (Base const &b)cutlass::MatrixCoord inline
+ Coord< 2, int >::operator-= (Coord const &b)cutlass::Coord< 2, int > inline
+ operator/ (Base const &b) const cutlass::MatrixCoord inline
+ Coord< 2, int >::operator/ (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator/= (Base const &b)cutlass::MatrixCoord inline
+ Coord< 2, int >::operator/= (Coord const &b)cutlass::Coord< 2, int > inline
+ operator< (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator<= (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator== (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator> (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator>= (Coord const &b) constcutlass::Coord< 2, int > inline
+ operator[] (int dim)cutlass::Coord< 2, int > inline
+ operator[] (int dim) constcutlass::Coord< 2, int > inline
+ product () constcutlass::Coord< 2, int > inline
+ row () const cutlass::MatrixCoord inline
+ row ()cutlass::MatrixCoord inline
+ slice (int start=0, Index identity=0) constcutlass::Coord< 2, int > inline
+ sum () constcutlass::Coord< 2, int > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixShape-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixShape-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..201e88379389a669308f6a280d6938770dbafa65
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1MatrixShape-members.html
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::MatrixShape< Row_, Column_ > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericArrayConverter_3_01half__t_00_01float_00_012_00_01FloatRoundStyle_1_1round__to__nearest_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericArrayConverter_3_01half__t_00_01float_00_012_00_01FloatRoundStyle_1_1round__to__nearest_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..ccfefc7dc9cf11a9dc8d5ed44505fe4ef3139a3d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericArrayConverter_3_01half__t_00_01float_00_012_00_01FloatRoundStyle_1_1round__to__nearest_01_4.html
@@ -0,0 +1,243 @@
+
+
+
+
+
+
+CUTLASS: cutlass::NumericArrayConverter< half_t, float, 2, FloatRoundStyle::round_to_nearest > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Partial specialization for Array<half, 2> <= Array<float, 2>, round to nearest.
+
+
+
#include <numeric_conversion.h >
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericConverter_3_01T_00_01T_00_01Round_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericConverter_3_01T_00_01T_00_01Round_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..fe8c1d9640515898b654de35414f126339cc4a34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1NumericConverter_3_01T_00_01T_00_01Round_01_4-members.html
@@ -0,0 +1,119 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::NumericConverter< T, T, Round > , including all inherited members.
+
+ convert (source_type const &s)cutlass::NumericConverter< T, T, Round > inline static
+ operator() (source_type const &s)cutlass::NumericConverter< T, T, Round > inline
+ result_type typedefcutlass::NumericConverter< T, T, Round >
+ round_style cutlass::NumericConverter< T, T, Round > static
+ source_type typedefcutlass::NumericConverter< T, T, Round >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..aa5daa60125a0b1cdbc6850d7455e30f05b6645a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4-members.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::ReferenceFactory< Element, true > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..b8d9167f06f982d951a79e4d521ce4cb826d9c68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1ReferenceFactory_3_01Element_00_01true_01_4.html
@@ -0,0 +1,200 @@
+
+
+
+
+
+
+CUTLASS: cutlass::ReferenceFactory< Element, true > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <subbyte_reference.h >
+
+
+
+
+
+
+template<typename Element >
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<typename Element >
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord.html
new file mode 100644
index 0000000000000000000000000000000000000000..5c8cdf59d9285bb8522c6428624053b083df9042
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord.html
@@ -0,0 +1,922 @@
+
+
+
+
+
+
+CUTLASS: cutlass::Tensor4DCoord Struct Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Defines a canonical 4D coordinate used by tensor operations.
+
+
+
#include <tensor_coord.h >
+
+
+
+
+
+
+CUTLASS_HOST_DEVICE Tensor4DCoord ()
+ Default ctor. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord (Coord < 4 > const &coord)
+ Constructs from Coord<4> More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord (Index n , Index h , Index w , Index c )
+ Helper to construct from N, H, W, and C. More...
+
+CUTLASS_HOST_DEVICE Index const & n () const
+ Returns the batch of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index & n ()
+ Returns the batch of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index const & h () const
+ Returns the row of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index & h ()
+ Returns the row of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index const & w () const
+ Returns the column of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index & w ()
+ Returns the column of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index const & c () const
+ Returns the channel of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Index & c ()
+ Returns the channel of the coordinate. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord operator+ (Base const &b) const
+ Element-wise addition. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord operator- (Base const &b) const
+ Element-wise subtraction. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord operator* (Base const &b) const
+ Element-wise multiplication. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord operator/ (Base const &b) const
+ Element-wise division. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord & operator+= (Base const &b)
+ In-place addition. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord & operator-= (Base const &b)
+ In-place subtraction. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord & operator*= (Base const &b)
+ In-place multiplication. More...
+
+CUTLASS_HOST_DEVICE Tensor4DCoord & operator/= (Base const &b)
+ In-place division. More...
+
+
+CUTLASS_HOST_DEVICE Coord (Index value=Index (0))
+ Default ctor initializes uniformly. More...
+
+CUTLASS_HOST_DEVICE Coord (Index const (&_idx)[kRank ])
+ Constructs from an array of integers. More...
+
+CUTLASS_HOST_DEVICE Coord (Coord < kRank , Index , LongIndex > const &coord)
+ Copy constructor. More...
+
+CUTLASS_HOST_DEVICE Coord < Slice > slice (int start=0, Index identity=0) const
+
+CUTLASS_HOST_DEVICE int min_dim_index () const
+ Returns the index of the dimension with least value. More...
+
+CUTLASS_HOST_DEVICE int max_dim_index () const
+ Returns the index of the dimension with greatest value. More...
+
+CUTLASS_HOST_DEVICE operator bool () const
+ Returns true if Coord is non-zero. More...
+
+CUTLASS_HOST_DEVICE bool operator! () const
+ Returns true if Coord is uniformly zero. More...
+
+CUTLASS_HOST_DEVICE Coord operator+ (Coord const &b) const
+ Element-wise addition. More...
+
+CUTLASS_HOST_DEVICE Coord operator- (Coord const &b) const
+ Element-wise subtraction. More...
+
+CUTLASS_HOST_DEVICE Coord operator* (Coord const &b) const
+ Element-wise multiplication. More...
+
+CUTLASS_HOST_DEVICE Coord operator/ (Coord const &b) const
+ Element-wise division. More...
+
+CUTLASS_HOST_DEVICE Coord & operator+= (Coord const &b)
+ In-place addition. More...
+
+CUTLASS_HOST_DEVICE Coord & operator-= (Coord const &b)
+ In-place subtraction. More...
+
+CUTLASS_HOST_DEVICE Coord & operator*= (Coord const &b)
+ In-place multiplication. More...
+
+CUTLASS_HOST_DEVICE Coord & operator/= (Coord const &b)
+ In-place division. More...
+
+CUTLASS_HOST_DEVICE Index & operator[] (int dim)
+ Member access operator. More...
+
+CUTLASS_HOST_DEVICE Index const & operator[] (int dim) const
+ Member access operator. More...
+
+CUTLASS_HOST_DEVICE LongIndex dot (Coord const &b, LongIndex sum =LongIndex (0)) const
+ Computes the dot product with anotherCoord object. More...
+
+CUTLASS_HOST_DEVICE Index & at ()
+ Gets the index of a given Coord element. More...
+
+CUTLASS_HOST_DEVICE Index & at (int dim)
+ Access via index; may limit unrolling potential. More...
+
+CUTLASS_HOST_DEVICE Index const & at () const
+ Gets the index of a given Coord element. More...
+
+CUTLASS_HOST_DEVICE Index const & at (int dim) const
+ Access via index; may limit unrolling potential. More...
+
+CUTLASS_HOST_DEVICE bool operator== (Coord const &b) const
+ Determines if two Coord<> objects are equal. More...
+
+CUTLASS_HOST_DEVICE bool operator!= (Coord const &b) const
+ Not equal. More...
+
+CUTLASS_HOST_DEVICE Coord & clamp (Coord const &max, Coord const &min=Coord ())
+ Clamps a coordinate to a range specified by maximum and minimum values. More...
+
+CUTLASS_HOST_DEVICE Index sum () const
+ Returns the sum of all elements. More...
+
+CUTLASS_HOST_DEVICE LongIndex product () const
+ Returns the product of all elements. More...
+
+CUTLASS_HOST_DEVICE bool operator< (Coord const &b) const
+ Less than operator. More...
+
+CUTLASS_HOST_DEVICE bool operator<= (Coord const &b) const
+ Less than or equals operator. More...
+
+CUTLASS_HOST_DEVICE bool operator> (Coord const &b) const
+ Greater than operator. More...
+
+CUTLASS_HOST_DEVICE bool operator>= (Coord const &b) const
+ Greater than or equals operator. More...
+
+
+
+static int const kN = 0
+ Batch dimension. More...
+
+static int const kH = 1
+ Height dimension. More...
+
+static int const kW = 2
+ Width dimension. More...
+
+static int const kC = 3
+ Channels dimension. More...
+
+
+static int const kRank
+ Number of elements in Coord. More...
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ int const cutlass::Tensor4DCoord::kC = 3
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ int const cutlass::Tensor4DCoord::kH = 1
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ int const cutlass::Tensor4DCoord::kN = 0
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ int const cutlass::Tensor4DCoord::kW = 2
+
+
+
+
+static
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..af308c33fa5ccefb998377a27da6e7cad75349a3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1Tensor4DCoord__inherit__graph.md5
@@ -0,0 +1 @@
+7f9f5fba5b156d46b8ea81b4cdb4f8c1
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01int8__t_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01int8__t_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..4175756b015e0119429b951e99e16316f9a00706
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01int8__t_01_4.html
@@ -0,0 +1,290 @@
+
+
+
+
+
+
+CUTLASS: cutlass::TypeTraits< int8_t > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <type_traits.h >
+
+
+static cudaDataType_t const cublas_type = CUDA_R_8I
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01unsigned_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01unsigned_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..865f4d42dc11e764c6f11644dc23c182c0b44595
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1TypeTraits_3_01unsigned_01_4.html
@@ -0,0 +1,290 @@
+
+
+
+
+
+
+CUTLASS: cutlass::TypeTraits< unsigned > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <type_traits.h >
+
+
+static cudaDataType_t const cublas_type = CUDA_R_32I
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ static uint32_t cutlass::TypeTraits < unsigned >::remove_negative_zero
+ (
+ uint32_t
+ x )
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_011_01_4_00_011_00_01complex_0a4e7894a173a90c4c8a848e15443dd6.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_011_01_4_00_011_00_01complex_0a4e7894a173a90c4c8a848e15443dd6.html
new file mode 100644
index 0000000000000000000000000000000000000000..30a00ff2ad7316758563dd386d0254c64bccbe2d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_011_01_4_00_011_00_01complex_0a4e7894a173a90c4c8a848e15443dd6.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, double, LayoutB, complex< double >, LayoutC, OpMultiplyAdd >
+
+
+
+
+
+
This is the complete list of members for cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, double, LayoutB, complex< double >, LayoutC, OpMultiplyAdd > , including all inherited members.
+
+ operator() (Array< complex< double >, 1 > &d, Array< complex< double >, 1 > const &a, Array< double, 1 > const &b, Array< complex< double >, 1 > const &c)cutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, double, LayoutB, complex< double >, LayoutC, OpMultiplyAdd > inline
+ Shape typedefcutlass::arch::Mma< gemm::GemmShape< 1, 1, 1 >, 1, complex< double >, LayoutA, double, LayoutB, complex< double >, LayoutC, OpMultiplyAdd >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_012_01_4_00_011_00_01int16__t3dda54d0df2c21b051e222cddd982e9b.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_012_01_4_00_011_00_01int16__t3dda54d0df2c21b051e222cddd982e9b.html
new file mode 100644
index 0000000000000000000000000000000000000000..a66cba836ed319c374b55ad943e345e65c654dea
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_011_00_011_00_012_01_4_00_011_00_01int16__t3dda54d0df2c21b051e222cddd982e9b.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 1, 1, 2 >, 1, int16_t, layout::RowMajor, int16_t, layout::ColumnMajor, int, LayoutC, OpMultiplyAdd >
+
+
+
+
+
+
This is the complete list of members for cutlass::arch::Mma< gemm::GemmShape< 1, 1, 2 >, 1, int16_t, layout::RowMajor, int16_t, layout::ColumnMajor, int, LayoutC, OpMultiplyAdd > , including all inherited members.
+
+ operator() (Array< int, 1 > &d, Array< int16_t, 2 > const &a, Array< int16_t, 2 > const &b, Array< int, 1 > const &c)cutlass::arch::Mma< gemm::GemmShape< 1, 1, 2 >, 1, int16_t, layout::RowMajor, int16_t, layout::ColumnMajor, int, LayoutC, OpMultiplyAdd > inline
+ Shape typedefcutlass::arch::Mma< gemm::GemmShape< 1, 1, 2 >, 1, int16_t, layout::RowMajor, int16_t, layout::ColumnMajor, int, LayoutC, OpMultiplyAdd >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01int8__96070083128b01fff1ff03d9341232b2.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01int8__96070083128b01fff1ff03d9341232b2.html
new file mode 100644
index 0000000000000000000000000000000000000000..f56b750ab44c01690cb659bde5cd4a5f3e9e46f8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01int8__96070083128b01fff1ff03d9341232b2.html
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
+
This is the complete list of members for cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd > , including all inherited members.
+
+ ElementA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ ElementB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ ElementC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ FragmentA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ FragmentB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ FragmentC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ LayoutA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ LayoutB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ LayoutC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ Operator typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+ operator() (FragmentC &d, FragmentA const &a, FragmentB const &b, FragmentC const &c) const cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd > inline
+ Shape typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, int8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01uint8_a62aa63a212985df306fb27e8a50aeae.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01uint8_a62aa63a212985df306fb27e8a50aeae.html
new file mode 100644
index 0000000000000000000000000000000000000000..745ccfabd1bd695155ef4aba198c4ca44ea7c48d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0116_01_4_00_0132_00_01uint8_a62aa63a212985df306fb27e8a50aeae.html
@@ -0,0 +1,335 @@
+
+
+
+
+
+
+CUTLASS: cutlass::arch::Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 8, 8, 16 >, 32, uint8_t, layout::RowMajor, int8_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
+
Matrix multiply-add operation: S32 = U8 * S8 + S32.
+
+
+
#include <mma_sm75.h >
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementA = uint8_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementB = int8_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementC = int
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentA = Array<uint8_t, 4>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentB = Array<int8_t, 4>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentC = Array<int, 2>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutA = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutB = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutC = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Operator = OpMultiplyAdd
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Shape = gemm::GemmShape <8, 8, 16>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS_HOST_DEVICE void cutlass::arch::Mma < gemm::GemmShape < 8, 8, 16 >, 32, uint8_t, layout::RowMajor , int8_t, layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::operator()
+ (
+ FragmentC &
+ d ,
+
+
+
+
+ FragmentA const &
+ a ,
+
+
+
+
+ FragmentB const &
+ b ,
+
+
+
+
+ FragmentC const &
+ c
+
+
+
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_4746fc55e614df0016c518d3fda2677e.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_4746fc55e614df0016c518d3fda2677e.html
new file mode 100644
index 0000000000000000000000000000000000000000..e9d969ba43f79f660765e5ecae339bb138ddd04e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_4746fc55e614df0016c518d3fda2677e.html
@@ -0,0 +1,335 @@
+
+
+
+
+
+
+CUTLASS: cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, uint4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
+
Matrix multiply-add operation: S32 = S4 * U4 + S32.
+
+
+
#include <mma_sm75.h >
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementA = int4b_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementB = uint4b_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementC = int
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentA = Array<int4b_t , 8>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentB = Array<uint4b_t , 8>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentC = Array<int, 2>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutA = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutB = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutC = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Operator = OpMultiplyAdd
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Shape = gemm::GemmShape <8,8,32>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS_HOST_DEVICE void cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , uint4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::operator()
+ (
+ FragmentC &
+ d ,
+
+
+
+
+ FragmentA const &
+ a ,
+
+
+
+
+ FragmentB const &
+ b ,
+
+
+
+
+ FragmentC const &
+ c
+
+
+
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_6e513ccbc44ae7909a60d93b9b5435b3.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_6e513ccbc44ae7909a60d93b9b5435b3.html
new file mode 100644
index 0000000000000000000000000000000000000000..2cc5e89dd61dcdf5c34d3ca78f9d2eaa352224a0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_0132_01_4_00_0132_00_01int4b_6e513ccbc44ae7909a60d93b9b5435b3.html
@@ -0,0 +1,335 @@
+
+
+
+
+
+
+CUTLASS: cutlass::arch::Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 8, 8, 32 >, 32, int4b_t, layout::RowMajor, int4b_t, layout::ColumnMajor, int, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
+
Matrix multiply-add operation: S32 = S4 * S4 + S32.
+
+
+
#include <mma_sm75.h >
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementA = int4b_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementB = int4b_t
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::ElementC = int
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentA = Array<int4b_t , 8>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentB = Array<int4b_t , 8>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::FragmentC = Array<int, 2>
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutA = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutB = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::LayoutC = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Operator = OpMultiplyAdd
+
+
+
+
+
+
+
+
+
+
+
+ using cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::Shape = gemm::GemmShape <8,8,32>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS_HOST_DEVICE void cutlass::arch::Mma < gemm::GemmShape < 8, 8, 32 >, 32, int4b_t , layout::RowMajor , int4b_t , layout::ColumnMajor , int, layout::RowMajor , OpMultiplyAdd >::operator()
+ (
+ FragmentC &
+ d ,
+
+
+
+
+ FragmentA const &
+ a ,
+
+
+
+
+ FragmentB const &
+ b ,
+
+
+
+
+ FragmentC const &
+ c
+
+
+
+ )
+ const
+
+
+
+
+inline
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_014_01_4_00_018_00_01half__t_2d559ae99ed058d77e22f2d26b3dd474.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_014_01_4_00_018_00_01half__t_2d559ae99ed058d77e22f2d26b3dd474.html
new file mode 100644
index 0000000000000000000000000000000000000000..cf793f514b85729d435c33101be440d3af8efde7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Mma_3_01gemm_1_1GemmShape_3_018_00_018_00_014_01_4_00_018_00_01half__t_2d559ae99ed058d77e22f2d26b3dd474.html
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass arch Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
+
This is the complete list of members for cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd > , including all inherited members.
+
+ ElementA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ ElementB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ ElementC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ FragmentA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ FragmentB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ FragmentC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ LayoutA typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ LayoutB typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ LayoutC typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ Operator typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+ operator() (FragmentC &d, FragmentA const &a, FragmentB const &b, FragmentC const &c)cutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd > inline
+ Shape typedefcutlass::arch::Mma< gemm::GemmShape< 8, 8, 4 >, 8, half_t, layout::ColumnMajor, half_t, layout::RowMajor, half_t, layout::RowMajor, OpMultiplyAdd >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Sm61-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Sm61-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..b40eb5de9c54ad757503a71af4d54c7f8a1db0eb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1arch_1_1Sm61-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::arch::Sm61 , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1device__memory_1_1allocation_1_1deleter-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1device__memory_1_1allocation_1_1deleter-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..2111fcdfabd1053d50de8aab20d69d1c0e8f403d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1device__memory_1_1allocation_1_1deleter-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::device_memory::allocation< T >::deleter , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueSimt-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueSimt-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..65ba8f9114ca2d16dd3bf2709d9be893cdefc883
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueSimt-members.html
@@ -0,0 +1,129 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess > , including all inherited members.
+
+ AccumulatorFragmentIterator typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ ElementAccumulator typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ ElementOutput typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ Epilogue typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ kElementsPerAccess cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess > static
+ kPartitionsK cutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess > static
+ LayoutC typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ OutputOp typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ OutputTileIterator typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ OutputTileThreadMap typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ Padding typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ Shape typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ SharedLoadIterator typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ WarpMmaSimt typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+ WarpTileIterator typedefcutlass::epilogue::threadblock::DefaultEpilogueSimt< Shape_, WarpMmaSimt_, OutputOp_, ElementsPerAccess >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueWmmaTensorOp.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueWmmaTensorOp.html
new file mode 100644
index 0000000000000000000000000000000000000000..4b037a596a73025790f72bcedd5e79a19f12737d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultEpilogueWmmaTensorOp.html
@@ -0,0 +1,389 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::threadblock::DefaultEpilogueWmmaTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Defines sensible defaults for epilogues for WMMA TensorOps.
+
+
+
#include <default_epilogue_wmma_tensor_op.h >
+
+
+using Shape = Shape_
+
+using WarpMmaTensorOp = WarpMmaTensorOp_
+
+using OutputOp = OutputOp_
+
+using ElementOutput = typename OutputOp::ElementOutput
+
+using LayoutC = typename WarpMmaTensorOp::LayoutC
+
+using ElementAccumulator = typename WarpMmaTensorOp::ElementC
+
+using OutputTileThreadMap = typename cutlass::epilogue::threadblock::DefaultThreadMapWmmaTensorOp < Shape , typename WarpMmaTensorOp::Shape, typename WarpMmaTensorOp::Policy::Operator::Shape, kPartitionsK , ElementOutput , kElementsPerAccess >::Type
+
+using OutputTileIterator = cutlass::epilogue::threadblock::PredicatedTileIterator < OutputTileThreadMap , ElementOutput >
+
+using AccumulatorFragmentIterator = cutlass::epilogue::warp::FragmentIteratorWmmaTensorOp < typename WarpMmaTensorOp::Shape, typename WarpMmaTensorOp::Policy::Operator::Shape, typename WarpMmaTensorOp::Policy::Operator::ElementC, typename WarpMmaTensorOp::Policy::Operator::FragmentC, LayoutC >
+
+using WarpTileIterator = cutlass::epilogue::warp::TileIteratorWmmaTensorOp < typename WarpMmaTensorOp::Shape, typename WarpMmaTensorOp::Policy::Operator::Shape, typename WarpMmaTensorOp::Policy::Operator::FragmentC, LayoutC >
+
+using SharedLoadIterator = cutlass::epilogue::threadblock::SharedLoadIterator < typename OutputTileThreadMap::CompactedThreadMap, ElementAccumulator >
+
+using Padding = typename WarpTileIterator::Padding
+ Hard-coded padding elements added. More...
+
+using Epilogue = cutlass::epilogue::threadblock::Epilogue < Shape , WarpMmaTensorOp , kPartitionsK , OutputTileIterator , AccumulatorFragmentIterator , WarpTileIterator , SharedLoadIterator , OutputOp , Padding >
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+ using cutlass::epilogue::threadblock::DefaultEpilogueWmmaTensorOp < Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess >::Epilogue = cutlass::epilogue::threadblock::Epilogue < Shape , WarpMmaTensorOp , kPartitionsK , OutputTileIterator , AccumulatorFragmentIterator , WarpTileIterator , SharedLoadIterator , OutputOp , Padding >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaTensorOp_ , int PartitionsK, typename OutputOp_ , int ElementsPerAccess>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultInterleavedEpilogueTensorOp-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultInterleavedEpilogueTensorOp-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..f8ce23014d4c116d69b9df6ff4cc43a6f83ad899
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultInterleavedEpilogueTensorOp-members.html
@@ -0,0 +1,126 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK > , including all inherited members.
+
+ AccumulatorFragmentIterator typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ ElementAccumulator typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ ElementOutput typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ Epilogue typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ kElementsPerAccess cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK > static
+ kPartitionsK cutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK > static
+ LayoutC typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ OutputOp typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ OutputTileIterator typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ OutputTileThreadMap typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ Shape typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+ WarpMmaTensorOp typedefcutlass::epilogue::threadblock::DefaultInterleavedEpilogueTensorOp< Shape_, WarpMmaTensorOp_, PartitionsK, OutputOp_, ElementsPerAccess, InterleavedK, IsBetaZero, isSplitK >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultThreadMapVoltaTensorOp_3_01ThreadblockShape__95db04b7b72e34283958bd7fbf851d16.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultThreadMapVoltaTensorOp_3_01ThreadblockShape__95db04b7b72e34283958bd7fbf851d16.html
new file mode 100644
index 0000000000000000000000000000000000000000..25221311451bd1fb05d9004468aebb80956a6c1d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1DefaultThreadMapVoltaTensorOp_3_01ThreadblockShape__95db04b7b72e34283958bd7fbf851d16.html
@@ -0,0 +1,267 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::threadblock::DefaultThreadMapVoltaTensorOp< ThreadblockShape_, WarpShape_, PartitionsK, ElementOutput_, ElementsPerAccess, float > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Defines the optimal thread map for TensorOp accumulator layouts.
+
+
+
#include <default_thread_map_volta_tensor_op.h >
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
+
+
+
+template<typename ThreadblockShape_ , typename WarpShape_ , int PartitionsK, typename ElementOutput_ , int ElementsPerAccess>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1EpilogueBase_1_1SharedStorage.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1EpilogueBase_1_1SharedStorage.html
new file mode 100644
index 0000000000000000000000000000000000000000..7482dc9bd235fc36b3ed20516572e375ac418f8d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1EpilogueBase_1_1SharedStorage.html
@@ -0,0 +1,328 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::threadblock::EpilogueBase< Shape_, WarpMmaOperator_, PartitionsK, AccumulatorFragmentIterator_, WarpTileIterator_, Padding_ >::SharedStorage Struct Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Shared storage allocation needed by the epilogue.
+
+
+
#include <epilogue_base.h >
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpMmaOperator_ , int PartitionsK, typename AccumulatorFragmentIterator_ , typename WarpTileIterator_ , typename Padding_ >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1InterleavedOutputTileThreadMap-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1InterleavedOutputTileThreadMap-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..36ccd21618e6d184da00a630c3e07633325f89f9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1InterleavedOutputTileThreadMap-members.html
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > , including all inherited members.
+
+ Delta typedefcutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize >
+ initial_offset (int thread_idx)cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > inline static
+ Iterations typedefcutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize >
+ kElementSize cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > static
+ kElementsPerAccess cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > static
+ kThreads cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > static
+ kWarpCount cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > static
+ kWarpSize cutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize > static
+ MmaCount typedefcutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize >
+ WarpCount typedefcutlass::epilogue::threadblock::InterleavedOutputTileThreadMap< WarpCount_, MmaCount_, Threads, ElementsPerAccess, ElementSize >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1OutputTileOptimalThreadMap_1_1Detail-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1OutputTileOptimalThreadMap_1_1Detail-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..0e8b529c7295a3eafe064440e6c0f903a079f9f7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1OutputTileOptimalThreadMap_1_1Detail-members.html
@@ -0,0 +1,128 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail , including all inherited members.
+
+ kAccessRows cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kAccessWidth cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kCompactedDeltaCluster cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kCompactedDeltaGroup cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kDeltaCluster cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kDeltaGroup cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kIterationsCluster cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kIterationsGroup cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kWarpPartitionsCluster cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kWarpPartitionsGroup cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kWarpsRemainingForGroups cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ kWarpsRemainingForRows cutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail static
+ RowArrangement typedefcutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail
+ WarpPartitions typedefcutlass::epilogue::threadblock::OutputTileOptimalThreadMap< Shape_, Count_, Threads, ElementsPerAccess, ElementSize >::Detail
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1PredicatedTileIterator_1_1Mask-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1PredicatedTileIterator_1_1Mask-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..fb88661e5057339893a6ef5e90dbe8282a9062d9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1threadblock_1_1PredicatedTileIterator_1_1Mask-members.html
@@ -0,0 +1,119 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1SimtPolicy_3_01WarpShape___00_01Operator___00_01layout_1_1Rcef1c60e23e997017ae176c92931151d.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1SimtPolicy_3_01WarpShape___00_01Operator___00_01layout_1_1Rcef1c60e23e997017ae176c92931151d.html
new file mode 100644
index 0000000000000000000000000000000000000000..c688870bb91b0df1a27f0a5243553f8071278ab5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1SimtPolicy_3_01WarpShape___00_01Operator___00_01layout_1_1Rcef1c60e23e997017ae176c92931151d.html
@@ -0,0 +1,330 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::warp::SimtPolicy< WarpShape_, Operator_, layout::RowMajor, MmaSimtPolicy_ > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Partial specialization for row-major.
+
+
+
#include <simt_policy.h >
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
Initial value: =
(WarpShape::kN / MmaSimtPolicy::WarpShape::kColumn)
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ , typename Operator_ , typename MmaSimtPolicy_ >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1TileIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1Gemm770cbca45441d295d5d7433e8222a700.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1TileIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1Gemm770cbca45441d295d5d7433e8222a700.html
new file mode 100644
index 0000000000000000000000000000000000000000..4509b9bb419c6bcec5ab8760a96d4a8e3ef67558
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1epilogue_1_1warp_1_1TileIteratorVoltaTensorOp_3_01WarpShape___00_01gemm_1_1Gemm770cbca45441d295d5d7433e8222a700.html
@@ -0,0 +1,244 @@
+
+
+
+
+
+
+CUTLASS: cutlass::epilogue::warp::TileIteratorVoltaTensorOp< WarpShape_, gemm::GemmShape< 32, 32, 4 >, float, layout::RowMajor >::Detail Struct Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <tile_iterator_volta_tensor_op.h >
+
+
+
+
+
+
+template<typename WarpShape_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ >
+
+
+
+
+
+
+
+
+
+template<typename WarpShape_ >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arc4fada4957d463c80a2831e47f28157c4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arc4fada4957d463c80a2831e47f28157c4.html
new file mode 100644
index 0000000000000000000000000000000000000000..288bbfdc905c5bf40708bc97f534a5867cb3eaba
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arc4fada4957d463c80a2831e47f28157c4.html
@@ -0,0 +1,281 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, int8_t, int8_t, ElementC, int32_t > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <default_gemm_configuration.h >
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcb27bf218007928652d5b803193eab473.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcb27bf218007928652d5b803193eab473.html
new file mode 100644
index 0000000000000000000000000000000000000000..fc71faad8b8c861b5da0a3326a1b844baf5e4e0c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcb27bf218007928652d5b803193eab473.html
@@ -0,0 +1,281 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint8_t, int8_t, ElementC, int32_t > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <default_gemm_configuration.h >
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcfea0f3503156e8e3fba6456f0cedafdd.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcfea0f3503156e8e3fba6456f0cedafdd.html
new file mode 100644
index 0000000000000000000000000000000000000000..897831a7137bb27d67c328ca9537c89fb3660e25
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1device_1_1DefaultGemmConfiguration_3_01arch_1_1OpClassTensorOp_00_01arcfea0f3503156e8e3fba6456f0cedafdd.html
@@ -0,0 +1,281 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::device::DefaultGemmConfiguration< arch::OpClassTensorOp, arch::Sm75, uint8_t, uint8_t, ElementC, int32_t > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <default_gemm_configuration.h >
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
+
+
+
+template<typename ElementC >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1DefaultGemm_3_01int8__t_00_01LayoutA_00_01kAlignmentA_00_01inf48440732c1c5f42ddbfaba179861815.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1DefaultGemm_3_01int8__t_00_01LayoutA_00_01kAlignmentA_00_01inf48440732c1c5f42ddbfaba179861815.html
new file mode 100644
index 0000000000000000000000000000000000000000..1d0d6410d5cffbc1b8ad1c94a16b5a42f311eecf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1DefaultGemm_3_01int8__t_00_01LayoutA_00_01kAlignmentA_00_01inf48440732c1c5f42ddbfaba179861815.html
@@ -0,0 +1,271 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::kernel::DefaultGemm< int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape< 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm kernel DefaultGemm< int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape< 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >
+
+
+
+
+
+
Partial specialization for SIMT DP4A.
+
+
+
#include <default_gemm.h >
+
+
+using InstructionShape = GemmShape < 1, 1, 4 >
+
+using ElementA = int8_t
+
+using ElementB = int8_t
+
+using OperatorClass = arch::OpClassSimt
+
+using Mma = typename cutlass::gemm::threadblock::DefaultMma < ElementA , LayoutA, kAlignmentA, ElementB , LayoutB, kAlignmentB, ElementAccumulator, LayoutC, arch::OpClassSimt, arch::Sm50 , ThreadblockShape, WarpShape, InstructionShape , 2, Operator, false >::ThreadblockMma
+ Define the threadblock-scoped matrix multiply-accumulate. More...
+
+using Epilogue = typename cutlass::epilogue::threadblock::DefaultEpilogueSimt < ThreadblockShape, typename Mma::Operator, EpilogueOutputOp, kEpilogueElementsPerAccess >::Epilogue
+ Define the epilogue. More...
+
+using GemmKernel = kernel::Gemm < Mma , Epilogue , ThreadblockSwizzle, SplitKSerial >
+ Define the kernel-level GEMM operator. More...
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::ElementA = int8_t
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::ElementB = int8_t
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::Epilogue = typename cutlass::epilogue::threadblock::DefaultEpilogueSimt < ThreadblockShape, typename Mma::Operator, EpilogueOutputOp, kEpilogueElementsPerAccess >::Epilogue
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::GemmKernel = kernel::Gemm <Mma , Epilogue , ThreadblockSwizzle, SplitKSerial>
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::InstructionShape = GemmShape <1, 1, 4>
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::Mma = typename cutlass::gemm::threadblock::DefaultMma <ElementA , LayoutA, kAlignmentA, ElementB , LayoutB, kAlignmentB, ElementAccumulator, LayoutC, arch::OpClassSimt, arch::Sm50 , ThreadblockShape, WarpShape, InstructionShape , 2, Operator, false >::ThreadblockMma
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+ using cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::OperatorClass = arch::OpClassSimt
+
+
+
+
+
+
+
+
+
+
+
+template<typename LayoutA , int kAlignmentA, typename LayoutB , int kAlignmentB, typename LayoutC , typename ElementC , typename ArchTag , typename ElementAccumulator , typename ThreadblockShape , typename WarpShape , typename EpilogueOutputOp , typename ThreadblockSwizzle , bool SplitKSerial, typename Operator >
+
+
+
+
+
+ int const cutlass::gemm::kernel::DefaultGemm < int8_t, LayoutA, kAlignmentA, int8_t, LayoutB, kAlignmentB, ElementC, LayoutC, ElementAccumulator, arch::OpClassSimt, ArchTag, ThreadblockShape, WarpShape, GemmShape < 1, 1, 4 >, EpilogueOutputOp, ThreadblockSwizzle, 2, SplitKSerial, Operator, false >::kEpilogueElementsPerAccess = EpilogueOutputOp::kCount
+
+
+
+
+static
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1Gemm-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1Gemm-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..ba6744d126b60fc4bb66dcac0e99d6887c95c41f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1Gemm-members.html
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > , including all inherited members.
+
+ can_implement (cutlass::gemm::GemmCoord const &problem_size, typename Mma::IteratorA::TensorRef ref_A, typename Mma::IteratorB::TensorRef ref_B, typename Epilogue::OutputTileIterator::TensorRef ref_C, typename Epilogue::OutputTileIterator::TensorRef ref_D)cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > inline static
+ Epilogue typedefcutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+ Gemm ()cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > inline
+ kSplitKSerial cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > static
+ kThreadCount cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > static
+ Mma typedefcutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+ operator() (Params const ¶ms, SharedStorage &shared_storage)cutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial > inline
+ OutputOp typedefcutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+ ThreadblockSwizzle typedefcutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+ WarpCount typedefcutlass::gemm::kernel::Gemm< Mma_, Epilogue_, ThreadblockSwizzle_, SplitKSerial >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1GemmBatched_1_1Params-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1GemmBatched_1_1Params-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..644542187e796b5781b21b607ec952c7eadb31c4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1GemmBatched_1_1Params-members.html
@@ -0,0 +1,133 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params , including all inherited members.
+
+ batch_count cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ epilogue cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ gemm_k_iterations cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ grid_tiled_shape cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ Params ()cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params inline
+ Params (cutlass::gemm::GemmCoord const &problem_size_, cutlass::gemm::GemmCoord const &grid_tiled_shape_, typename Mma::IteratorA::TensorRef ref_A_, int64_t stride_A_, typename Mma::IteratorB::TensorRef ref_B_, int64_t stride_B_, typename Epilogue::OutputTileIterator::TensorRef ref_C_, int64_t stride_C_, typename Epilogue::OutputTileIterator::TensorRef ref_D_, int64_t stride_D_, typename OutputOp::Params epilogue_, int batch_count_)cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params inline
+ params_A cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ params_B cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ params_C cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ params_D cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ problem_size cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ ref_A cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ ref_B cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ ref_C cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ ref_D cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ stride_A cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ stride_B cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ stride_C cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+ stride_D cutlass::gemm::kernel::GemmBatched< Mma_, Epilogue_, ThreadblockSwizzle_ >::Params
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1detail_1_1GemvBatchedStridedEpilogueScaling-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1detail_1_1GemvBatchedStridedEpilogueScaling-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..e1073d8bff1c1c3895a914fc399fbb08d93fbff3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1kernel_1_1detail_1_1GemvBatchedStridedEpilogueScaling-members.html
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1EnableMma__Crow__SM60-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1EnableMma__Crow__SM60-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..90d40fa8221eedda8585e35e939266e5a29c6d1d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1EnableMma__Crow__SM60-members.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::thread::detail::EnableMma_Crow_SM60< LayoutA, LayoutB > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1Mma__HFMA2_3_01Shape_00_01layout_1_1RowMajor_00_01l086c058a15d6c79558e4f3d9ff1dc148.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1Mma__HFMA2_3_01Shape_00_01layout_1_1RowMajor_00_01l086c058a15d6c79558e4f3d9ff1dc148.html
new file mode 100644
index 0000000000000000000000000000000000000000..e881513b578be946d162acfb039ee9ad2e2ef156
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1thread_1_1detail_1_1Mma__HFMA2_3_01Shape_00_01layout_1_1RowMajor_00_01l086c058a15d6c79558e4f3d9ff1dc148.html
@@ -0,0 +1,233 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::thread::detail::Mma_HFMA2< Shape, layout::RowMajor, layout::RowMajor, layout::RowMajor, true > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <mma_sm60.h >
+
+
+
+
+
+
+template<typename Shape >
+
+
+
+
+
+
+
+
+
+template<typename Shape >
+
+
+
+
+
+
+
+
+
+template<typename Shape >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape >
+
+
+
Initialize output with input
+
Use 1x2x1 HFMA2 sequence for bulk of computation
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultGemvCore-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultGemvCore-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..d9044d068f5a33ca5eb2c6b3a29d765cfbc6817f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultGemvCore-members.html
@@ -0,0 +1,131 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ > , including all inherited members.
+
+ ElementA typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ ElementB typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ ElementC typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorA typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorB typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorC typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorPolicyA typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorPolicyB typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ IteratorPolicyC typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ kThreadsPerN cutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ > static
+ LayoutA typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ LayoutB typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ LayoutC typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ MmaSimtOp typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ Operator typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ Shape typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+ ThreadShape typedefcutlass::gemm::threadblock::DefaultGemvCore< Shape_, ThreadShape_, ElementA_, LayoutA_, ElementB_, LayoutB_, ElementC_, LayoutC_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMma.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMma.html
new file mode 100644
index 0000000000000000000000000000000000000000..27e84b3c598b22ad6ea86574354586ca00cb6709
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMma.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::threadblock::DefaultMma< ElementA_, LayoutA_, kAlignmentA, ElementB_, LayoutB_, kAlignmentB, ElementAccumulator_, LayoutC_, OperatorClass_, ArchTag_, ThreadblockShape_, WarpShape_, InstructionShape_, Stages, Operator, AccumulatorsInRowMajor > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <default_mma.h >
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha4dc50bde4c2a3941f8f9807599cc52ef.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha4dc50bde4c2a3941f8f9807599cc52ef.html
new file mode 100644
index 0000000000000000000000000000000000000000..b5352e1e0229faaee0aad2fc682efe996c77f8ee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha4dc50bde4c2a3941f8f9807599cc52ef.html
@@ -0,0 +1,138 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm threadblock DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > , including all inherited members.
+
+ ElementA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ ElementB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ ElementC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ InstructionShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ IteratorThreadMapA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ IteratorThreadMapB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ kAccessSizeInBits cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ kThreads cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ kWarpSize cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ LayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ LayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ LayoutC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ MmaPolicy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ MmaTensorOp typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Operator typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ OperatorClass typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Policy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Shape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemIteratorA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemIteratorB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemLayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemLayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ WarpCount typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ WarpShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::RowMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha903c12d1a6db57137118ba796bc8de3e.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha903c12d1a6db57137118ba796bc8de3e.html
new file mode 100644
index 0000000000000000000000000000000000000000..40d2c849050a3b06c0d7b8e227ac1a3e44ce3b17
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmSha903c12d1a6db57137118ba796bc8de3e.html
@@ -0,0 +1,148 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm threadblock DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > , including all inherited members.
+
+ ElementA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ ElementB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ ElementC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ InstructionShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ IteratorThreadMapA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ IteratorThreadMapB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ kThreads cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ kWarpSize cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ LaneLayout cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ LaneM cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ LaneMmaShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ LaneN cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ LayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ LayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ LayoutC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ MmaPolicy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ MmaWarpSimt typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ numElementsA cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ numElementsB cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ Operator typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ OperatorClass typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ PartitionsK cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ Policy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ Shape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ SmemIteratorA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ SmemIteratorB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ SmemLayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ SmemLayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ ThreadTileM cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ ThreadTileN cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ WarpCount typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+ WarpNumThreadsM cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ WarpNumThreadsN cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ > static
+ WarpShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 1, 1, 4 >, int8_t, layout::ColumnMajor, int8_t, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassSimt, 2, Operator_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmShaa65fcc9419ddceacdfc43dd268adb852.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmShaa65fcc9419ddceacdfc43dd268adb852.html
new file mode 100644
index 0000000000000000000000000000000000000000..3afdccb719933b10efad55fdd701d7b9495f49de
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmShaa65fcc9419ddceacdfc43dd268adb852.html
@@ -0,0 +1,138 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm threadblock DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > , including all inherited members.
+
+ ElementA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ ElementB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ ElementC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ InstructionShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ IteratorThreadMapA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ IteratorThreadMapB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ kAccessSizeInBits cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ kThreads cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ kWarpSize cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > static
+ LayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ LayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ LayoutC typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ MmaPolicy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ MmaTensorOp typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Operator typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ OperatorClass typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Policy typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ Shape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemIteratorA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemIteratorB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemLayoutA typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ SmemLayoutB typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ WarpCount typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+ WarpShape typedefcutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, GemmShape< 8, 8, 4 >, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instruc803d38bc1e4618c07c47f54c87ae2678.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instruc803d38bc1e4618c07c47f54c87ae2678.html
new file mode 100644
index 0000000000000000000000000000000000000000..7d8653edf3208448e838736ba67b0daa22d1a5e6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instruc803d38bc1e4618c07c47f54c87ae2678.html
@@ -0,0 +1,586 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm threadblock DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
+
#include <default_mma_core_sm75.h >
+
+
+using Shape = Shape_
+
+using WarpShape = WarpShape_
+
+using InstructionShape = InstructionShape_
+
+using ElementA = ElementA_
+
+using LayoutA = layout::ColumnMajor
+
+using ElementB = ElementB_
+
+using LayoutB = layout::ColumnMajor
+
+using ElementC = ElementC_
+
+using LayoutC = LayoutC_
+
+using OperatorClass = arch::OpClassTensorOp
+
+using WarpCount = GemmShape < Shape::kM/WarpShape::kM, Shape::kN/WarpShape::kN, Shape::kK/WarpShape::kK >
+ Number of warps present. More...
+
+using Operator = Operator_
+ Default Operator. More...
+
+using SmemLayoutA = layout::ColumnMajorTensorOpMultiplicandCongruous < sizeof_bits < ElementA >::value, int(128/sizeof(ElementA ))>
+
+using SmemLayoutB = layout::ColumnMajorTensorOpMultiplicandCrosswise < sizeof_bits < ElementB >::value, Shape::kK >
+
+using IteratorThreadMapA = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape < Shape::kM, Shape::kK >, kThreads , layout::PitchLinearShape < 8, 4 >, kAccessSizeInBits /sizeof_bits < ElementA >::value >
+ ThreadMap of iterator A. More...
+
+using SmemIteratorA = transform::threadblock::RegularTileIterator < MatrixShape < Shape::kM, Shape::kK >, ElementA , SmemLayoutA , 1, IteratorThreadMapA >
+ Shared memory iterator to A operand. More...
+
+using IteratorThreadMapB = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape < Shape::kK, Shape::kN >, kThreads , layout::PitchLinearShape < kWarpThreadArrangementContiguousB , kWarpThreadArrangementStridedB >, kAccessSizeInBits /sizeof_bits < ElementB >::value >
+ ThreadMap of iterator B. More...
+
+using SmemIteratorB = transform::threadblock::RegularTileIterator < MatrixShape < Shape::kK, Shape::kN >, ElementB , SmemLayoutB , 1, IteratorThreadMapB >
+ Shared memory iterator to B operand. More...
+
+using MmaTensorOp = typename cutlass::gemm::warp::DefaultMmaTensorOp < WarpShape , InstructionShape , ElementA , SmemLayoutA , ElementB , SmemLayoutB , ElementC , LayoutC , Operator , WarpCount::kK >::Type
+
+using MmaPolicy = MmaPolicy < MmaTensorOp , MatrixShape < 0, 0 >, MatrixShape < 0, 0 >, WarpCount::kK >
+ Policy used to define MmaPipelined . More...
+
+
+
+
template<typename Shape_, typename WarpShape_, typename InstructionShape_, typename ElementA_, typename ElementB_, typename ElementC_, typename LayoutC_, typename Operator_>
+struct cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::ColumnMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
Partial specialization:
+
A: column-major B: column-major Operator: tensor op class
+
This uses the default warp-level operator given tile sizes
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementA = ElementA_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementB = ElementB_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementC = ElementC_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::InstructionShape = InstructionShape_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::IteratorThreadMapA = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape <Shape::kM, Shape::kK>, kThreads , layout::PitchLinearShape <8, 4>, kAccessSizeInBits / sizeof_bits <ElementA >::value>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::IteratorThreadMapB = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape <Shape::kK, Shape::kN>, kThreads , layout::PitchLinearShape <kWarpThreadArrangementContiguousB , kWarpThreadArrangementStridedB >, kAccessSizeInBits / sizeof_bits <ElementB >::value>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutA = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutB = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutC = LayoutC_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::MmaPolicy = MmaPolicy <MmaTensorOp , MatrixShape <0, 0>, MatrixShape <0, 0>, WarpCount::kK>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::MmaTensorOp = typename cutlass::gemm::warp::DefaultMmaTensorOp < WarpShape , InstructionShape , ElementA , SmemLayoutA , ElementB , SmemLayoutB , ElementC , LayoutC , Operator , WarpCount::kK>::Type
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::Operator = Operator_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::OperatorClass = arch::OpClassTensorOp
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::Shape = Shape_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemIteratorA = transform::threadblock::RegularTileIterator < MatrixShape <Shape::kM, Shape::kK>, ElementA , SmemLayoutA , 1, IteratorThreadMapA >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemIteratorB = transform::threadblock::RegularTileIterator < MatrixShape <Shape::kK, Shape::kN>, ElementB , SmemLayoutB , 1, IteratorThreadMapB >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemLayoutA = layout::ColumnMajorTensorOpMultiplicandCongruous < sizeof_bits <ElementA >::value, int(128 / sizeof(ElementA ))>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemLayoutB = layout::ColumnMajorTensorOpMultiplicandCrosswise < sizeof_bits <ElementB >::value, Shape::kK>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::WarpCount = GemmShape <Shape::kM / WarpShape::kM, Shape::kN / WarpShape::kN, Shape::kK / WarpShape::kK>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::WarpShape = WarpShape_
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kAccessSizeInBits = 128
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kThreads = WarpCount::kCount * kWarpSize
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kWarpSize = warp::WarpSize <arch::OpClassTensorOp>::value
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kWarpThreadArrangementContiguousB
+
+
+
+
+static
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::ColumnMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kWarpThreadArrangementStridedB
+
+
+
+
+static
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instrucf60fe02fcdd80d28b7fd419133465dcc.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instrucf60fe02fcdd80d28b7fd419133465dcc.html
new file mode 100644
index 0000000000000000000000000000000000000000..d78a6c9c69f575a8b24c84f7f55fabd720d24d96
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01Instrucf60fe02fcdd80d28b7fd419133465dcc.html
@@ -0,0 +1,538 @@
+
+
+
+
+
+
+CUTLASS: cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+cutlass gemm threadblock DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
+
+
+
+
#include <default_mma_core_sm75.h >
+
+
+using Shape = Shape_
+
+using WarpShape = WarpShape_
+
+using InstructionShape = InstructionShape_
+
+using ElementA = ElementA_
+
+using LayoutA = layout::ColumnMajor
+
+using ElementB = ElementB_
+
+using LayoutB = layout::RowMajor
+
+using ElementC = ElementC_
+
+using LayoutC = LayoutC_
+
+using OperatorClass = arch::OpClassTensorOp
+
+using WarpCount = GemmShape < Shape::kM/WarpShape::kM, Shape::kN/WarpShape::kN, Shape::kK/WarpShape::kK >
+ Number of warps present. More...
+
+using Operator = Operator_
+ Default Operator. More...
+
+using SmemLayoutA = layout::ColumnMajorTensorOpMultiplicandCongruous < sizeof_bits < ElementA >::value, int(128/sizeof(ElementA ))>
+
+using SmemLayoutB = layout::RowMajorTensorOpMultiplicandCongruous < sizeof_bits < ElementB >::value, int(128/sizeof(ElementB ))>
+
+using IteratorThreadMapA = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape < Shape::kM, Shape::kK >, kThreads , layout::PitchLinearShape < 8, 4 >, kAccessSizeInBits /sizeof_bits < ElementA >::value >
+ ThreadMap of iterator A. More...
+
+using SmemIteratorA = transform::threadblock::RegularTileIterator < MatrixShape < Shape::kM, Shape::kK >, ElementA , SmemLayoutA , 1, IteratorThreadMapA >
+ Shared memory iterator to A operand. More...
+
+using IteratorThreadMapB = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape < Shape::kN, Shape::kK >, kThreads , layout::PitchLinearShape < 8, 4 >, kAccessSizeInBits /sizeof_bits < ElementB >::value >
+ ThreadMap of iterator B. More...
+
+using SmemIteratorB = transform::threadblock::RegularTileIterator < MatrixShape < Shape::kK, Shape::kN >, ElementB , SmemLayoutB , 0, IteratorThreadMapB >
+ Shared memory iterator to B operand. More...
+
+using MmaTensorOp = typename cutlass::gemm::warp::DefaultMmaTensorOp < WarpShape , InstructionShape , ElementA , SmemLayoutA , ElementB , SmemLayoutB , ElementC , LayoutC , Operator , WarpCount::kK >::Type
+
+using MmaPolicy = MmaPolicy < MmaTensorOp , MatrixShape < 0, 0 >, MatrixShape < 0, 0 >, WarpCount::kK >
+ Policy used to define MmaPipelined . More...
+
+
+
+
template<typename Shape_, typename WarpShape_, typename InstructionShape_, typename ElementA_, typename ElementB_, typename ElementC_, typename LayoutC_, typename Operator_>
+struct cutlass::gemm::threadblock::DefaultMmaCore< Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor, ElementB_, layout::RowMajor, ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >
+
+
Partial specialization:
+
A: column-major B: row-major Operator: tensor op class
+
This uses the default warp-level operator given tile sizes
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementA = ElementA_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementB = ElementB_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::ElementC = ElementC_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::InstructionShape = InstructionShape_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::IteratorThreadMapA = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape <Shape::kM, Shape::kK>, kThreads , layout::PitchLinearShape <8, 4>, kAccessSizeInBits / sizeof_bits <ElementA >::value >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::IteratorThreadMapB = transform::PitchLinearWarpRakedThreadMap < layout::PitchLinearShape <Shape::kN, Shape::kK>, kThreads , layout::PitchLinearShape <8, 4>, kAccessSizeInBits / sizeof_bits <ElementB >::value >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutA = layout::ColumnMajor
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutB = layout::RowMajor
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::LayoutC = LayoutC_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::MmaPolicy = MmaPolicy < MmaTensorOp , MatrixShape <0, 0>, MatrixShape <0, 0>, WarpCount::kK >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::MmaTensorOp = typename cutlass::gemm::warp::DefaultMmaTensorOp < WarpShape , InstructionShape , ElementA , SmemLayoutA , ElementB , SmemLayoutB , ElementC , LayoutC , Operator , WarpCount::kK>::Type
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::Operator = Operator_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::OperatorClass = arch::OpClassTensorOp
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::Shape = Shape_
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemIteratorA = transform::threadblock::RegularTileIterator < MatrixShape <Shape::kM, Shape::kK>, ElementA , SmemLayoutA , 1, IteratorThreadMapA >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemIteratorB = transform::threadblock::RegularTileIterator < MatrixShape <Shape::kK, Shape::kN>, ElementB , SmemLayoutB , 0, IteratorThreadMapB >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemLayoutA = layout::ColumnMajorTensorOpMultiplicandCongruous < sizeof_bits <ElementA >::value, int(128 / sizeof(ElementA ))>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::SmemLayoutB = layout::RowMajorTensorOpMultiplicandCongruous < sizeof_bits <ElementB >::value, int(128 / sizeof(ElementB ))>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::WarpCount = GemmShape < Shape::kM / WarpShape::kM, Shape::kN / WarpShape::kN, Shape::kK / WarpShape::kK >
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+ using cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::WarpShape = WarpShape_
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kAccessSizeInBits = 128
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kThreads = WarpCount::kCount * kWarpSize
+
+
+
+
+static
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename WarpShape_ , typename InstructionShape_ , typename ElementA_ , typename ElementB_ , typename ElementC_ , typename LayoutC_ , typename Operator_ >
+
+
+
+
+
+ int const cutlass::gemm::threadblock::DefaultMmaCore < Shape_, WarpShape_, InstructionShape_, ElementA_, layout::ColumnMajor , ElementB_, layout::RowMajor , ElementC_, LayoutC_, arch::OpClassTensorOp, 2, Operator_ >::kWarpSize = warp::WarpSize <arch::OpClassTensorOp>::value
+
+
+
+
+static
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1GemmHorizontalThreadblockSwizzle-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1GemmHorizontalThreadblockSwizzle-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..27673fd2ff1609d06024d26da1bb8b84074c20c9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1GemmHorizontalThreadblockSwizzle-members.html
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::GemmHorizontalThreadblockSwizzle , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1MmaPolicy-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1MmaPolicy-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..5b38fe060122c586d960592c95b225e2169164e9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1threadblock_1_1MmaPolicy-members.html
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK > , including all inherited members.
+
+ kPartitionsK cutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK > static
+ Operator typedefcutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK >
+ SmemPaddingA typedefcutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK >
+ SmemPaddingB typedefcutlass::gemm::threadblock::MmaPolicy< Operator_, SmemPaddingA_, SmemPaddingB_, PartitionsK >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaTensorOpPolicy-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaTensorOpPolicy-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..c7c0d8ca58396cef50ff88ff0fd7547f93ae67c7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaTensorOpPolicy-members.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::warp::MmaTensorOpPolicy< Operator_, OpDelta_ > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpAccumulatorTileIterator_1_1Policy-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpAccumulatorTileIterator_1_1Policy-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..c76556d1f75c28ea9f7206c9f5b3c5e4ce175e3d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpAccumulatorTileIterator_1_1Policy-members.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >::Policy , including all inherited members.
+
+ InterleavedTile typedefcutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >::Policy
+ MmaIterations typedefcutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >::Policy
+ TileIterations typedefcutlass::gemm::warp::MmaVoltaTensorOpAccumulatorTileIterator< Shape_, Element_, Layout_, InstructionShape_, OpDelta_ >::Policy
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Opera5da07caa645948ad891c884c71a4e5f2.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Opera5da07caa645948ad891c884c71a4e5f2.html
new file mode 100644
index 0000000000000000000000000000000000000000..f5383c646555a91c16d15f3997ad3b14fed0488e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1gemm_1_1warp_1_1MmaVoltaTensorOpMultiplicandTileIterator_3_01Shape___00_01Opera5da07caa645948ad891c884c71a4e5f2.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >::Policy , including all inherited members.
+
+ LdsIterations typedefcutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >::Policy
+ LdsShape typedefcutlass::gemm::warp::MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value >, InstructionShape_, OpDelta_, 32 >::Policy
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1ColumnMajorTensorOpMultiplicandCrosswise.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1ColumnMajorTensorOpMultiplicandCrosswise.html
new file mode 100644
index 0000000000000000000000000000000000000000..562e70fdf657b53e850e7715f1c87caa0bb057d4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1ColumnMajorTensorOpMultiplicandCrosswise.html
@@ -0,0 +1,645 @@
+
+
+
+
+
+
+CUTLASS: cutlass::layout::ColumnMajorTensorOpMultiplicandCrosswise< ElementSize, Crosswise > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <tensor_op_multiplicand_sm75.h >
+
+
+
template<int ElementSize, int Crosswise>
+struct cutlass::layout::ColumnMajorTensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+
+
Template mapping a column-major view of pitch-linear memory to TensorOpMultiplicandCrosswise
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
Compute the number of contiguous elements needed to store a tensor with the given size
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
Returns the offset of a coordinate in linear memory. Assumes coordinate has convention (contiguous, strided)
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
+
+
+
+template<int ElementSize, int Crosswise>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandColumnMajorInterleaved-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandColumnMajorInterleaved-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..134549401810fcefe4132f65f7834f49b0b62036
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandColumnMajorInterleaved-members.html
@@ -0,0 +1,131 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > , including all inherited members.
+
+ capacity (TensorCoord const &extent) const cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+ Index typedefcutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK >
+ kAccessSize cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ kElementSize cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ kElementsPerAccess cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ kInterleavedK cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ kRank cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ kStrideRank cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > static
+ LongIndex typedefcutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK >
+ operator() (TensorCoord const &coord) const cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+ packed (TensorCoord const &extent)cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline static
+ stride () const cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+ stride ()cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+ Stride typedefcutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK >
+ TensorCoord typedefcutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK >
+ TensorOpMultiplicandColumnMajorInterleaved (Index ldm=0)cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+ TensorOpMultiplicandColumnMajorInterleaved (Stride stride)cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCongruous-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCongruous-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..f15e79de4fd7b4e6ca5195ee35a93c005b612852
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCongruous-members.html
@@ -0,0 +1,136 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > , including all inherited members.
+
+ AccessCount typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ Base typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ capacity (TensorCoord const &extent) const cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ Index typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ inverse (LongIndex offset) const cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ kAccessSize cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > static
+ kElementSize cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > static
+ kElementsPerAccess cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > static
+ kRank cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > static
+ kStrideRank cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > static
+ LongIndex typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ operator() (TensorCoord const &coord) const cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ packed (TensorCoord const &extent)cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline static
+ PartitionCount typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ PartitionShape typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ stride () const cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ stride ()cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ Stride typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ TensorCoord typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+ TensorOpMultiplicandCongruous (Index ldm=0)cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ TensorOpMultiplicandCongruous (Stride stride)cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise > inline
+ TileShape typedefcutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCrosswise-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCrosswise-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..b10418489acb00d8d614d5bd929226d45046e94c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandCrosswise-members.html
@@ -0,0 +1,138 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > , including all inherited members.
+
+ AccessCount typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ Base typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ capacity (TensorCoord const &extent) const cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ Index typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ inverse (LongIndex offset) const cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ kAccessSize cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kCrosswise cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kElementSize cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kElementsPerAccess cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kFactor cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kRank cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ kStrideRank cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > static
+ LongIndex typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ operator() (TensorCoord const &coord) const cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ packed (TensorCoord const &extent)cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline static
+ PartitionCount typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ PartitionShape typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ stride () const cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ stride ()cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ Stride typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ TensorCoord typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+ TensorOpMultiplicandCrosswise (Index ldm=0)cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ TensorOpMultiplicandCrosswise (Stride stride)cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise > inline
+ TileShape typedefcutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandRowMajorInterleaved-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandRowMajorInterleaved-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..d78277453d618a431e2adc58cac8a855d59c66ac
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1layout_1_1TensorOpMultiplicandRowMajorInterleaved-members.html
@@ -0,0 +1,131 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > , including all inherited members.
+
+ capacity (TensorCoord const &extent) const cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+ Index typedefcutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK >
+ kAccessSize cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ kElementSize cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ kElementsPerAccess cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ kInterleavedK cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ kRank cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ kStrideRank cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > static
+ LongIndex typedefcutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK >
+ operator() (TensorCoord const &coord) const cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+ packed (TensorCoord const &extent)cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline static
+ stride () const cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+ stride ()cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+ Stride typedefcutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK >
+ TensorCoord typedefcutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK >
+ TensorOpMultiplicandRowMajorInterleaved (Index ldm=0)cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+ TensorOpMultiplicandRowMajorInterleaved (Stride stride)cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmArrayConfiguration__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmArrayConfiguration__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..12cd7b73faa8f96eb2cedf5e4a933ae75eabacb8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmArrayConfiguration__coll__graph.md5
@@ -0,0 +1 @@
+6360f66436a5f77f2e50b8ac908ca57d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmConfiguration-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmConfiguration-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..1667282fc1157bf2ad7f9499afaeda61ed299a95
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmConfiguration-members.html
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::library::GemmConfiguration , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmDescription-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmDescription-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..61638a939c2865ec0d4b0ca595aeb7d6df2ecb2a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1GemmDescription-members.html
@@ -0,0 +1,127 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::library::GemmDescription , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..cc76c0e0e3a3609375abf8d438a8d5215c3f42db
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription-members.html
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::library::TileDescription , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..652069a3b96f1e3f4430d6a090ff76950f77f92b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1library_1_1TileDescription__coll__graph.md5
@@ -0,0 +1 @@
+542fd71660ddb8a4a75809a3773dde56
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1log2__down.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1log2__down.html
new file mode 100644
index 0000000000000000000000000000000000000000..c3a0f231e0c79dca78542c4bd96056c9c113296a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1log2__down.html
@@ -0,0 +1,151 @@
+
+
+
+
+
+
+CUTLASS: cutlass::log2_down< N, CurrentVal, Count > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <fast_math.h >
+
+
+enum { value = log2_down<N, (CurrentVal >> 1), Count + 1>::value
+ } Static logarithm value. More...
+
+
+
+
+
template<int N, int CurrentVal = N, int Count = 0>
+struct cutlass::log2_down< N, CurrentVal, Count >
+
+
Statically determine log2(N), rounded down
+
+
+
+
+
+template<int N, int CurrentVal = N, int Count = 0>
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1maximum_3_01float_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1maximum_3_01float_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..45ca06a3bc225ad757cbc8db6b9bccbb2e9cdb7c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1maximum_3_01float_01_4.html
@@ -0,0 +1,160 @@
+
+
+
+
+
+
+CUTLASS: cutlass::maximum< float > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <functional.h >
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1minus_3_01Array_3_01half__t_00_01N_01_4_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1minus_3_01Array_3_01half__t_00_01N_01_4_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..5b5cb281185f839a0802bf2410bc3c069168c418
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1minus_3_01Array_3_01half__t_00_01N_01_4_01_4.html
@@ -0,0 +1,238 @@
+
+
+
+
+
+
+CUTLASS: cutlass::minus< Array< half_t, N > > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <functional.h >
+
+
+CUTLASS_HOST_DEVICE Array< half_t , N > operator() (Array< half_t , N > const &lhs, Array< half_t , N > const &rhs) const
+
+CUTLASS_HOST_DEVICE Array< half_t , N > operator() (half_t const &lhs, Array< half_t , N > const &rhs) const
+
+CUTLASS_HOST_DEVICE Array< half_t , N > operator() (Array< half_t , N > const &lhs, half_t const &rhs) const
+
+
+
+
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1multiply__add_3_01Array_3_01T_00_01N_01_4_00_01Array_3_01T_00_01N_01_4_00_01Arrc22976a5dc70dc30cb0b8cb0caf7ab47.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1multiply__add_3_01Array_3_01T_00_01N_01_4_00_01Array_3_01T_00_01N_01_4_00_01Arrc22976a5dc70dc30cb0b8cb0caf7ab47.html
new file mode 100644
index 0000000000000000000000000000000000000000..77dfb26eab5366e959bb289ed41207377343cb98
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1multiply__add_3_01Array_3_01T_00_01N_01_4_00_01Array_3_01T_00_01N_01_4_00_01Arrc22976a5dc70dc30cb0b8cb0caf7ab47.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::multiply_add< Array< T, N >, Array< T, N >, Array< T, N > > , including all inherited members.
+
+ operator() (Array< T, N > const &a, Array< T, N > const &b, Array< T, N > const &c) const cutlass::multiply_add< Array< T, N >, Array< T, N >, Array< T, N > > inline
+ operator() (Array< T, N > const &a, T const &scalar, Array< T, N > const &c) const cutlass::multiply_add< Array< T, N >, Array< T, N >, Array< T, N > > inline
+ operator() (T const &scalar, Array< T, N > const &b, Array< T, N > const &c) const cutlass::multiply_add< Array< T, N >, Array< T, N >, Array< T, N > > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01const_01volatile_01value__t_01_4__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01const_01volatile_01value__t_01_4__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ca49896db662b4dc9050a962ee0cc4a6d70abd5a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01const_01volatile_01value__t_01_4__inherit__graph.md5
@@ -0,0 +1 @@
+556d6238e325a9e9bd5920cfc95eef33
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01float4_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01float4_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..230ee6cc7e8079b94a35afaaf7131955f2056b77
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01float4_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::platform::alignment_of< float4 > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01int4_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01int4_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..c29465e1cb15135b30e347607f19a5a0a9ab342c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01int4_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::platform::alignment_of< int4 > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01uint4_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01uint4_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..3e89f06c8e00c5d267c5f641176239febada64a3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1alignment__of_3_01uint4_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::platform::alignment_of< uint4 > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1default__delete.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1default__delete.html
new file mode 100644
index 0000000000000000000000000000000000000000..1cdc3e0c00fd14c5ca5708a368579298d905bdb3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1default__delete.html
@@ -0,0 +1,155 @@
+
+
+
+
+
+
+CUTLASS: cutlass::platform::default_delete< T > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Default deleter.
+
+
+
#include <platform.h >
+
+
+
+
+
+
+template<typename T >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__fundamental__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__fundamental__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3958930564e17c5ba29de55937877e20072ec7ba
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__fundamental__coll__graph.md5
@@ -0,0 +1 @@
+a4b4122e668d3cc26ae6e5ea753703dc
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01char_01_4__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01char_01_4__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..de2b3459bd336f137be11db5e87ebf4cfee97b6b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01char_01_4__coll__graph.md5
@@ -0,0 +1 @@
+c9a4b468194d64a4bff79df3781bfaa9
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..37bb1bf3ca351d7629aca51a7c4cffd79753ed31
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4.html
@@ -0,0 +1,149 @@
+
+
+
+
+
+
+CUTLASS: cutlass::platform::is_integral< const volatile T > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <platform.h >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..ea67c3d591c570bd4b8982efa6c6a2a3190ce7d7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01const_01volatile_01T_01_4__inherit__graph.md5
@@ -0,0 +1 @@
+26292c18d46d1fd05122d232891902ae
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01long_01long_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01long_01long_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..83f0ae467c6680cc18c5e8c23581a265616d06df
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01long_01long_01_4.html
@@ -0,0 +1,149 @@
+
+
+
+
+
+
+CUTLASS: cutlass::platform::is_integral< long long > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <platform.h >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01signed_01char_01_4.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01signed_01char_01_4.html
new file mode 100644
index 0000000000000000000000000000000000000000..a7a5011310ae68cd2feb70510cf8d9b6a76f3af1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01signed_01char_01_4.html
@@ -0,0 +1,149 @@
+
+
+
+
+
+
+CUTLASS: cutlass::platform::is_integral< signed char > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <platform.h >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d821a0e333fa3a6dded55517769ffd878d860930
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__coll__graph.md5
@@ -0,0 +1 @@
+9ad1de75c2e999a8d4ccdd300a2d1d03
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..cfb3c6bdb2b7fa2e6de3c126f4fb7332c3a94b46
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__integral_3_01unsigned_01short_01_4__inherit__graph.md5
@@ -0,0 +1 @@
+4d1e77742faee400bce0a8155e5843b5
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__pointer__helper_3_01T_01_5_01_4__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__pointer__helper_3_01T_01_5_01_4__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..d0ae8c921492e6da1596a5c4488e660ce70ebbf1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__pointer__helper_3_01T_01_5_01_4__coll__graph.md5
@@ -0,0 +1 @@
+4449e3114fdb1086fd3fa4b23b10139c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__volatile_3_01volatile_01T_01_4__inherit__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__volatile_3_01volatile_01T_01_4__inherit__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3e64dbc792d5c96ae312b3daf9a05c64831b4dee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1platform_1_1is__volatile_3_01volatile_01T_01_4__inherit__graph.md5
@@ -0,0 +1 @@
+e18a7063ce09369badbe5bfa9f0b0d5c
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1kernel_1_1ReduceSplitK_1_1Params.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1kernel_1_1ReduceSplitK_1_1Params.html
new file mode 100644
index 0000000000000000000000000000000000000000..4c49aec9f195cd5e476324ac7b0cdab095bf4a16
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1kernel_1_1ReduceSplitK_1_1Params.html
@@ -0,0 +1,368 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reduction::kernel::ReduceSplitK< Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >::Params Struct Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Params structure.
+
+
+
#include <reduce_split_k.h >
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+ CUTLASS_HOST_DEVICE cutlass::reduction::kernel::ReduceSplitK < Shape_, OutputOp_, ReductionOp_, PartitionsPerStage >::Params::Params
+ (
+ MatrixCoord
+ problem_size_ ,
+
+
+
+
+ int
+ partitions_ ,
+
+
+
+
+ size_t
+ partition_stride_ ,
+
+
+
+
+ WorkspaceTensorRef
+ workspace_ ,
+
+
+
+
+ OutputTensorRef
+ destination_ ,
+
+
+
+
+ OutputTensorRef
+ source_ ,
+
+
+
+
+ typename OutputOp::Params
+ output_ = typename OutputOp::Params(),
+
+
+
+
+ typename ReductionOp::Params
+ reduction_ = typename ReductionOp::Params()
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
+
+
+
+template<typename Shape_ , typename OutputOp_ , typename ReductionOp_ , int PartitionsPerStage = 4>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1thread_1_1Reduce_3_01plus_3_01half__t_01_4_00_01Array_3_01half__t_00_01N_01_4_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1thread_1_1Reduce_3_01plus_3_01half__t_01_4_00_01Array_3_01half__t_00_01N_01_4_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..358eb842151f15305ba93f64827932bebb37c447
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reduction_1_1thread_1_1Reduce_3_01plus_3_01half__t_01_4_00_01Array_3_01half__t_00_01N_01_4_01_4-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reduction::thread::Reduce< plus< half_t >, Array< half_t, N > > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1Gemm_3_01ElementA_00_01LayoutA_00_01ElementB_00_01Layout369ab66cb5af61d94815b1554b7ffdd3.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1Gemm_3_01ElementA_00_01LayoutA_00_01ElementB_00_01Layout369ab66cb5af61d94815b1554b7ffdd3.html
new file mode 100644
index 0000000000000000000000000000000000000000..0edb01bc577ad6b5a542e037b26bd227f8dea358
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1Gemm_3_01ElementA_00_01LayoutA_00_01ElementB_00_01Layout369ab66cb5af61d94815b1554b7ffdd3.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reference::device::Gemm< ElementA, LayoutA, ElementB, LayoutB, ElementC, LayoutC, ScalarType, AccumulatorType, arch::OpXorPopc > , including all inherited members.
+
+ operator() (gemm::GemmCoord problem_size, ScalarType alpha, TensorRef< ElementA, LayoutA > tensor_a, TensorRef< ElementB, LayoutB > tensor_b, ScalarType beta, TensorRef< ElementC, LayoutC > tensor_c, AccumulatorType initial_accum=AccumulatorType(0))cutlass::reference::device::Gemm< ElementA, LayoutA, ElementB, LayoutB, ElementC, LayoutC, ScalarType, AccumulatorType, arch::OpXorPopc > inline
+ operator() (gemm::GemmCoord problem_size, ScalarType alpha, TensorRef< ElementA, LayoutA > tensor_a, TensorRef< ElementB, LayoutB > tensor_b, ScalarType beta, TensorRef< ElementC, LayoutC > tensor_c, TensorRef< ElementC, LayoutC > tensor_d, AccumulatorType initial_accum=AccumulatorType(0))cutlass::reference::device::Gemm< ElementA, LayoutA, ElementB, LayoutB, ElementC, LayoutC, ScalarType, AccumulatorType, arch::OpXorPopc > inline
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalInFunc__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalInFunc__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..351c1fbe662e8bab2f64fa23a88b638252133bc2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalInFunc__coll__graph.md5
@@ -0,0 +1 @@
+62adef1ea7a652ac7ea34a7f55cc4247
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalOutFunc_1_1Params__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalOutFunc_1_1Params__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..80ccce71a596fae6e3444466ac243fcffae75b99
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorCopyDiagonalOutFunc_1_1Params__coll__graph.md5
@@ -0,0 +1 @@
+074d316e5dd36acc494a28461d061712
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc.html
new file mode 100644
index 0000000000000000000000000000000000000000..d2f84f1269090f91f47e97aec8a4d76bb208c247
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc.html
@@ -0,0 +1,314 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::device::detail::TensorFillRandomGaussianFunc< Element, Layout > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Computes a random Gaussian distribution.
+ More...
+
+
#include <tensor_fill.h >
+
+
+
+
+
template<typename Element, typename Layout>
+struct cutlass::reference::device::detail::TensorFillRandomGaussianFunc< Element, Layout >
+
+
< Layout function
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
+
+
+
+template<typename Element , typename Layout >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..de6ba5ffee9fba88dd81f68eb6ec7eee9d3f2460
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillRandomGaussianFunc__coll__graph.md5
@@ -0,0 +1 @@
+b7891f3be01c3e9f2370156f0609f5e5
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..c5f1f4a718656f9364ded3b681f550087a962ff8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach-members.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reference::host::BlockForEach< Element, Func > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach.html
new file mode 100644
index 0000000000000000000000000000000000000000..55603957a963c49989a60a3281802ec864588664
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1BlockForEach.html
@@ -0,0 +1,169 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::host::BlockForEach< Element, Func > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <tensor_foreach.h >
+
+
+ BlockForEach (Element *ptr, size_t capacity, typename Func::Params params=typename Func::Params())
+ Constructor performs the operation. More...
+
+
+
+
+
+
+
+template<typename Element , typename Func >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1Gemm.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1Gemm.html
new file mode 100644
index 0000000000000000000000000000000000000000..842cbd55dfdc5a5b8a9848a70c243958533b2167
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1Gemm.html
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::host::Gemm< ElementA, LayoutA, ElementB, LayoutB, ElementC, LayoutC, ScalarType, ComputeType, InnerProductOp > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <gemm.h >
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1RandomGaussianFunc-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1RandomGaussianFunc-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..9035c926d1d6939071bffb2f2ee2dee44f863f0d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1RandomGaussianFunc-members.html
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reference::host::detail::RandomGaussianFunc< Element > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillGaussianFunc.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillGaussianFunc.html
new file mode 100644
index 0000000000000000000000000000000000000000..dc46b994b7b053a32878724146814b5b145b1dad
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillGaussianFunc.html
@@ -0,0 +1,266 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::host::detail::TensorFillGaussianFunc< Element, Layout > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Computes a random Gaussian distribution.
+ More...
+
+
#include <tensor_fill.h >
+
+
+
+
+
template<typename Element, typename Layout>
+struct cutlass::reference::host::detail::TensorFillGaussianFunc< Element, Layout >
+
+
< Layout function
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..286a890fd714d2daf4b6b7af5b4ad985c7ca9063
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc-members.html
@@ -0,0 +1,121 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout > , including all inherited members.
+
+ operator() (Coord< Layout::kRank > const &coord) const cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout > inline
+ s cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout >
+ TensorFillLinearFunc ()cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout > inline
+ TensorFillLinearFunc (TensorView const &view_, Array< Element, Layout::kRank > const &v_, Element s_=Element(0))cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout > inline
+ TensorView typedefcutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout >
+ v cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout >
+ view cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout >
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc.html
new file mode 100644
index 0000000000000000000000000000000000000000..29f9fd4f54d9bbaf4441f5fdad672f84d3c24934
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc.html
@@ -0,0 +1,310 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::host::detail::TensorFillLinearFunc< Element, Layout > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
< Layout function
+
+
+
#include <tensor_fill.h >
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
+
+
+
+template<typename Element, typename Layout>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillRandomUniformFunc-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillRandomUniformFunc-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..440b818d6147ba49a402a627c53b24abebfe8250
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillRandomUniformFunc-members.html
@@ -0,0 +1,119 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::reference::host::detail::TensorFillRandomUniformFunc< Element, Layout > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp.html
new file mode 100644
index 0000000000000000000000000000000000000000..4c36f20682e0021f17f403f0f063685e04a6e4e4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp.html
@@ -0,0 +1,313 @@
+
+
+
+
+
+
+CUTLASS: cutlass::reference::host::detail::TensorFuncBinaryOp< ElementA, LayoutA, ElementB, LayoutB, ElementD, LayoutD, BinaryFunc > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Helper to apply a binary operator in place.
+
+
+
#include <tensor_elementwise.h >
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+ cutlass::reference::host::detail::TensorFuncBinaryOp < ElementA, LayoutA, ElementB, LayoutB, ElementD, LayoutD, BinaryFunc >::TensorFuncBinaryOp
+ (
+ TensorView < ElementD, LayoutD > const &
+ view_d_ ,
+
+
+
+
+ TensorRef < ElementA, LayoutA > const &
+ ref_a_ ,
+
+
+
+
+ TensorRef < ElementB, LayoutB > const &
+ ref_b_ ,
+
+
+
+
+ BinaryFunc
+ func = BinaryFunc()
+
+
+
+ )
+
+
+
+
+
+inline
+
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
+
+
+
+template<typename ElementA , typename LayoutA , typename ElementB , typename LayoutB , typename ElementD , typename LayoutD , typename BinaryFunc >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp__coll__graph.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp__coll__graph.md5
new file mode 100644
index 0000000000000000000000000000000000000000..41e2ec169c2cbb140fc0685b1460944e00adc2f7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFuncBinaryOp__coll__graph.md5
@@ -0,0 +1 @@
+99705019e45a6546ffa1ec42c0fe1c87
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1sizeof__bits.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1sizeof__bits.html
new file mode 100644
index 0000000000000000000000000000000000000000..76760e3c1c4c5f58228d69aeac11a6907f74ea20
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1sizeof__bits.html
@@ -0,0 +1,151 @@
+
+
+
+
+
+
+CUTLASS: cutlass::sizeof_bits< T > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Defines the size of an element in bits.
+
+
+
#include <numeric_types.h >
+
+
+static int const value = sizeof(T) * 8
+
+
+
+
+
+
+
+template<typename T>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1PitchLinearTilePolicyStripminedThreadStrided.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1PitchLinearTilePolicyStripminedThreadStrided.html
new file mode 100644
index 0000000000000000000000000000000000000000..021d959c10386d865d464986dfb4d4b1f110f38c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1PitchLinearTilePolicyStripminedThreadStrided.html
@@ -0,0 +1,274 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::PitchLinearTilePolicyStripminedThreadStrided< Shape, Threads, ElementsPerAccess > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <pitch_linear_thread_map.h >
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+inline static
+
+
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
+
+
+
+template<typename Shape , int Threads, int ElementsPerAccess = 1>
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMap.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMap.html
new file mode 100644
index 0000000000000000000000000000000000000000..6a8635af2d7916fdfd780ac644a906abc185fe35
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMap.html
@@ -0,0 +1,326 @@
+
+
+
+
+
+
+CUTLASS: cutlass::transform::TransposePitchLinearThreadMap< ThreadMap_, WarpThreadArrangement_ > Struct Template Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#include <pitch_linear_thread_map.h >
+
+
+struct Detail
+ Internal details made public to facilitate introspection Iterations along each dimension (concept: PitchLinearShape) More...
+
+
+
+static int const kThreads = ThreadMap::kThreads
+ Number of threads total. More...
+
+static int const kElementsPerAccess = ThreadMap::kElementsPerAccess
+ Extract vector length from Layout. More...
+
+
+
+
template<typename ThreadMap_, typename WarpThreadArrangement_>
+struct cutlass::transform::TransposePitchLinearThreadMap< ThreadMap_, WarpThreadArrangement_ >
+
+
Transpose the existing ThreadMap. For example, interleaved layout is like congruous in the global memory and crosswise in the shared memory. We need to transpose the coordinates between two.
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+inline static
+
+
+
+
Maps thread ID to a coordinate offset within the tensor's logical coordinate space Note this is slightly different from the one of PitchLinearWarpRakedThreadMap .
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
+
+
+
+template<typename ThreadMap_ , typename WarpThreadArrangement_ >
+
+
+
+
+
+
The documentation for this struct was generated from the following file:
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMapSimt-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMapSimt-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..7939c2ec954b9aeecde9bbb7785efea8f2e5062e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1TransposePitchLinearThreadMapSimt-members.html
@@ -0,0 +1,123 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for cutlass::transform::TransposePitchLinearThreadMapSimt< ThreadMap_ > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_06b6dd3317cd1748fb948900df8beec57.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_06b6dd3317cd1748fb948900df8beec57.html
new file mode 100644
index 0000000000000000000000000000000000000000..8ef4abfdf570bcf7d874f96778dd844103344810
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_06b6dd3317cd1748fb948900df8beec57.html
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structstd_1_1numeric__limits_3_01cutlass_1_1half__t_01_4-members.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structstd_1_1numeric__limits_3_01cutlass_1_1half__t_01_4-members.html
new file mode 100644
index 0000000000000000000000000000000000000000..0828d20fac322203a7a328668ede4e676ff05404
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/structstd_1_1numeric__limits_3_01cutlass_1_1half__t_01_4-members.html
@@ -0,0 +1,137 @@
+
+
+
+
+
+
+CUTLASS: Member List
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
This is the complete list of members for std::numeric_limits< cutlass::half_t > , including all inherited members.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..772790a362d8c6ccc6f654f790fb60782730082a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor_8h_source.html
@@ -0,0 +1,169 @@
+
+
+
+
+
+
+CUTLASS: tensor.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 100 extent.
w () * extent.
c (),
101 extent.
h () * extent.
w () * extent.
c ()
125 int n = 0, h = 0, w = 0, c = 0;
127 #if defined(__CUDA_ARCH__) 129 c = int(index % static_cast<int>(stride_[0]));
131 unsigned int hw_mul, hw_shr, w_mul, w_shr, c_mul, c_shr;
137 fast_divmod (n, tmp, index,
int (stride_[2]), hw_mul, hw_shr);
138 fast_divmod (h, w, tmp,
int (stride_[1]), w_mul, w_shr);
139 fast_divmod (w, tmp, w,
int (stride_[0]), c_mul, c_shr);
142 n = int(index / (stride_[0] * stride_[1] * stride_[2]));
143 LongIndex residual = index % (stride_[0] * stride_[1] * stride_[2]);
145 h = int(residual / (stride_[0] * stride_[1]));
146 residual = (residual % (stride_[0] * stride_[1]));
148 w = int(residual / stride_[0]);
149 c = int(residual % stride_[0]);
173 if ((extent.
c () > stride_[0])
174 || (extent.
w () * stride_[0] > stride_[1])
175 || (extent.
h () * stride_[1] > stride_[2])) {
178 return extent.
n () * stride_[2];
189 static int const kRank = 4;
192 static int const kStrideRank = 3;
229 extent.
w () * extent.
h (),
230 extent.
h () * extent.
w () * extent.
c ()
259 return extent.
n () * stride_[2];
266 template <
int Interleave>
271 static int const kInterleave = Interleave;
274 static int const kRank = 4;
277 static int const kStrideRank = 3;
313 kInterleave * extent.
w (),
314 kInterleave * extent.
w () * extent.
h (),
315 extent.
h () * extent.
w () * extent.
c ()
324 Index c_minor = (coord.
c () % kInterleave);
325 Index c_major = (coord.
c () / kInterleave);
349 return extent.
n () * stride_[2];
356 template <
int Interleave>
361 static int const kInterleave = Interleave;
364 static int const kRank = 4;
367 static int const kStrideRank = 3;
403 kInterleave * extent.
n (),
404 kInterleave * extent.
n () * extent.
w (),
405 kInterleave * extent.
n () * extent.
w () * extent.
h ()
414 Index c_minor = (coord.
c () % kInterleave);
415 Index c_major = (coord.
c () / kInterleave);
439 return (extent.
c () / kInterleave * stride_[2]);
Coord< kStrideRank > Stride
Stride vector.
Definition: tensor.h:71
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor.h:246
+
Defines a canonical 4D coordinate used by tensor operations.
Definition: tensor_coord.h:38
+
CUTLASS_HOST_DEVICE TensorCxRSKx(Stride const &stride=Stride(0))
Constructor.
Definition: tensor.h:396
+
Definition: aligned_buffer.h:35
+
CUTLASS_HOST_DEVICE void fast_divmod(int &quo, int &rem, int src, int div, unsigned int mul, unsigned int shr)
Definition: fast_math.h:176
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor.h:348
+
CUTLASS_HOST_DEVICE TensorNCxHWx(Stride const &stride=Stride(0))
Constructor.
Definition: tensor.h:306
+
static int const kStrideRank
Rank of stride vector.
Definition: tensor.h:59
+
static CUTLASS_HOST_DEVICE TensorNCxHWx packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor.h:310
+
A Coord is a coordinate of arbitrary rank into a tensor or matrix.
+
CUTLASS_HOST_DEVICE Coord< 1 > make_Coord(int _0)
Helper to make a 2-element coordinate.
Definition: coord.h:387
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Returns the offset of a coordinate in linear memory.
Definition: tensor.h:412
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor.h:336
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor.h:169
+
int32_t Index
Index type used for coordinates.
Definition: tensor.h:62
+
Tensor4DCoord TensorCoord
Logical coordinate (n, h, w, c)
Definition: tensor.h:68
+
Mapping function for 4-D NC/xHWx tensors.
Definition: tensor.h:267
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor.h:198
+
CUTLASS_HOST_DEVICE Index const & w() const
Returns the column of the coordinate.
Definition: tensor_coord.h:95
+
CUTLASS_HOST_DEVICE TensorNHWC(Stride const &stride=Stride(0))
Constructor.
Definition: tensor.h:88
+
int Index
Index type used to store elements.
Definition: coord.h:55
+
static CUTLASS_HOST_DEVICE TensorNCHW packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor.h:225
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor.h:163
+
CUTLASS_HOST_DEVICE TensorNCHW(Stride const &stride=Stride(0))
Constructor.
Definition: tensor.h:221
+
static int const kRank
Logical rank of tensor.
Definition: tensor.h:56
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor.h:342
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor.h:258
+
CUTLASS_HOST_DEVICE Index const & c() const
Returns the channel of the coordinate.
Definition: tensor_coord.h:103
+
int32_t Index
Index type used for coordinates.
Definition: tensor.h:370
+
CUTLASS_HOST_DEVICE TensorNHWC(typename Stride::Index c, typename Stride::Index wc, typename Stride::Index hwc)
Constructor.
Definition: tensor.h:92
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor.h:432
+
Defines a canonical coordinate for rank=4 tensors offering named indices.
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor.h:426
+
Mapping function for 4-D CxRSKx tensors.
Definition: tensor.h:357
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor.h:65
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
static CUTLASS_HOST_DEVICE TensorNHWC packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed NHWC tensor.
Definition: tensor.h:96
+
Mapping function for 4-D NCHW tensors.
Definition: tensor.h:186
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor.h:157
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor.h:438
+
static CUTLASS_HOST_DEVICE TensorCxRSKx packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor.h:400
+
int32_t Index
Index type used for coordinates.
Definition: tensor.h:195
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Returns the offset of a coordinate in linear memory.
Definition: tensor.h:237
+
+
Mapping function for row-major matrices.
Definition: layout/matrix.h:50
+
CUTLASS_HOST_DEVICE Index const & n() const
Returns the batch of the coordinate.
Definition: tensor_coord.h:79
+
CUTLASS_HOST_DEVICE void find_divisor(unsigned int &mul, unsigned int &shr, unsigned int denom)
Definition: fast_math.h:159
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor.h:373
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor.h:252
+
Defines layout functions used by TensorRef and derived classes.
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Returns the offset of a coordinate in linear memory.
Definition: tensor.h:322
+
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor.h:283
+
CUTLASS_HOST_DEVICE Index const & h() const
Returns the row of the coordinate.
Definition: tensor_coord.h:87
+
Mapping function for 4-D NHWC tensors.
Definition: tensor.h:53
+
int32_t Index
Index type used for coordinates.
Definition: tensor.h:280
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex index) const
Returns the logical coordinate (n, h, w, c) from a given offset in linear memory. ...
Definition: tensor.h:123
+
Basic include for CUTLASS.
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Returns the offset of a coordinate (n, h, w, c) in linear memory.
Definition: tensor.h:108
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm70_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm70_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..5d8126adb0fc2932de3b730692364cd17d0e6e12
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm70_8h_source.html
@@ -0,0 +1,241 @@
+
+
+
+
+
+
+CUTLASS: tensor_op_multiplicand_sm70.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 59 template <
int ElementSize>
145 int vec_strided_idx = coord.
strided ();
156 int permuted_strided_within_tile = (tile_contiguous_residual >> 1);
157 int permuted_contiguous_within_tile = (tile_strided_residual ^ permuted_strided_within_tile) |
158 ((tile_contiguous_residual & 1) << 2);
163 int element_strided = tile_strided_idx *
TileShape::kStrided + permuted_strided_within_tile;
165 return element_contiguous + element_strided * stride_[0];
183 return extent[1] * stride_[0];
190 template <
int ElementSize>
292 template <
int ElementSize>
396 template <
int ElementSize>
481 int vec_strided_idx = coord.
strided ();
492 int permuted_strided_within_tile = (tile_contiguous_residual & 0x3);
493 int permuted_contiguous_within_tile = (tile_strided_residual ^ permuted_strided_within_tile) |
494 (tile_contiguous_residual & 0x4);
500 int element_strided = tile_strided_idx *
TileShape::kStrided + permuted_strided_within_tile;
502 return element_contiguous + element_strided * stride_[0];
520 return extent[1] * stride_[0];
527 template <
int ElementSize>
629 template <
int ElementSize>
732 template <
int ElementSize,
int KBlock>
765 static int const kKBlock = KBlock;
803 int vec_strided_idx = coord.
strided ();
810 int vec_strided_within_tile = vec_contiguous_idx & 0x7;
811 int permuted_vec_contiguous =
812 (vec_strided_idx & (~0xF)) + (vec_strided_idx & 0x3) * 4 +
813 (((vec_strided_idx >> 2) ^ ((vec_strided_idx & 0x10) >> 3)) & 0x3);
815 permuted_vec_contiguous ^= ((vec_strided_within_tile >> 1) & 0x3);
817 int permuted_vec_strided = vec_contiguous_idx;
823 int element_contiguous = permuted_vec_contiguous * kElementsPerAccess +
841 return extent[0] * stride_[0];
847 template <
int ElementSize,
int KBlock>
942 template <
int ElementSize,
int KBlock>
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:388
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Definition: tensor_op_multiplicand_sm70.h:935
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:1021
+
Template mapping a row-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous.
Definition: tensor_op_multiplicand_sm70.h:630
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:537
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:519
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:261
+
CUTLASS_HOST_DEVICE Index const & column() const
Returns the column of the coordinate.
Definition: matrix_coord.h:85
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:604
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCrosswise(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:992
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:69
+
Definition: aligned_buffer.h:35
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:130
+
Coordinate in pitch-linear space.
Definition: pitch_linear.h:52
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:617
+
typename Base::PartitionCount PartitionCount
Definition: tensor_op_multiplicand_sm70.h:228
+
typename Base::PartitionShape PartitionShape
Definition: tensor_op_multiplicand_sm70.h:220
+
static CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:356
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:930
+
A Coord is a coordinate of arbitrary rank into a tensor or matrix.
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:859
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:706
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Definition: tensor_op_multiplicand_sm70.h:1030
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:170
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:382
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandBCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:583
+
typename Base::AccessCount AccessCount
Definition: tensor_op_multiplicand_sm70.h:331
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:926
+
CUTLASS_HOST_DEVICE Index const & row() const
Returns the row of the coordinate.
Definition: matrix_coord.h:77
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:540
+
Definition: tensor_op_multiplicand_sm70.h:848
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:477
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCrosswise(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:996
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:507
+
static int const kElementSize
Definition: tensor_op_multiplicand_sm70.h:97
+
typename Base::TileShape TileShape
Definition: tensor_op_multiplicand_sm70.h:658
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Definition: tensor_op_multiplicand_sm70.h:840
+
typename Base::TileShape TileShape
Definition: tensor_op_multiplicand_sm70.h:321
+
static CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:693
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:267
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:642
+
static CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:134
+
typename Base::PartitionShape PartitionShape
Definition: tensor_op_multiplicand_sm70.h:557
+
Template defining a shape used by pitch-linear operators.
Definition: pitch_linear.h:43
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:1025
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:369
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:200
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:352
+
typename Base::TileShape TileShape
Definition: tensor_op_multiplicand_sm70.h:219
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:513
+
Template mapping a column-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous.
Definition: tensor_op_multiplicand_sm70.h:528
+
static int const kStrided
Definition: pitch_linear.h:45
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCrosswise(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:785
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:623
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:1008
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:405
+
static int const kContiguous
Definition: pitch_linear.h:44
+
typename Base::PartitionCount PartitionCount
Definition: tensor_op_multiplicand_sm70.h:667
+
static int const kElementsPerAccess
Definition: tensor_op_multiplicand_sm70.h:98
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:919
+
static CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:591
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:203
+
typename Base::PartitionCount PartitionCount
Definition: tensor_op_multiplicand_sm70.h:330
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:725
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:598
+
typename Base::PartitionCount PartitionCount
Definition: tensor_op_multiplicand_sm70.h:565
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:951
+
Template mapping a row-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous.
Definition: tensor_op_multiplicand_sm70.h:293
+
static int const kRank
Logical rank of tensor.
Definition: tensor_op_multiplicand_sm70.h:63
+
static CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCrosswise packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:1000
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:305
+
typename Base::PartitionShape PartitionShape
Definition: tensor_op_multiplicand_sm70.h:659
+
CUTLASS_HOST_DEVICE TensorCoord inverse(LongIndex offset) const
Inverse of layout function, mapping linear offset to logical coordinate.
Definition: tensor_op_multiplicand_sm70.h:1014
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCrosswise(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:897
+
Template based on element size (in bits) - defined in terms of pitch-linear memory.
Definition: tensor_op_multiplicand_sm70.h:397
+
typename Base::AccessCount AccessCount
Definition: tensor_op_multiplicand_sm70.h:668
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:363
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:913
+
#define CUTLASS_HOST_DEVICE
Definition: cutlass.h:89
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:302
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandBCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:466
+
static CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCrosswise packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:789
+
CUTLASS_HOST_DEVICE Index const & contiguous() const
Returns the contiguous dimension.
Definition: pitch_linear.h:89
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandBCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:689
+
static CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:470
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:72
+
static CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:254
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:796
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:741
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:719
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:611
+
static CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCrosswise packed(TensorCoord const &extent)
Helper returns a layout to a tightly packed tensor.
Definition: tensor_op_multiplicand_sm70.h:905
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:835
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:274
+
typename Base::AccessCount AccessCount
Definition: tensor_op_multiplicand_sm70.h:566
+
Definition: tensor_op_multiplicand_sm70.h:733
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:348
+
+
Definition: tensor_op_multiplicand_sm70.h:943
+
typename Base::TileShape TileShape
Definition: tensor_op_multiplicand_sm70.h:556
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:639
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:376
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:744
+
static int const kStrideRank
Rank of stride vector.
Definition: tensor_op_multiplicand_sm70.h:66
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:954
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandBCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:587
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:246
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:126
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:182
+
typename Base::AccessCount AccessCount
Definition: tensor_op_multiplicand_sm70.h:229
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandCrosswise(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:781
+
static int const kAccessSize
This layout is optimized for 128b accesses.
Definition: tensor_op_multiplicand_sm70.h:85
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:176
+
Defines layout functions used by TensorRef and derived classes for pitch-linear memory.
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:713
+
CUTLASS_HOST_DEVICE VoltaTensorOpMultiplicandBCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:462
+
int32_t Index
Index type used for coordinates.
Definition: tensor_op_multiplicand_sm70.h:856
+
Template mapping a column-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous.
Definition: tensor_op_multiplicand_sm70.h:191
+
CUTLASS_HOST_DEVICE LongIndex capacity(TensorCoord const &extent) const
Compute the number of contiguous elements needed to store a tensor with the given size...
Definition: tensor_op_multiplicand_sm70.h:286
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:700
+
typename Base::PartitionShape PartitionShape
Definition: tensor_op_multiplicand_sm70.h:322
+
CUTLASS_HOST_DEVICE Stride & stride()
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:280
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCrosswise(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:901
+
int64_t LongIndex
Long index type used for offsets.
Definition: tensor_op_multiplicand_sm70.h:408
+
Template based on element size (in bits) - defined in terms of pitch-linear memory.
Definition: tensor_op_multiplicand_sm70.h:60
+
Basic include for CUTLASS.
+
Definition: matrix_coord.h:39
+
CUTLASS_HOST_DEVICE Index const & strided() const
Returns the column of the coordinate.
Definition: pitch_linear.h:97
+
CUTLASS_HOST_DEVICE Stride stride() const
Returns the stride of the layout.
Definition: tensor_op_multiplicand_sm70.h:831
+
CUTLASS_HOST_DEVICE ColumnMajorVoltaTensorOpMultiplicandCongruous(Stride stride)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:250
+
CUTLASS_HOST_DEVICE LongIndex operator()(TensorCoord const &coord) const
Definition: tensor_op_multiplicand_sm70.h:141
+
CUTLASS_HOST_DEVICE RowMajorVoltaTensorOpMultiplicandBCongruous(Index ldm=0)
Ctor.
Definition: tensor_op_multiplicand_sm70.h:685
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm75_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm75_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..8d8b66ccfb9da1738e0e4316e28cc0fc2937153d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__op__multiplicand__sm75_8h.html
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+CUTLASS: tensor_op_multiplicand_sm75.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the source code of this file.
+
+
+struct cutlass::layout::TensorOpMultiplicand< ElementSize, Crosswise >
+
+struct cutlass::layout::TensorOpMultiplicandCongruous< ElementSize, Crosswise >
+
+struct cutlass::layout::TensorOpMultiplicandCongruous< 32, Crosswise >
+
+struct cutlass::layout::ColumnMajorTensorOpMultiplicandCongruous< ElementSize, Crosswise >
+
+struct cutlass::layout::RowMajorTensorOpMultiplicandCongruous< ElementSize, Crosswise >
+
+struct cutlass::layout::TensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+
+struct cutlass::layout::ColumnMajorTensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+
+struct cutlass::layout::RowMajorTensorOpMultiplicandCrosswise< ElementSize, Crosswise >
+
+struct cutlass::layout::TensorOpMultiplicandColumnMajorInterleaved< ElementSize, InterleavedK >
+ Template based on element size (in bits) - defined in terms of pitch-linear memory. More...
+
+struct cutlass::layout::TensorOpMultiplicandRowMajorInterleaved< ElementSize, InterleavedK >
+ Template based on element size (in bits) - defined in terms of pitch-linear memory. More...
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..a685ccbf6c47aa56e7c7c10056ca5a61605db629
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view_8h__incl.md5
@@ -0,0 +1 @@
+2f1a0d7ff7b61dc7fef5d63b2b41915d
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view__io_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view__io_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..93d6337f42c77dc8ee1b9d5b4e1a3906049a4f53
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tensor__view__io_8h__dep__incl.md5
@@ -0,0 +1 @@
+a8cd04acb9671844b7c099d61bb26738
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2device_2thread_2gemm_8h__dep__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2device_2thread_2gemm_8h__dep__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..17bde0a3f3df1a5b1c86fcdf43948b35414c1af9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2device_2thread_2gemm_8h__dep__incl.md5
@@ -0,0 +1 @@
+3bccc2c6770656909ad537a135330c32
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2host_2gemm__complex_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2host_2gemm__complex_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..3590e0fc7fd1fb36bfcedb0f481a80d6596a2822
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/tools_2util_2include_2cutlass_2util_2reference_2host_2gemm__complex_8h__incl.md5
@@ -0,0 +1 @@
+5788165e8d7ec69e2519ab90c6ed9e20
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/transpose_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/transpose_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..dabb16233df96d580b3b1724df754c6c6ea1f3a1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/transpose_8h_source.html
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+CUTLASS: transpose.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 37 typename TransposeShape,
42 template <
int ElementCount_>
43 struct Transpose <ElementCount_, layout::PitchLinearShape<4,4> , int8_t> {
45 static const int kElementCount = ElementCount_;
48 using Fragment = cutlass::Array<Element, kElementCount>;
50 static_assert (!(kElementCount % TransposeShape::kCount),
"Shape needs to be multiple of 16 elements to do a 4x4 transpose" );
56 int * src_int =
reinterpret_cast< int *
> (&src);
57 int * dst_int =
reinterpret_cast< int *
> (&dst);
60 for (
int i = 0; i < kElementCount / TransposeShape::kCount; i++){
62 int const i0 = 4 * i + 0;
63 int const i1 = 4 * i + 1;
64 int const i2 = 4 * i + 2;
65 int const i3 = 4 * i + 3;
72 int b0, b1, b2, b3, c0;
73 asm volatile (
"prmt.b32 %0, %1, %2, 0x0040;" :
"=r" (b0) :
"r" (a0),
"r" (a1));
74 asm volatile (
"prmt.b32 %0, %1, %2, 0x0040;" :
"=r" (c0) :
"r" (a2),
"r" (a3));
75 asm volatile (
"prmt.b32 %0, %1, %2, 0x5410;" :
"=r" (b0) :
"r" (b0),
"r" (c0));
77 asm volatile (
"prmt.b32 %0, %1, %2, 0x0051;" :
"=r" (b1) :
"r" (a0),
"r" (a1));
78 asm volatile (
"prmt.b32 %0, %1, %2, 0x0051;" :
"=r" (c0) :
"r" (a2),
"r" (a3));
79 asm volatile (
"prmt.b32 %0, %1, %2, 0x5410;" :
"=r" (b1) :
"r" (b1),
"r" (c0));
81 asm volatile (
"prmt.b32 %0, %1, %2, 0x0062;" :
"=r" (b2) :
"r" (a0),
"r" (a1));
82 asm volatile (
"prmt.b32 %0, %1, %2, 0x0062;" :
"=r" (c0) :
"r" (a2),
"r" (a3));
83 asm volatile (
"prmt.b32 %0, %1, %2, 0x5410;" :
"=r" (b2) :
"r" (b2),
"r" (c0));
85 asm volatile (
"prmt.b32 %0, %1, %2, 0x0073;" :
"=r" (b3) :
"r" (a0),
"r" (a1));
86 asm volatile (
"prmt.b32 %0, %1, %2, 0x0073;" :
"=r" (c0) :
"r" (a2),
"r" (a3));
87 asm volatile (
"prmt.b32 %0, %1, %2, 0x5410;" :
"=r" (b3) :
"r" (b3),
"r" (c0));
Definition: aligned_buffer.h:35
+
+
+
+
Template defining a shape used by pitch-linear operators.
Definition: pitch_linear.h:43
+
#define CUTLASS_PRAGMA_UNROLL
Definition: cutlass.h:110
+
+
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__array_8h.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__array_8h.html
new file mode 100644
index 0000000000000000000000000000000000000000..1a0bf7ae7f2b5b86b99456f500a3f6c0e765625b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__array_8h.html
@@ -0,0 +1,129 @@
+
+
+
+
+
+
+CUTLASS: wmma_array.h File Reference
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Statically sized array of elements that accommodates all CUTLASS-supported numeric types and is safe to use in a union.
+More...
+
+
Go to the source code of this file.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__ptx_8h__incl.md5 b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__ptx_8h__incl.md5
new file mode 100644
index 0000000000000000000000000000000000000000..7eee48058576e584a77acfe8baa9aaf3c36d5a73
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__ptx_8h__incl.md5
@@ -0,0 +1 @@
+678d62dda283747c7e12dd7eb9e3b693
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__sm72_8h_source.html b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__sm72_8h_source.html
new file mode 100644
index 0000000000000000000000000000000000000000..ffe37a4d6004e23c49685a5900a8f8c0c2c3cc50
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/3rdparty/cutlass/docs/wmma__sm72_8h_source.html
@@ -0,0 +1,114 @@
+
+
+
+
+
+
+CUTLASS: wmma_sm72.h Source File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ CUTLASS
+
+ CUDA Templates for Linear Algebra Subroutines and Solvers
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Go to the documentation of this file. 59 #if defined(CUTLASS_ARCH_WMMA_SM72_ENABLED) 61 using ElementA = int8_t;
62 using LayoutA = LayoutA_;
63 using ElementB = int8_t;
64 using LayoutB = LayoutB_;
65 using ElementC = int32_t;
66 using LayoutC = LayoutC_;
67 using Operator = cutlass::arch::OpMultiplyAdd;
74 "Supported list of wmma operator shape for s8 multiplicands are: 16x16x16, 8x328x16, and 32x8x16" );
78 using FragmentA = nvcuda::wmma::fragment<
79 nvcuda::wmma::matrix_a,
83 typename CutlassToWmmaDataType<ElementA>::Type,
84 typename CutlassToWmmaLayout<LayoutA>::Layout>;
86 using FragmentB = nvcuda::wmma::fragment<
87 nvcuda::wmma::matrix_b,
91 typename CutlassToWmmaDataType<ElementB>::Type,
92 typename CutlassToWmmaLayout<LayoutB>::Layout>;
94 using FragmentC = nvcuda::wmma::fragment<
95 nvcuda::wmma::accumulator,
99 typename CutlassToWmmaDataType<ElementC>::Type>;
107 FragmentC
const &C)
const {
109 nvcuda::wmma::mma_sync(D, A, B, C);
113 static_assert (
false ,
"wmma.mma.sync interger type multiplicands is avialable only for SM72 and beyond" );
139 #if defined(CUTLASS_ARCH_WMMA_SM72_ENABLED) 140 using Shape = Shape_;
141 using ElementA = uint8_t;
142 using LayoutA = LayoutA_;
143 using ElementB = uint8_t;
144 using LayoutB = LayoutB_;
145 using ElementC = int32_t;
146 using LayoutC = LayoutC_;
147 using Operator = cutlass::arch::OpMultiplyAdd;
154 "Supported list of wmma operator shape for u8 multiplicands are: 16x16x16, 8x328x16, and 32x8x16" );
157 using FragmentA = nvcuda::wmma::fragment<
158 nvcuda::wmma::matrix_a,
162 typename CutlassToWmmaDataType<ElementA>::Type,
163 typename CutlassToWmmaLayout<LayoutA>::Layout>;
165 using FragmentB = nvcuda::wmma::fragment<
166 nvcuda::wmma::matrix_b,
170 typename CutlassToWmmaDataType<ElementB>::Type,
171 typename CutlassToWmmaLayout<LayoutB>::Layout>;
173 using FragmentC = nvcuda::wmma::fragment<
174 nvcuda::wmma::accumulator,
178 typename CutlassToWmmaDataType<ElementC>::Type>;
186 FragmentC
const &C)
const {
188 nvcuda::wmma::mma_sync(D, A, B, C);
192 static_assert (
false ,
"wmma.mma.sync interger type multiplicands is avialable only for SM72 and beyond" );
Definition: aligned_buffer.h:35
+
+
Shape of a matrix multiply-add operation.
Definition: include/cutlass/gemm/gemm.h:57
+
+
Defines layout functions used by TensorRef and derived classes.
+
+
+
+
+
diff --git a/venv/lib/python3.10/site-packages/bitblas/__init__.py b/venv/lib/python3.10/site-packages/bitblas/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ab4554e26616929568a8cb93c4713288f1e9130
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/__init__.py
@@ -0,0 +1,156 @@
+# Copyright (c) Microsoft Corporation.
+# Licensed under the MIT License.
+import sys
+import os
+
+import warnings
+import functools
+import logging
+from tqdm import tqdm
+
+
+class TqdmLoggingHandler(logging.Handler):
+ """Custom logging handler that directs log output to tqdm progress bar to avoid interference."""
+
+ def __init__(self, level=logging.NOTSET):
+ """Initialize the handler with an optional log level."""
+ super().__init__(level)
+
+ def emit(self, record):
+ """Emit a log record. Messages are written to tqdm to ensure output in progress bars isn't corrupted."""
+ try:
+ msg = self.format(record)
+ tqdm.write(msg)
+ except Exception:
+ self.handleError(record)
+
+
+def set_log_level(level):
+ """Set the logging level for the module's logger.
+
+ Args:
+ level (str or int): Can be the string name of the level (e.g., 'INFO') or the actual level (e.g., logging.INFO).
+ OPTIONS: 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'
+ """
+ if isinstance(level, str):
+ level = getattr(logging, level.upper(), logging.INFO)
+ logger = logging.getLogger(__name__)
+ logger.setLevel(level)
+
+
+def _init_logger():
+ """Initialize the logger specific for this module with custom settings and a Tqdm-based handler."""
+ logger = logging.getLogger(__name__)
+ handler = TqdmLoggingHandler()
+ formatter = logging.Formatter(
+ fmt="%(asctime)s [BitBLAS:%(levelname)s]: %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
+ logger.propagate = False
+ set_log_level("WARNING")
+
+
+_init_logger()
+
+
+def deprecated(reason):
+ """
+ This is a decorator which can be used to mark functions as deprecated.
+ It will result in a warning being emitted when the function is used.
+ """
+
+ def decorator(func):
+
+ @functools.wraps(func)
+ def new_func(*args, **kwargs):
+ warnings.warn(
+ f"Call to deprecated function {func.__name__} ({reason}).",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ return func(*args, **kwargs)
+
+ return new_func
+
+ return decorator
+
+
+logger = logging.getLogger(__name__)
+
+# SETUP ENVIRONMENT VARIABLES
+CUTLASS_NOT_FOUND_MESSAGE = ("CUTLASS is not installed or found in the expected path")
+", which may lead to compilation bugs when utilize tilelang backend."
+TL_TEMPLATE_NOT_FOUND_MESSAGE = ("TileLang is not installed or found in the expected path")
+", which may lead to compilation bugs when utilize tilelang backend."
+
+# Handle TVM_IMPORT_PYTHON_PATH to import tvm from the specified path
+TVM_IMPORT_PYTHON_PATH = os.environ.get("TVM_IMPORT_PYTHON_PATH", None)
+
+if TVM_IMPORT_PYTHON_PATH is not None:
+ os.environ["PYTHONPATH"] = (TVM_IMPORT_PYTHON_PATH + ":" + os.environ.get("PYTHONPATH", ""))
+ sys.path.insert(0, TVM_IMPORT_PYTHON_PATH + "/python")
+else:
+ # remove the existing tvm path in PYTHONPATH
+ def remove_tvm_path(path):
+ return "tvm" in path
+
+ # installed 3rdparty tvm
+ install_tvm_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "3rdparty", "tvm")
+ if os.path.exists(install_tvm_path) and install_tvm_path not in sys.path:
+ os.environ["PYTHONPATH"] = ":".join(
+ filter(remove_tvm_path,
+ os.environ.get("PYTHONPATH", "").split(":")))
+ sys.path = [path for path in sys.path if not remove_tvm_path(path)]
+
+ os.environ["PYTHONPATH"] = (
+ install_tvm_path + "/python:" + os.environ.get("PYTHONPATH", ""))
+ sys.path.insert(0, install_tvm_path + "/python")
+
+ # developed 3rdparty tvm
+ develop_tvm_path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "..", "3rdparty", "tvm")
+ if os.path.exists(develop_tvm_path) and develop_tvm_path not in sys.path:
+ os.environ["PYTHONPATH"] = ":".join(
+ filter(remove_tvm_path,
+ os.environ.get("PYTHONPATH", "").split(":")))
+ sys.path = [path for path in sys.path if not remove_tvm_path(path)]
+ os.environ["PYTHONPATH"] = (
+ develop_tvm_path + "/python:" + os.environ.get("PYTHONPATH", ""))
+ sys.path.insert(0, develop_tvm_path + "/python")
+
+if os.environ.get("TL_CUTLASS_PATH", None) is None:
+ install_cutlass_path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "3rdparty", "cutlass")
+ develop_cutlass_path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "..", "3rdparty", "cutlass")
+ if os.path.exists(install_cutlass_path):
+ os.environ["TL_CUTLASS_PATH"] = install_cutlass_path + "/include"
+ elif (os.path.exists(develop_cutlass_path) and develop_cutlass_path not in sys.path):
+ os.environ["TL_CUTLASS_PATH"] = develop_cutlass_path + "/include"
+ else:
+ logger.warning(CUTLASS_NOT_FOUND_MESSAGE)
+
+import tvm as tvm # noqa: E402
+from .base import (
+ TileDevice, # noqa: F401
+ fast_tune, # noqa: F401
+ BlockInfo, # noqa: F401
+ IterInfo, # noqa: F401
+ ScheduleRule, # noqa: F401
+ normalize_prim_func, # noqa: F401
+ try_inline, # noqa: F401
+ try_inline_contiguous_spatial, # noqa: F401
+)
+from .relax import (
+ ApplyDefaultSchedule, # noqa: F401
+ ApplyFastTuning, # noqa: F401
+)
+from .utils import auto_detect_nvidia_target, apply_transform_on_input # noqa: F401
+from .ops.general_matmul import MatmulConfig, Matmul # noqa: F401
+from .ops.general_matmul_splitk import MatmulConfigWithSplitK, MatmulWithSplitK # noqa: F401
+from .ops.general_flashatten import FlashAttenConfig, FlashAtten # noqa: F401
+from .module import Linear # noqa: F401
+
+__version__ = "0.1.0"
diff --git a/venv/lib/python3.10/site-packages/bitblas/common.py b/venv/lib/python3.10/site-packages/bitblas/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1b0aa36192a3e53851450c627deb3645ac1014b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/bitblas/common.py
@@ -0,0 +1,8 @@
+# Copyright (c) Microsoft Corporation.
+# Licensed under the MIT License.
+
+import os
+
+BITBLAS_DEFAULT_CACHE_PATH = os.path.expanduser("~/.cache/bitblas")
+
+MAX_ERROR_MESSAGE_LENGTH = 500
diff --git a/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/METADATA b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..38f9a3b248f89b818d10abc7e78df7d0076bfb68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/METADATA
@@ -0,0 +1,109 @@
+Metadata-Version: 2.4
+Name: blake3
+Version: 1.0.5
+License-File: LICENSE
+Summary: Python bindings for the Rust blake3 crate
+Home-Page: https://github.com/oconnor663/blake3-py
+Author: Jack O'Connor
+Author-email: Jack O'Connor
+License: CC0-1.0 OR Apache-2.0
+Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
+Project-URL: Source Code, https://github.com/oconnor663/blake3-py
+
+# blake3-py [](https://github.com/oconnor663/blake3-py/actions/workflows/tests.yml) [](https://pypi.python.org/pypi/blake3)
+
+Python bindings for the [official Rust implementation of
+BLAKE3](https://github.com/BLAKE3-team/BLAKE3), based on
+[PyO3](https://github.com/PyO3/pyo3). These bindings expose all the features of
+BLAKE3, including extendable output, keying, and multithreading. The basic API
+matches that of Python's standard
+[`hashlib`](https://docs.python.org/3/library/hashlib.html) module.
+
+## Examples
+
+```python
+from blake3 import blake3
+
+# Hash some input all at once. The input can be bytes, a bytearray, or a memoryview.
+hash1 = blake3(b"foobarbaz").digest()
+
+# Hash the same input incrementally.
+hasher = blake3()
+hasher.update(b"foo")
+hasher.update(b"bar")
+hasher.update(b"baz")
+hash2 = hasher.digest()
+assert hash1 == hash2
+
+# Hash the same input fluently.
+assert hash1 == blake3(b"foo").update(b"bar").update(b"baz").digest()
+
+# Hexadecimal output.
+print("The hash of 'hello world' is", blake3(b"hello world").hexdigest())
+
+# Use the keyed hashing mode, which takes a 32-byte key.
+import secrets
+random_key = secrets.token_bytes(32)
+message = b"a message to authenticate"
+mac = blake3(message, key=random_key).digest()
+
+# Use the key derivation mode, which takes a context string. Context strings
+# should be hardcoded, globally unique, and application-specific.
+context = "blake3-py 2020-03-04 11:13:10 example context"
+key_material = b"usually at least 32 random bytes, not a password"
+derived_key = blake3(key_material, derive_key_context=context).digest()
+
+# Extendable output. The default digest size is 32 bytes.
+extended = blake3(b"foo").digest(length=100)
+assert extended[:32] == blake3(b"foo").digest()
+assert extended[75:100] == blake3(b"foo").digest(length=25, seek=75)
+
+# Hash a large input using multiple threads. Note that this can be slower for
+# inputs shorter than ~1 MB, and it's a good idea to benchmark it for your use
+# case on your platform.
+large_input = bytearray(1_000_000)
+hash_single = blake3(large_input).digest()
+hash_two = blake3(large_input, max_threads=2).digest()
+hash_many = blake3(large_input, max_threads=blake3.AUTO).digest()
+assert hash_single == hash_two == hash_many
+
+# Hash a file with multiple threads using memory mapping. This is what b3sum
+# does by default.
+file_hasher = blake3(max_threads=blake3.AUTO)
+file_hasher.update_mmap("/big/file.txt")
+file_hash = file_hasher.digest()
+
+# Copy a hasher that's already accepted some input.
+hasher1 = blake3(b"foo")
+hasher2 = hasher1.copy()
+hasher1.update(b"bar")
+hasher2.update(b"baz")
+assert hasher1.digest() == blake3(b"foobar").digest()
+assert hasher2.digest() == blake3(b"foobaz").digest()
+```
+
+## Installation
+
+```
+pip install blake3
+```
+
+As usual with Pip, you might need to use `sudo` or the `--user` flag
+with the command above, depending on how you installed Python on your
+system.
+
+There are binary wheels [available on
+PyPI](https://pypi.org/project/blake3/#files) for most environments. But
+if you're building the source distribution, or if a binary wheel isn't
+available for your environment, you'll need to [install the Rust
+toolchain](https://rustup.rs).
+
+## C Bindings
+
+Experimental bindings for the official BLAKE3 C implementation are available in
+the [`c_impl`](c_impl) directory. These will probably not be published on PyPI,
+and most applications should prefer the Rust-based bindings. But if you can't
+depend on the Rust toolchain, and you're on some platform that this project
+doesn't provide binary wheels for, the C-based bindings might be an
+alternative.
+
diff --git a/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/RECORD b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..61122efb56235a25bae43fd561bc9bede09543a0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/RECORD
@@ -0,0 +1,10 @@
+blake3-1.0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+blake3-1.0.5.dist-info/METADATA,sha256=lvV0eKv9k--yIyhZWy9CPsqgiNQM_XWIyKaSKg5gyOk,4188
+blake3-1.0.5.dist-info/RECORD,,
+blake3-1.0.5.dist-info/WHEEL,sha256=pM2Fp-Ynaqt8ornuONT9rEZFWixKnS89Tuqp6pz8lXg,129
+blake3-1.0.5.dist-info/licenses/LICENSE,sha256=8dcAngYoiDbFbjtdQhs7F_g1creA1J1w3te3lFGYpeU,18674
+blake3/__init__.py,sha256=i5GXKa35g4Dt_hOK8OmCFGY-6xDtzmTAGlepSFv_0ns,107
+blake3/__init__.pyi,sha256=Ngl-UCmwX3q3E9IWmQGCqbEQhfdkaoSVd1G1QaHtQNg,750
+blake3/__pycache__/__init__.cpython-310.pyc,,
+blake3/blake3.cpython-310-x86_64-linux-gnu.so,sha256=PqS85i8Mke-W85wxScFehKbYyiJuGnf-6ZfE0dAPDII,969920
+blake3/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/WHEEL b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..69ab970975f8987d1d30da6eb46632c7145ca527
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: maturin (1.8.6)
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64
diff --git a/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..fb801df3d05d49f44b754c066474d6f9279d352e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/blake3-1.0.5.dist-info/licenses/LICENSE
@@ -0,0 +1,330 @@
+This work is released into the public domain with CC0 1.0. Alternatively, it is
+licensed under the Apache License 2.0.
+
+-------------------------------------------------------------------------------
+
+Creative Commons Legal Code
+
+CC0 1.0 Universal
+
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
+ HEREUNDER.
+
+Statement of Purpose
+
+The laws of most jurisdictions throughout the world automatically confer
+exclusive Copyright and Related Rights (defined below) upon the creator
+and subsequent owner(s) (each and all, an "owner") of an original work of
+authorship and/or a database (each, a "Work").
+
+Certain owners wish to permanently relinquish those rights to a Work for
+the purpose of contributing to a commons of creative, cultural and
+scientific works ("Commons") that the public can reliably and without fear
+of later claims of infringement build upon, modify, incorporate in other
+works, reuse and redistribute as freely as possible in any form whatsoever
+and for any purposes, including without limitation commercial purposes.
+These owners may contribute to the Commons to promote the ideal of a free
+culture and the further production of creative, cultural and scientific
+works, or to gain reputation or greater distribution for their Work in
+part through the use and efforts of others.
+
+For these and/or other purposes and motivations, and without any
+expectation of additional consideration or compensation, the person
+associating CC0 with a Work (the "Affirmer"), to the extent that he or she
+is an owner of Copyright and Related Rights in the Work, voluntarily
+elects to apply CC0 to the Work and publicly distribute the Work under its
+terms, with knowledge of his or her Copyright and Related Rights in the
+Work and the meaning and intended legal effect of CC0 on those rights.
+
+1. Copyright and Related Rights. A Work made available under CC0 may be
+protected by copyright and related or neighboring rights ("Copyright and
+Related Rights"). Copyright and Related Rights include, but are not
+limited to, the following:
+
+ i. the right to reproduce, adapt, distribute, perform, display,
+ communicate, and translate a Work;
+ ii. moral rights retained by the original author(s) and/or performer(s);
+iii. publicity and privacy rights pertaining to a person's image or
+ likeness depicted in a Work;
+ iv. rights protecting against unfair competition in regards to a Work,
+ subject to the limitations in paragraph 4(a), below;
+ v. rights protecting the extraction, dissemination, use and reuse of data
+ in a Work;
+ vi. database rights (such as those arising under Directive 96/9/EC of the
+ European Parliament and of the Council of 11 March 1996 on the legal
+ protection of databases, and under any national implementation
+ thereof, including any amended or successor version of such
+ directive); and
+vii. other similar, equivalent or corresponding rights throughout the
+ world based on applicable law or treaty, and any national
+ implementations thereof.
+
+2. Waiver. To the greatest extent permitted by, but not in contravention
+of, applicable law, Affirmer hereby overtly, fully, permanently,
+irrevocably and unconditionally waives, abandons, and surrenders all of
+Affirmer's Copyright and Related Rights and associated claims and causes
+of action, whether now known or unknown (including existing as well as
+future claims and causes of action), in the Work (i) in all territories
+worldwide, (ii) for the maximum duration provided by applicable law or
+treaty (including future time extensions), (iii) in any current or future
+medium and for any number of copies, and (iv) for any purpose whatsoever,
+including without limitation commercial, advertising or promotional
+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
+member of the public at large and to the detriment of Affirmer's heirs and
+successors, fully intending that such Waiver shall not be subject to
+revocation, rescission, cancellation, termination, or any other legal or
+equitable action to disrupt the quiet enjoyment of the Work by the public
+as contemplated by Affirmer's express Statement of Purpose.
+
+3. Public License Fallback. Should any part of the Waiver for any reason
+be judged legally invalid or ineffective under applicable law, then the
+Waiver shall be preserved to the maximum extent permitted taking into
+account Affirmer's express Statement of Purpose. In addition, to the
+extent the Waiver is so judged Affirmer hereby grants to each affected
+person a royalty-free, non transferable, non sublicensable, non exclusive,
+irrevocable and unconditional license to exercise Affirmer's Copyright and
+Related Rights in the Work (i) in all territories worldwide, (ii) for the
+maximum duration provided by applicable law or treaty (including future
+time extensions), (iii) in any current or future medium and for any number
+of copies, and (iv) for any purpose whatsoever, including without
+limitation commercial, advertising or promotional purposes (the
+"License"). The License shall be deemed effective as of the date CC0 was
+applied by Affirmer to the Work. Should any part of the License for any
+reason be judged legally invalid or ineffective under applicable law, such
+partial invalidity or ineffectiveness shall not invalidate the remainder
+of the License, and in such case Affirmer hereby affirms that he or she
+will not (i) exercise any of his or her remaining Copyright and Related
+Rights in the Work or (ii) assert any associated claims and causes of
+action with respect to the Work, in either case contrary to Affirmer's
+express Statement of Purpose.
+
+4. Limitations and Disclaimers.
+
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
+ surrendered, licensed or otherwise affected by this document.
+ b. Affirmer offers the Work as-is and makes no representations or
+ warranties of any kind concerning the Work, express, implied,
+ statutory or otherwise, including without limitation warranties of
+ title, merchantability, fitness for a particular purpose, non
+ infringement, or the absence of latent or other defects, accuracy, or
+ the present or absence of errors, whether or not discoverable, all to
+ the greatest extent permissible under applicable law.
+ c. Affirmer disclaims responsibility for clearing rights of other persons
+ that may apply to the Work or any use thereof, including without
+ limitation any person's Copyright and Related Rights in the Work.
+ Further, Affirmer disclaims responsibility for obtaining any necessary
+ consents, permissions or other rights required for any use of the
+ Work.
+ d. Affirmer understands and acknowledges that Creative Commons is not a
+ party to this document and has no duty or obligation with respect to
+ this CC0 or use of the Work.
+
+-------------------------------------------------------------------------------
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2020 Jack O'Connor
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..e1dabf19cec84dadbc2875424decc36e7dd212ed
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/METADATA
@@ -0,0 +1,184 @@
+Metadata-Version: 2.1
+Name: cloudpickle
+Version: 3.0.0
+Summary: Pickler class to extend the standard pickle.Pickler functionality
+Home-page: https://github.com/cloudpipe/cloudpickle
+License: BSD-3-Clause
+Author: The cloudpickle developer team
+Author-email: cloudpipe@googlegroups.com
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: POSIX
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: System :: Distributed Computing
+
+# cloudpickle
+
+[](https://github.com/cloudpipe/cloudpickle/actions)
+[](https://codecov.io/github/cloudpipe/cloudpickle?branch=master)
+
+`cloudpickle` makes it possible to serialize Python constructs not supported
+by the default `pickle` module from the Python standard library.
+
+`cloudpickle` is especially useful for **cluster computing** where Python
+code is shipped over the network to execute on remote hosts, possibly close
+to the data.
+
+Among other things, `cloudpickle` supports pickling for **lambda functions**
+along with **functions and classes defined interactively** in the
+`__main__` module (for instance in a script, a shell or a Jupyter notebook).
+
+Cloudpickle can only be used to send objects between the **exact same version
+of Python**.
+
+Using `cloudpickle` for **long-term object storage is not supported and
+strongly discouraged.**
+
+**Security notice**: one should **only load pickle data from trusted sources** as
+otherwise `pickle.load` can lead to arbitrary code execution resulting in a critical
+security vulnerability.
+
+
+Installation
+------------
+
+The latest release of `cloudpickle` is available from
+[pypi](https://pypi.python.org/pypi/cloudpickle):
+
+ pip install cloudpickle
+
+
+Examples
+--------
+
+Pickling a lambda expression:
+
+```python
+>>> import cloudpickle
+>>> squared = lambda x: x ** 2
+>>> pickled_lambda = cloudpickle.dumps(squared)
+
+>>> import pickle
+>>> new_squared = pickle.loads(pickled_lambda)
+>>> new_squared(2)
+4
+```
+
+Pickling a function interactively defined in a Python shell session
+(in the `__main__` module):
+
+```python
+>>> CONSTANT = 42
+>>> def my_function(data: int) -> int:
+... return data + CONSTANT
+...
+>>> pickled_function = cloudpickle.dumps(my_function)
+>>> depickled_function = pickle.loads(pickled_function)
+>>> depickled_function
+ int>
+>>> depickled_function(43)
+85
+```
+
+
+Overriding pickle's serialization mechanism for importable constructs:
+----------------------------------------------------------------------
+
+An important difference between `cloudpickle` and `pickle` is that
+`cloudpickle` can serialize a function or class **by value**, whereas `pickle`
+can only serialize it **by reference**. Serialization by reference treats
+functions and classes as attributes of modules, and pickles them through
+instructions that trigger the import of their module at load time.
+Serialization by reference is thus limited in that it assumes that the module
+containing the function or class is available/importable in the unpickling
+environment. This assumption breaks when pickling constructs defined in an
+interactive session, a case that is automatically detected by `cloudpickle`,
+that pickles such constructs **by value**.
+
+Another case where the importability assumption is expected to break is when
+developing a module in a distributed execution environment: the worker
+processes may not have access to the said module, for example if they live on a
+different machine than the process in which the module is being developed. By
+itself, `cloudpickle` cannot detect such "locally importable" modules and
+switch to serialization by value; instead, it relies on its default mode, which
+is serialization by reference. However, since `cloudpickle 2.0.0`, one can
+explicitly specify modules for which serialization by value should be used,
+using the
+`register_pickle_by_value(module)`/`/unregister_pickle_by_value(module)` API:
+
+```python
+>>> import cloudpickle
+>>> import my_module
+>>> cloudpickle.register_pickle_by_value(my_module)
+>>> cloudpickle.dumps(my_module.my_function) # my_function is pickled by value
+>>> cloudpickle.unregister_pickle_by_value(my_module)
+>>> cloudpickle.dumps(my_module.my_function) # my_function is pickled by reference
+```
+
+Using this API, there is no need to re-install the new version of the module on
+all the worker nodes nor to restart the workers: restarting the client Python
+process with the new source code is enough.
+
+Note that this feature is still **experimental**, and may fail in the following
+situations:
+
+- If the body of a function/class pickled by value contains an `import` statement:
+ ```python
+ >>> def f():
+ >>> ... from another_module import g
+ >>> ... # calling f in the unpickling environment may fail if another_module
+ >>> ... # is unavailable
+ >>> ... return g() + 1
+ ```
+
+- If a function pickled by reference uses a function pickled by value during its execution.
+
+
+Running the tests
+-----------------
+
+- With `tox`, to test run the tests for all the supported versions of
+ Python and PyPy:
+
+ pip install tox
+ tox
+
+ or alternatively for a specific environment:
+
+ tox -e py312
+
+
+- With `pytest` to only run the tests for your current version of
+ Python:
+
+ pip install -r dev-requirements.txt
+ PYTHONPATH='.:tests' pytest
+
+History
+-------
+
+`cloudpickle` was initially developed by [picloud.com](http://web.archive.org/web/20140721022102/http://blog.picloud.com/2013/11/17/picloud-has-joined-dropbox/) and shipped as part of
+the client SDK.
+
+A copy of `cloudpickle.py` was included as part of PySpark, the Python
+interface to [Apache Spark](https://spark.apache.org/). Davies Liu, Josh
+Rosen, Thom Neale and other Apache Spark developers improved it significantly,
+most notably to add support for PyPy and Python 3.
+
+The aim of the `cloudpickle` project is to make that work available to a wider
+audience outside of the Spark ecosystem and to make it easier to improve it
+further notably with the help of a dedicated non-regression test suite.
+
diff --git a/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..bdcb4519b9c32808df27e1a6960c33ed2e2ecb40
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/RECORD
@@ -0,0 +1,11 @@
+cloudpickle-3.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+cloudpickle-3.0.0.dist-info/METADATA,sha256=KypidktC6rU0wvKKVftMrMAIg3sVaYWMSzkModFn5FY,6955
+cloudpickle-3.0.0.dist-info/RECORD,,
+cloudpickle-3.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+cloudpickle-3.0.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
+cloudpickle/__init__.py,sha256=vb2JCOn1EpLUdVyPe1ESyhLymcvh-Rk3ISHJ-52aDLw,308
+cloudpickle/__pycache__/__init__.cpython-310.pyc,,
+cloudpickle/__pycache__/cloudpickle.cpython-310.pyc,,
+cloudpickle/__pycache__/cloudpickle_fast.cpython-310.pyc,,
+cloudpickle/cloudpickle.py,sha256=APCGMuIfVpWcelGsLlo2zRmwKRloaoiznQEOAoEWH9Y,55283
+cloudpickle/cloudpickle_fast.py,sha256=1GqUD4nLKsv0vv9ty2La3eVLyeWNrPFlhUCN-aNI-30,322
diff --git a/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle-3.0.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.9.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/__init__.py b/venv/lib/python3.10/site-packages/cloudpickle/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..58a8d086ff616b2ef75ab0d788d990e749f96e8d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle/__init__.py
@@ -0,0 +1,18 @@
+from . import cloudpickle
+from .cloudpickle import * # noqa
+
+__doc__ = cloudpickle.__doc__
+
+__version__ = "3.0.0"
+
+__all__ = [ # noqa
+ "__version__",
+ "Pickler",
+ "CloudPickler",
+ "dumps",
+ "loads",
+ "dump",
+ "load",
+ "register_pickle_by_value",
+ "unregister_pickle_by_value",
+]
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..005c5185d80d86755653fa01fdae3e4b75235fb1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8b328b529eccb462b38261288c5d600c427ee98
Binary files /dev/null and b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle_fast.cpython-310.pyc b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle_fast.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ac2d4ab4f620072c2cbfc5ef1d70d1ada7a5b03
Binary files /dev/null and b/venv/lib/python3.10/site-packages/cloudpickle/__pycache__/cloudpickle_fast.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle.py b/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb43a9676bbb11bdecf187e7f6cde51f793ff3fc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle.py
@@ -0,0 +1,1487 @@
+"""Pickler class to extend the standard pickle.Pickler functionality
+
+The main objective is to make it natural to perform distributed computing on
+clusters (such as PySpark, Dask, Ray...) with interactively defined code
+(functions, classes, ...) written in notebooks or console.
+
+In particular this pickler adds the following features:
+- serialize interactively-defined or locally-defined functions, classes,
+ enums, typevars, lambdas and nested functions to compiled byte code;
+- deal with some other non-serializable objects in an ad-hoc manner where
+ applicable.
+
+This pickler is therefore meant to be used for the communication between short
+lived Python processes running the same version of Python and libraries. In
+particular, it is not meant to be used for long term storage of Python objects.
+
+It does not include an unpickler, as standard Python unpickling suffices.
+
+This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
+ `_.
+
+Copyright (c) 2012-now, CloudPickle developers and contributors.
+Copyright (c) 2012, Regents of the University of California.
+Copyright (c) 2009 `PiCloud, Inc. `_.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the University of California, Berkeley nor the
+ names of its contributors may be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""
+
+import _collections_abc
+from collections import ChainMap, OrderedDict
+import abc
+import builtins
+import copyreg
+import dataclasses
+import dis
+from enum import Enum
+import io
+import itertools
+import logging
+import opcode
+import pickle
+from pickle import _getattribute
+import platform
+import struct
+import sys
+import threading
+import types
+import typing
+import uuid
+import warnings
+import weakref
+
+# The following import is required to be imported in the cloudpickle
+# namespace to be able to load pickle files generated with older versions of
+# cloudpickle. See: tests/test_backward_compat.py
+from types import CellType # noqa: F401
+
+
+# cloudpickle is meant for inter process communication: we expect all
+# communicating processes to run the same Python version hence we favor
+# communication speed over compatibility:
+DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
+
+# Names of modules whose resources should be treated as dynamic.
+_PICKLE_BY_VALUE_MODULES = set()
+
+# Track the provenance of reconstructed dynamic classes to make it possible to
+# reconstruct instances from the matching singleton class definition when
+# appropriate and preserve the usual "isinstance" semantics of Python objects.
+_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
+_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
+_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
+
+PYPY = platform.python_implementation() == "PyPy"
+
+builtin_code_type = None
+if PYPY:
+ # builtin-code objects only exist in pypy
+ builtin_code_type = type(float.__new__.__code__)
+
+_extract_code_globals_cache = weakref.WeakKeyDictionary()
+
+
+def _get_or_create_tracker_id(class_def):
+ with _DYNAMIC_CLASS_TRACKER_LOCK:
+ class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
+ if class_tracker_id is None:
+ class_tracker_id = uuid.uuid4().hex
+ _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
+ _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
+ return class_tracker_id
+
+
+def _lookup_class_or_track(class_tracker_id, class_def):
+ if class_tracker_id is not None:
+ with _DYNAMIC_CLASS_TRACKER_LOCK:
+ class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
+ class_tracker_id, class_def
+ )
+ _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
+ return class_def
+
+
+def register_pickle_by_value(module):
+ """Register a module to make it functions and classes picklable by value.
+
+ By default, functions and classes that are attributes of an importable
+ module are to be pickled by reference, that is relying on re-importing
+ the attribute from the module at load time.
+
+ If `register_pickle_by_value(module)` is called, all its functions and
+ classes are subsequently to be pickled by value, meaning that they can
+ be loaded in Python processes where the module is not importable.
+
+ This is especially useful when developing a module in a distributed
+ execution environment: restarting the client Python process with the new
+ source code is enough: there is no need to re-install the new version
+ of the module on all the worker nodes nor to restart the workers.
+
+ Note: this feature is considered experimental. See the cloudpickle
+ README.md file for more details and limitations.
+ """
+ if not isinstance(module, types.ModuleType):
+ raise ValueError(f"Input should be a module object, got {str(module)} instead")
+ # In the future, cloudpickle may need a way to access any module registered
+ # for pickling by value in order to introspect relative imports inside
+ # functions pickled by value. (see
+ # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633).
+ # This access can be ensured by checking that module is present in
+ # sys.modules at registering time and assuming that it will still be in
+ # there when accessed during pickling. Another alternative would be to
+ # store a weakref to the module. Even though cloudpickle does not implement
+ # this introspection yet, in order to avoid a possible breaking change
+ # later, we still enforce the presence of module inside sys.modules.
+ if module.__name__ not in sys.modules:
+ raise ValueError(
+ f"{module} was not imported correctly, have you used an "
+ "`import` statement to access it?"
+ )
+ _PICKLE_BY_VALUE_MODULES.add(module.__name__)
+
+
+def unregister_pickle_by_value(module):
+ """Unregister that the input module should be pickled by value."""
+ if not isinstance(module, types.ModuleType):
+ raise ValueError(f"Input should be a module object, got {str(module)} instead")
+ if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
+ raise ValueError(f"{module} is not registered for pickle by value")
+ else:
+ _PICKLE_BY_VALUE_MODULES.remove(module.__name__)
+
+
+def list_registry_pickle_by_value():
+ return _PICKLE_BY_VALUE_MODULES.copy()
+
+
+def _is_registered_pickle_by_value(module):
+ module_name = module.__name__
+ if module_name in _PICKLE_BY_VALUE_MODULES:
+ return True
+ while True:
+ parent_name = module_name.rsplit(".", 1)[0]
+ if parent_name == module_name:
+ break
+ if parent_name in _PICKLE_BY_VALUE_MODULES:
+ return True
+ module_name = parent_name
+ return False
+
+
+def _whichmodule(obj, name):
+ """Find the module an object belongs to.
+
+ This function differs from ``pickle.whichmodule`` in two ways:
+ - it does not mangle the cases where obj's module is __main__ and obj was
+ not found in any module.
+ - Errors arising during module introspection are ignored, as those errors
+ are considered unwanted side effects.
+ """
+ module_name = getattr(obj, "__module__", None)
+
+ if module_name is not None:
+ return module_name
+ # Protect the iteration by using a copy of sys.modules against dynamic
+ # modules that trigger imports of other modules upon calls to getattr or
+ # other threads importing at the same time.
+ for module_name, module in sys.modules.copy().items():
+ # Some modules such as coverage can inject non-module objects inside
+ # sys.modules
+ if (
+ module_name == "__main__"
+ or module is None
+ or not isinstance(module, types.ModuleType)
+ ):
+ continue
+ try:
+ if _getattribute(module, name)[0] is obj:
+ return module_name
+ except Exception:
+ pass
+ return None
+
+
+def _should_pickle_by_reference(obj, name=None):
+ """Test whether an function or a class should be pickled by reference
+
+ Pickling by reference means by that the object (typically a function or a
+ class) is an attribute of a module that is assumed to be importable in the
+ target Python environment. Loading will therefore rely on importing the
+ module and then calling `getattr` on it to access the function or class.
+
+ Pickling by reference is the only option to pickle functions and classes
+ in the standard library. In cloudpickle the alternative option is to
+ pickle by value (for instance for interactively or locally defined
+ functions and classes or for attributes of modules that have been
+ explicitly registered to be pickled by value.
+ """
+ if isinstance(obj, types.FunctionType) or issubclass(type(obj), type):
+ module_and_name = _lookup_module_and_qualname(obj, name=name)
+ if module_and_name is None:
+ return False
+ module, name = module_and_name
+ return not _is_registered_pickle_by_value(module)
+
+ elif isinstance(obj, types.ModuleType):
+ # We assume that sys.modules is primarily used as a cache mechanism for
+ # the Python import machinery. Checking if a module has been added in
+ # is sys.modules therefore a cheap and simple heuristic to tell us
+ # whether we can assume that a given module could be imported by name
+ # in another Python process.
+ if _is_registered_pickle_by_value(obj):
+ return False
+ return obj.__name__ in sys.modules
+ else:
+ raise TypeError(
+ "cannot check importability of {} instances".format(type(obj).__name__)
+ )
+
+
+def _lookup_module_and_qualname(obj, name=None):
+ if name is None:
+ name = getattr(obj, "__qualname__", None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, "__name__", None)
+
+ module_name = _whichmodule(obj, name)
+
+ if module_name is None:
+ # In this case, obj.__module__ is None AND obj was not found in any
+ # imported module. obj is thus treated as dynamic.
+ return None
+
+ if module_name == "__main__":
+ return None
+
+ # Note: if module_name is in sys.modules, the corresponding module is
+ # assumed importable at unpickling time. See #357
+ module = sys.modules.get(module_name, None)
+ if module is None:
+ # The main reason why obj's module would not be imported is that this
+ # module has been dynamically created, using for example
+ # types.ModuleType. The other possibility is that module was removed
+ # from sys.modules after obj was created/imported. But this case is not
+ # supported, as the standard pickle does not support it either.
+ return None
+
+ try:
+ obj2, parent = _getattribute(module, name)
+ except AttributeError:
+ # obj was not found inside the module it points to
+ return None
+ if obj2 is not obj:
+ return None
+ return module, name
+
+
+def _extract_code_globals(co):
+ """Find all globals names read or written to by codeblock co."""
+ out_names = _extract_code_globals_cache.get(co)
+ if out_names is None:
+ # We use a dict with None values instead of a set to get a
+ # deterministic order and avoid introducing non-deterministic pickle
+ # bytes as a results.
+ out_names = {name: None for name in _walk_global_ops(co)}
+
+ # Declaring a function inside another one using the "def ..." syntax
+ # generates a constant code object corresponding to the one of the
+ # nested function's As the nested function may itself need global
+ # variables, we need to introspect its code, extract its globals, (look
+ # for code object in it's co_consts attribute..) and add the result to
+ # code_globals
+ if co.co_consts:
+ for const in co.co_consts:
+ if isinstance(const, types.CodeType):
+ out_names.update(_extract_code_globals(const))
+
+ _extract_code_globals_cache[co] = out_names
+
+ return out_names
+
+
+def _find_imported_submodules(code, top_level_dependencies):
+ """Find currently imported submodules used by a function.
+
+ Submodules used by a function need to be detected and referenced for the
+ function to work correctly at depickling time. Because submodules can be
+ referenced as attribute of their parent package (``package.submodule``), we
+ need a special introspection technique that does not rely on GLOBAL-related
+ opcodes to find references of them in a code object.
+
+ Example:
+ ```
+ import concurrent.futures
+ import cloudpickle
+ def func():
+ x = concurrent.futures.ThreadPoolExecutor
+ if __name__ == '__main__':
+ cloudpickle.dumps(func)
+ ```
+ The globals extracted by cloudpickle in the function's state include the
+ concurrent package, but not its submodule (here, concurrent.futures), which
+ is the module used by func. Find_imported_submodules will detect the usage
+ of concurrent.futures. Saving this module alongside with func will ensure
+ that calling func once depickled does not fail due to concurrent.futures
+ not being imported
+ """
+
+ subimports = []
+ # check if any known dependency is an imported package
+ for x in top_level_dependencies:
+ if (
+ isinstance(x, types.ModuleType)
+ and hasattr(x, "__package__")
+ and x.__package__
+ ):
+ # check if the package has any currently loaded sub-imports
+ prefix = x.__name__ + "."
+ # A concurrent thread could mutate sys.modules,
+ # make sure we iterate over a copy to avoid exceptions
+ for name in list(sys.modules):
+ # Older versions of pytest will add a "None" module to
+ # sys.modules.
+ if name is not None and name.startswith(prefix):
+ # check whether the function can address the sub-module
+ tokens = set(name[len(prefix) :].split("."))
+ if not tokens - set(code.co_names):
+ subimports.append(sys.modules[name])
+ return subimports
+
+
+# relevant opcodes
+STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"]
+DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"]
+LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"]
+GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL)
+HAVE_ARGUMENT = dis.HAVE_ARGUMENT
+EXTENDED_ARG = dis.EXTENDED_ARG
+
+
+_BUILTIN_TYPE_NAMES = {}
+for k, v in types.__dict__.items():
+ if type(v) is type:
+ _BUILTIN_TYPE_NAMES[v] = k
+
+
+def _builtin_type(name):
+ if name == "ClassType": # pragma: no cover
+ # Backward compat to load pickle files generated with cloudpickle
+ # < 1.3 even if loading pickle files from older versions is not
+ # officially supported.
+ return type
+ return getattr(types, name)
+
+
+def _walk_global_ops(code):
+ """Yield referenced name for global-referencing instructions in code."""
+ for instr in dis.get_instructions(code):
+ op = instr.opcode
+ if op in GLOBAL_OPS:
+ yield instr.argval
+
+
+def _extract_class_dict(cls):
+ """Retrieve a copy of the dict of a class without the inherited method."""
+ clsdict = dict(cls.__dict__) # copy dict proxy to a dict
+ if len(cls.__bases__) == 1:
+ inherited_dict = cls.__bases__[0].__dict__
+ else:
+ inherited_dict = {}
+ for base in reversed(cls.__bases__):
+ inherited_dict.update(base.__dict__)
+ to_remove = []
+ for name, value in clsdict.items():
+ try:
+ base_value = inherited_dict[name]
+ if value is base_value:
+ to_remove.append(name)
+ except KeyError:
+ pass
+ for name in to_remove:
+ clsdict.pop(name)
+ return clsdict
+
+
+def is_tornado_coroutine(func):
+ """Return whether `func` is a Tornado coroutine function.
+
+ Running coroutines are not supported.
+ """
+ warnings.warn(
+ "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be "
+ "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function "
+ "directly instead.",
+ category=DeprecationWarning,
+ )
+ if "tornado.gen" not in sys.modules:
+ return False
+ gen = sys.modules["tornado.gen"]
+ if not hasattr(gen, "is_coroutine_function"):
+ # Tornado version is too old
+ return False
+ return gen.is_coroutine_function(func)
+
+
+def subimport(name):
+ # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is
+ # the name of a submodule, __import__ will return the top-level root module
+ # of this submodule. For instance, __import__('os.path') returns the `os`
+ # module.
+ __import__(name)
+ return sys.modules[name]
+
+
+def dynamic_subimport(name, vars):
+ mod = types.ModuleType(name)
+ mod.__dict__.update(vars)
+ mod.__dict__["__builtins__"] = builtins.__dict__
+ return mod
+
+
+def _get_cell_contents(cell):
+ try:
+ return cell.cell_contents
+ except ValueError:
+ # Handle empty cells explicitly with a sentinel value.
+ return _empty_cell_value
+
+
+def instance(cls):
+ """Create a new instance of a class.
+
+ Parameters
+ ----------
+ cls : type
+ The class to create an instance of.
+
+ Returns
+ -------
+ instance : cls
+ A new instance of ``cls``.
+ """
+ return cls()
+
+
+@instance
+class _empty_cell_value:
+ """Sentinel for empty closures."""
+
+ @classmethod
+ def __reduce__(cls):
+ return cls.__name__
+
+
+def _make_function(code, globals, name, argdefs, closure):
+ # Setting __builtins__ in globals is needed for nogil CPython.
+ globals["__builtins__"] = __builtins__
+ return types.FunctionType(code, globals, name, argdefs, closure)
+
+
+def _make_empty_cell():
+ if False:
+ # trick the compiler into creating an empty cell in our lambda
+ cell = None
+ raise AssertionError("this route should not be executed")
+
+ return (lambda: cell).__closure__[0]
+
+
+def _make_cell(value=_empty_cell_value):
+ cell = _make_empty_cell()
+ if value is not _empty_cell_value:
+ cell.cell_contents = value
+ return cell
+
+
+def _make_skeleton_class(
+ type_constructor, name, bases, type_kwargs, class_tracker_id, extra
+):
+ """Build dynamic class with an empty __dict__ to be filled once memoized
+
+ If class_tracker_id is not None, try to lookup an existing class definition
+ matching that id. If none is found, track a newly reconstructed class
+ definition under that id so that other instances stemming from the same
+ class id will also reuse this class definition.
+
+ The "extra" variable is meant to be a dict (or None) that can be used for
+ forward compatibility shall the need arise.
+ """
+ skeleton_class = types.new_class(
+ name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs)
+ )
+ return _lookup_class_or_track(class_tracker_id, skeleton_class)
+
+
+def _make_skeleton_enum(
+ bases, name, qualname, members, module, class_tracker_id, extra
+):
+ """Build dynamic enum with an empty __dict__ to be filled once memoized
+
+ The creation of the enum class is inspired by the code of
+ EnumMeta._create_.
+
+ If class_tracker_id is not None, try to lookup an existing enum definition
+ matching that id. If none is found, track a newly reconstructed enum
+ definition under that id so that other instances stemming from the same
+ class id will also reuse this enum definition.
+
+ The "extra" variable is meant to be a dict (or None) that can be used for
+ forward compatibility shall the need arise.
+ """
+ # enums always inherit from their base Enum class at the last position in
+ # the list of base classes:
+ enum_base = bases[-1]
+ metacls = enum_base.__class__
+ classdict = metacls.__prepare__(name, bases)
+
+ for member_name, member_value in members.items():
+ classdict[member_name] = member_value
+ enum_class = metacls.__new__(metacls, name, bases, classdict)
+ enum_class.__module__ = module
+ enum_class.__qualname__ = qualname
+
+ return _lookup_class_or_track(class_tracker_id, enum_class)
+
+
+def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id):
+ tv = typing.TypeVar(
+ name,
+ *constraints,
+ bound=bound,
+ covariant=covariant,
+ contravariant=contravariant,
+ )
+ return _lookup_class_or_track(class_tracker_id, tv)
+
+
+def _decompose_typevar(obj):
+ return (
+ obj.__name__,
+ obj.__bound__,
+ obj.__constraints__,
+ obj.__covariant__,
+ obj.__contravariant__,
+ _get_or_create_tracker_id(obj),
+ )
+
+
+def _typevar_reduce(obj):
+ # TypeVar instances require the module information hence why we
+ # are not using the _should_pickle_by_reference directly
+ module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
+
+ if module_and_name is None:
+ return (_make_typevar, _decompose_typevar(obj))
+ elif _is_registered_pickle_by_value(module_and_name[0]):
+ return (_make_typevar, _decompose_typevar(obj))
+
+ return (getattr, module_and_name)
+
+
+def _get_bases(typ):
+ if "__orig_bases__" in getattr(typ, "__dict__", {}):
+ # For generic types (see PEP 560)
+ # Note that simply checking `hasattr(typ, '__orig_bases__')` is not
+ # correct. Subclasses of a fully-parameterized generic class does not
+ # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
+ # will return True because it's defined in the base class.
+ bases_attr = "__orig_bases__"
+ else:
+ # For regular class objects
+ bases_attr = "__bases__"
+ return getattr(typ, bases_attr)
+
+
+def _make_dict_keys(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict.fromkeys(obj).keys()
+ else:
+ return dict.fromkeys(obj).keys()
+
+
+def _make_dict_values(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
+ else:
+ return {i: _ for i, _ in enumerate(obj)}.values()
+
+
+def _make_dict_items(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict(obj).items()
+ else:
+ return obj.items()
+
+
+# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
+# -------------------------------------------------
+
+
+def _class_getnewargs(obj):
+ type_kwargs = {}
+ if "__module__" in obj.__dict__:
+ type_kwargs["__module__"] = obj.__module__
+
+ __dict__ = obj.__dict__.get("__dict__", None)
+ if isinstance(__dict__, property):
+ type_kwargs["__dict__"] = __dict__
+
+ return (
+ type(obj),
+ obj.__name__,
+ _get_bases(obj),
+ type_kwargs,
+ _get_or_create_tracker_id(obj),
+ None,
+ )
+
+
+def _enum_getnewargs(obj):
+ members = {e.name: e.value for e in obj}
+ return (
+ obj.__bases__,
+ obj.__name__,
+ obj.__qualname__,
+ members,
+ obj.__module__,
+ _get_or_create_tracker_id(obj),
+ None,
+ )
+
+
+# COLLECTION OF OBJECTS RECONSTRUCTORS
+# ------------------------------------
+def _file_reconstructor(retval):
+ return retval
+
+
+# COLLECTION OF OBJECTS STATE GETTERS
+# -----------------------------------
+
+
+def _function_getstate(func):
+ # - Put func's dynamic attributes (stored in func.__dict__) in state. These
+ # attributes will be restored at unpickling time using
+ # f.__dict__.update(state)
+ # - Put func's members into slotstate. Such attributes will be restored at
+ # unpickling time by iterating over slotstate and calling setattr(func,
+ # slotname, slotvalue)
+ slotstate = {
+ "__name__": func.__name__,
+ "__qualname__": func.__qualname__,
+ "__annotations__": func.__annotations__,
+ "__kwdefaults__": func.__kwdefaults__,
+ "__defaults__": func.__defaults__,
+ "__module__": func.__module__,
+ "__doc__": func.__doc__,
+ "__closure__": func.__closure__,
+ }
+
+ f_globals_ref = _extract_code_globals(func.__code__)
+ f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__}
+
+ if func.__closure__ is not None:
+ closure_values = list(map(_get_cell_contents, func.__closure__))
+ else:
+ closure_values = ()
+
+ # Extract currently-imported submodules used by func. Storing these modules
+ # in a smoke _cloudpickle_subimports attribute of the object's state will
+ # trigger the side effect of importing these modules at unpickling time
+ # (which is necessary for func to work correctly once depickled)
+ slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
+ func.__code__, itertools.chain(f_globals.values(), closure_values)
+ )
+ slotstate["__globals__"] = f_globals
+
+ state = func.__dict__
+ return state, slotstate
+
+
+def _class_getstate(obj):
+ clsdict = _extract_class_dict(obj)
+ clsdict.pop("__weakref__", None)
+
+ if issubclass(type(obj), abc.ABCMeta):
+ # If obj is an instance of an ABCMeta subclass, don't pickle the
+ # cache/negative caches populated during isinstance/issubclass
+ # checks, but pickle the list of registered subclasses of obj.
+ clsdict.pop("_abc_cache", None)
+ clsdict.pop("_abc_negative_cache", None)
+ clsdict.pop("_abc_negative_cache_version", None)
+ registry = clsdict.pop("_abc_registry", None)
+ if registry is None:
+ # The abc caches and registered subclasses of a
+ # class are bundled into the single _abc_impl attribute
+ clsdict.pop("_abc_impl", None)
+ (registry, _, _, _) = abc._get_dump(obj)
+
+ clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry]
+ else:
+ # In the above if clause, registry is a set of weakrefs -- in
+ # this case, registry is a WeakSet
+ clsdict["_abc_impl"] = [type_ for type_ in registry]
+
+ if "__slots__" in clsdict:
+ # pickle string length optimization: member descriptors of obj are
+ # created automatically from obj's __slots__ attribute, no need to
+ # save them in obj's state
+ if isinstance(obj.__slots__, str):
+ clsdict.pop(obj.__slots__)
+ else:
+ for k in obj.__slots__:
+ clsdict.pop(k, None)
+
+ clsdict.pop("__dict__", None) # unpicklable property object
+
+ return (clsdict, {})
+
+
+def _enum_getstate(obj):
+ clsdict, slotstate = _class_getstate(obj)
+
+ members = {e.name: e.value for e in obj}
+ # Cleanup the clsdict that will be passed to _make_skeleton_enum:
+ # Those attributes are already handled by the metaclass.
+ for attrname in [
+ "_generate_next_value_",
+ "_member_names_",
+ "_member_map_",
+ "_member_type_",
+ "_value2member_map_",
+ ]:
+ clsdict.pop(attrname, None)
+ for member in members:
+ clsdict.pop(member)
+ # Special handling of Enum subclasses
+ return clsdict, slotstate
+
+
+# COLLECTIONS OF OBJECTS REDUCERS
+# -------------------------------
+# A reducer is a function taking a single argument (obj), and that returns a
+# tuple with all the necessary data to re-construct obj. Apart from a few
+# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
+# correctly pickle an object.
+# While many built-in objects (Exceptions objects, instances of the "object"
+# class, etc), are shipped with their own built-in reducer (invoked using
+# obj.__reduce__), some do not. The following methods were created to "fill
+# these holes".
+
+
+def _code_reduce(obj):
+ """code object reducer."""
+ # If you are not sure about the order of arguments, take a look at help
+ # of the specific type from types, for example:
+ # >>> from types import CodeType
+ # >>> help(CodeType)
+ if hasattr(obj, "co_exceptiontable"):
+ # Python 3.11 and later: there are some new attributes
+ # related to the enhanced exceptions.
+ args = (
+ obj.co_argcount,
+ obj.co_posonlyargcount,
+ obj.co_kwonlyargcount,
+ obj.co_nlocals,
+ obj.co_stacksize,
+ obj.co_flags,
+ obj.co_code,
+ obj.co_consts,
+ obj.co_names,
+ obj.co_varnames,
+ obj.co_filename,
+ obj.co_name,
+ obj.co_qualname,
+ obj.co_firstlineno,
+ obj.co_linetable,
+ obj.co_exceptiontable,
+ obj.co_freevars,
+ obj.co_cellvars,
+ )
+ elif hasattr(obj, "co_linetable"):
+ # Python 3.10 and later: obj.co_lnotab is deprecated and constructor
+ # expects obj.co_linetable instead.
+ args = (
+ obj.co_argcount,
+ obj.co_posonlyargcount,
+ obj.co_kwonlyargcount,
+ obj.co_nlocals,
+ obj.co_stacksize,
+ obj.co_flags,
+ obj.co_code,
+ obj.co_consts,
+ obj.co_names,
+ obj.co_varnames,
+ obj.co_filename,
+ obj.co_name,
+ obj.co_firstlineno,
+ obj.co_linetable,
+ obj.co_freevars,
+ obj.co_cellvars,
+ )
+ elif hasattr(obj, "co_nmeta"): # pragma: no cover
+ # "nogil" Python: modified attributes from 3.9
+ args = (
+ obj.co_argcount,
+ obj.co_posonlyargcount,
+ obj.co_kwonlyargcount,
+ obj.co_nlocals,
+ obj.co_framesize,
+ obj.co_ndefaultargs,
+ obj.co_nmeta,
+ obj.co_flags,
+ obj.co_code,
+ obj.co_consts,
+ obj.co_varnames,
+ obj.co_filename,
+ obj.co_name,
+ obj.co_firstlineno,
+ obj.co_lnotab,
+ obj.co_exc_handlers,
+ obj.co_jump_table,
+ obj.co_freevars,
+ obj.co_cellvars,
+ obj.co_free2reg,
+ obj.co_cell2reg,
+ )
+ else:
+ # Backward compat for 3.8 and 3.9
+ args = (
+ obj.co_argcount,
+ obj.co_posonlyargcount,
+ obj.co_kwonlyargcount,
+ obj.co_nlocals,
+ obj.co_stacksize,
+ obj.co_flags,
+ obj.co_code,
+ obj.co_consts,
+ obj.co_names,
+ obj.co_varnames,
+ obj.co_filename,
+ obj.co_name,
+ obj.co_firstlineno,
+ obj.co_lnotab,
+ obj.co_freevars,
+ obj.co_cellvars,
+ )
+ return types.CodeType, args
+
+
+def _cell_reduce(obj):
+ """Cell (containing values of a function's free variables) reducer."""
+ try:
+ obj.cell_contents
+ except ValueError: # cell is empty
+ return _make_empty_cell, ()
+ else:
+ return _make_cell, (obj.cell_contents,)
+
+
+def _classmethod_reduce(obj):
+ orig_func = obj.__func__
+ return type(obj), (orig_func,)
+
+
+def _file_reduce(obj):
+ """Save a file."""
+ import io
+
+ if not hasattr(obj, "name") or not hasattr(obj, "mode"):
+ raise pickle.PicklingError(
+ "Cannot pickle files that do not map to an actual file"
+ )
+ if obj is sys.stdout:
+ return getattr, (sys, "stdout")
+ if obj is sys.stderr:
+ return getattr, (sys, "stderr")
+ if obj is sys.stdin:
+ raise pickle.PicklingError("Cannot pickle standard input")
+ if obj.closed:
+ raise pickle.PicklingError("Cannot pickle closed files")
+ if hasattr(obj, "isatty") and obj.isatty():
+ raise pickle.PicklingError("Cannot pickle files that map to tty objects")
+ if "r" not in obj.mode and "+" not in obj.mode:
+ raise pickle.PicklingError(
+ "Cannot pickle files that are not opened for reading: %s" % obj.mode
+ )
+
+ name = obj.name
+
+ retval = io.StringIO()
+
+ try:
+ # Read the whole file
+ curloc = obj.tell()
+ obj.seek(0)
+ contents = obj.read()
+ obj.seek(curloc)
+ except OSError as e:
+ raise pickle.PicklingError(
+ "Cannot pickle file %s as it cannot be read" % name
+ ) from e
+ retval.write(contents)
+ retval.seek(curloc)
+
+ retval.name = name
+ return _file_reconstructor, (retval,)
+
+
+def _getset_descriptor_reduce(obj):
+ return getattr, (obj.__objclass__, obj.__name__)
+
+
+def _mappingproxy_reduce(obj):
+ return types.MappingProxyType, (dict(obj),)
+
+
+def _memoryview_reduce(obj):
+ return bytes, (obj.tobytes(),)
+
+
+def _module_reduce(obj):
+ if _should_pickle_by_reference(obj):
+ return subimport, (obj.__name__,)
+ else:
+ # Some external libraries can populate the "__builtins__" entry of a
+ # module's `__dict__` with unpicklable objects (see #316). For that
+ # reason, we do not attempt to pickle the "__builtins__" entry, and
+ # restore a default value for it at unpickling time.
+ state = obj.__dict__.copy()
+ state.pop("__builtins__", None)
+ return dynamic_subimport, (obj.__name__, state)
+
+
+def _method_reduce(obj):
+ return (types.MethodType, (obj.__func__, obj.__self__))
+
+
+def _logger_reduce(obj):
+ return logging.getLogger, (obj.name,)
+
+
+def _root_logger_reduce(obj):
+ return logging.getLogger, ()
+
+
+def _property_reduce(obj):
+ return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
+
+
+def _weakset_reduce(obj):
+ return weakref.WeakSet, (list(obj),)
+
+
+def _dynamic_class_reduce(obj):
+ """Save a class that can't be referenced as a module attribute.
+
+ This method is used to serialize classes that are defined inside
+ functions, or that otherwise can't be serialized as attribute lookups
+ from importable modules.
+ """
+ if Enum is not None and issubclass(obj, Enum):
+ return (
+ _make_skeleton_enum,
+ _enum_getnewargs(obj),
+ _enum_getstate(obj),
+ None,
+ None,
+ _class_setstate,
+ )
+ else:
+ return (
+ _make_skeleton_class,
+ _class_getnewargs(obj),
+ _class_getstate(obj),
+ None,
+ None,
+ _class_setstate,
+ )
+
+
+def _class_reduce(obj):
+ """Select the reducer depending on the dynamic nature of the class obj."""
+ if obj is type(None): # noqa
+ return type, (None,)
+ elif obj is type(Ellipsis):
+ return type, (Ellipsis,)
+ elif obj is type(NotImplemented):
+ return type, (NotImplemented,)
+ elif obj in _BUILTIN_TYPE_NAMES:
+ return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
+ elif not _should_pickle_by_reference(obj):
+ return _dynamic_class_reduce(obj)
+ return NotImplemented
+
+
+def _dict_keys_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_keys, (list(obj),)
+
+
+def _dict_values_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_values, (list(obj),)
+
+
+def _dict_items_reduce(obj):
+ return _make_dict_items, (dict(obj),)
+
+
+def _odict_keys_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_keys, (list(obj), True)
+
+
+def _odict_values_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_values, (list(obj), True)
+
+
+def _odict_items_reduce(obj):
+ return _make_dict_items, (dict(obj), True)
+
+
+def _dataclass_field_base_reduce(obj):
+ return _get_dataclass_field_type_sentinel, (obj.name,)
+
+
+# COLLECTIONS OF OBJECTS STATE SETTERS
+# ------------------------------------
+# state setters are called at unpickling time, once the object is created and
+# it has to be updated to how it was at unpickling time.
+
+
+def _function_setstate(obj, state):
+ """Update the state of a dynamic function.
+
+ As __closure__ and __globals__ are readonly attributes of a function, we
+ cannot rely on the native setstate routine of pickle.load_build, that calls
+ setattr on items of the slotstate. Instead, we have to modify them inplace.
+ """
+ state, slotstate = state
+ obj.__dict__.update(state)
+
+ obj_globals = slotstate.pop("__globals__")
+ obj_closure = slotstate.pop("__closure__")
+ # _cloudpickle_subimports is a set of submodules that must be loaded for
+ # the pickled function to work correctly at unpickling time. Now that these
+ # submodules are depickled (hence imported), they can be removed from the
+ # object's state (the object state only served as a reference holder to
+ # these submodules)
+ slotstate.pop("_cloudpickle_submodules")
+
+ obj.__globals__.update(obj_globals)
+ obj.__globals__["__builtins__"] = __builtins__
+
+ if obj_closure is not None:
+ for i, cell in enumerate(obj_closure):
+ try:
+ value = cell.cell_contents
+ except ValueError: # cell is empty
+ continue
+ obj.__closure__[i].cell_contents = value
+
+ for k, v in slotstate.items():
+ setattr(obj, k, v)
+
+
+def _class_setstate(obj, state):
+ state, slotstate = state
+ registry = None
+ for attrname, attr in state.items():
+ if attrname == "_abc_impl":
+ registry = attr
+ else:
+ setattr(obj, attrname, attr)
+ if registry is not None:
+ for subclass in registry:
+ obj.register(subclass)
+
+ return obj
+
+
+# COLLECTION OF DATACLASS UTILITIES
+# ---------------------------------
+# There are some internal sentinel values whose identity must be preserved when
+# unpickling dataclass fields. Each sentinel value has a unique name that we can
+# use to retrieve its identity at unpickling time.
+
+
+_DATACLASSE_FIELD_TYPE_SENTINELS = {
+ dataclasses._FIELD.name: dataclasses._FIELD,
+ dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR,
+ dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR,
+}
+
+
+def _get_dataclass_field_type_sentinel(name):
+ return _DATACLASSE_FIELD_TYPE_SENTINELS[name]
+
+
+class Pickler(pickle.Pickler):
+ # set of reducers defined and used by cloudpickle (private)
+ _dispatch_table = {}
+ _dispatch_table[classmethod] = _classmethod_reduce
+ _dispatch_table[io.TextIOWrapper] = _file_reduce
+ _dispatch_table[logging.Logger] = _logger_reduce
+ _dispatch_table[logging.RootLogger] = _root_logger_reduce
+ _dispatch_table[memoryview] = _memoryview_reduce
+ _dispatch_table[property] = _property_reduce
+ _dispatch_table[staticmethod] = _classmethod_reduce
+ _dispatch_table[CellType] = _cell_reduce
+ _dispatch_table[types.CodeType] = _code_reduce
+ _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce
+ _dispatch_table[types.ModuleType] = _module_reduce
+ _dispatch_table[types.MethodType] = _method_reduce
+ _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce
+ _dispatch_table[weakref.WeakSet] = _weakset_reduce
+ _dispatch_table[typing.TypeVar] = _typevar_reduce
+ _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce
+ _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce
+ _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce
+ _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce
+ _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce
+ _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce
+ _dispatch_table[abc.abstractmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractproperty] = _property_reduce
+ _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce
+
+ dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table)
+
+ # function reducers are defined as instance methods of cloudpickle.Pickler
+ # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref)
+ def _dynamic_function_reduce(self, func):
+ """Reduce a function that is not pickleable via attribute lookup."""
+ newargs = self._function_getnewargs(func)
+ state = _function_getstate(func)
+ return (_make_function, newargs, state, None, None, _function_setstate)
+
+ def _function_reduce(self, obj):
+ """Reducer for function objects.
+
+ If obj is a top-level attribute of a file-backed module, this reducer
+ returns NotImplemented, making the cloudpickle.Pickler fall back to
+ traditional pickle.Pickler routines to save obj. Otherwise, it reduces
+ obj using a custom cloudpickle reducer designed specifically to handle
+ dynamic functions.
+ """
+ if _should_pickle_by_reference(obj):
+ return NotImplemented
+ else:
+ return self._dynamic_function_reduce(obj)
+
+ def _function_getnewargs(self, func):
+ code = func.__code__
+
+ # base_globals represents the future global namespace of func at
+ # unpickling time. Looking it up and storing it in
+ # cloudpickle.Pickler.globals_ref allow functions sharing the same
+ # globals at pickling time to also share them once unpickled, at one
+ # condition: since globals_ref is an attribute of a cloudpickle.Pickler
+ # instance, and that a new cloudpickle.Pickler is created each time
+ # cloudpickle.dump or cloudpickle.dumps is called, functions also need
+ # to be saved within the same invocation of
+ # cloudpickle.dump/cloudpickle.dumps (for example:
+ # cloudpickle.dumps([f1, f2])). There is no such limitation when using
+ # cloudpickle.Pickler.dump, as long as the multiple invocations are
+ # bound to the same cloudpickle.Pickler instance.
+ base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
+
+ if base_globals == {}:
+ # Add module attributes used to resolve relative imports
+ # instructions inside func.
+ for k in ["__package__", "__name__", "__path__", "__file__"]:
+ if k in func.__globals__:
+ base_globals[k] = func.__globals__[k]
+
+ # Do not bind the free variables before the function is created to
+ # avoid infinite recursion.
+ if func.__closure__ is None:
+ closure = None
+ else:
+ closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars)))
+
+ return code, base_globals, None, None, closure
+
+ def dump(self, obj):
+ try:
+ return super().dump(obj)
+ except RuntimeError as e:
+ if len(e.args) > 0 and "recursion" in e.args[0]:
+ msg = "Could not pickle object as excessively deep recursion required."
+ raise pickle.PicklingError(msg) from e
+ else:
+ raise
+
+ def __init__(self, file, protocol=None, buffer_callback=None):
+ if protocol is None:
+ protocol = DEFAULT_PROTOCOL
+ super().__init__(file, protocol=protocol, buffer_callback=buffer_callback)
+ # map functions __globals__ attribute ids, to ensure that functions
+ # sharing the same global namespace at pickling time also share
+ # their global namespace at unpickling time.
+ self.globals_ref = {}
+ self.proto = int(protocol)
+
+ if not PYPY:
+ # pickle.Pickler is the C implementation of the CPython pickler and
+ # therefore we rely on reduce_override method to customize the pickler
+ # behavior.
+
+ # `cloudpickle.Pickler.dispatch` is only left for backward
+ # compatibility - note that when using protocol 5,
+ # `cloudpickle.Pickler.dispatch` is not an extension of
+ # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler`
+ # subclasses the C-implemented `pickle.Pickler`, which does not expose
+ # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler`
+ # used `cloudpickle.Pickler.dispatch` as a class-level attribute
+ # storing all reducers implemented by cloudpickle, but the attribute
+ # name was not a great choice given because it would collide with a
+ # similarly named attribute in the pure-Python `pickle._Pickler`
+ # implementation in the standard library.
+ dispatch = dispatch_table
+
+ # Implementation of the reducer_override callback, in order to
+ # efficiently serialize dynamic functions and classes by subclassing
+ # the C-implemented `pickle.Pickler`.
+ # TODO: decorrelate reducer_override (which is tied to CPython's
+ # implementation - would it make sense to backport it to pypy? - and
+ # pickle's protocol 5 which is implementation agnostic. Currently, the
+ # availability of both notions coincide on CPython's pickle, but it may
+ # not be the case anymore when pypy implements protocol 5.
+
+ def reducer_override(self, obj):
+ """Type-agnostic reducing callback for function and classes.
+
+ For performance reasons, subclasses of the C `pickle.Pickler` class
+ cannot register custom reducers for functions and classes in the
+ dispatch_table attribute. Reducers for such types must instead
+ implemented via the special `reducer_override` method.
+
+ Note that this method will be called for any object except a few
+ builtin-types (int, lists, dicts etc.), which differs from reducers
+ in the Pickler's dispatch_table, each of them being invoked for
+ objects of a specific type only.
+
+ This property comes in handy for classes: although most classes are
+ instances of the ``type`` metaclass, some of them can be instances
+ of other custom metaclasses (such as enum.EnumMeta for example). In
+ particular, the metaclass will likely not be known in advance, and
+ thus cannot be special-cased using an entry in the dispatch_table.
+ reducer_override, among other things, allows us to register a
+ reducer that will be called for any class, independently of its
+ type.
+
+ Notes:
+
+ * reducer_override has the priority over dispatch_table-registered
+ reducers.
+ * reducer_override can be used to fix other limitations of
+ cloudpickle for other types that suffered from type-specific
+ reducers, such as Exceptions. See
+ https://github.com/cloudpipe/cloudpickle/issues/248
+ """
+ t = type(obj)
+ try:
+ is_anyclass = issubclass(t, type)
+ except TypeError: # t is not a class (old Boost; see SF #502085)
+ is_anyclass = False
+
+ if is_anyclass:
+ return _class_reduce(obj)
+ elif isinstance(obj, types.FunctionType):
+ return self._function_reduce(obj)
+ else:
+ # fallback to save_global, including the Pickler's
+ # dispatch_table
+ return NotImplemented
+
+ else:
+ # When reducer_override is not available, hack the pure-Python
+ # Pickler's types.FunctionType and type savers. Note: the type saver
+ # must override Pickler.save_global, because pickle.py contains a
+ # hard-coded call to save_global when pickling meta-classes.
+ dispatch = pickle.Pickler.dispatch.copy()
+
+ def _save_reduce_pickle5(
+ self,
+ func,
+ args,
+ state=None,
+ listitems=None,
+ dictitems=None,
+ state_setter=None,
+ obj=None,
+ ):
+ save = self.save
+ write = self.write
+ self.save_reduce(
+ func,
+ args,
+ state=None,
+ listitems=listitems,
+ dictitems=dictitems,
+ obj=obj,
+ )
+ # backport of the Python 3.8 state_setter pickle operations
+ save(state_setter)
+ save(obj) # simple BINGET opcode as obj is already memoized.
+ save(state)
+ write(pickle.TUPLE2)
+ # Trigger a state_setter(obj, state) function call.
+ write(pickle.REDUCE)
+ # The purpose of state_setter is to carry-out an
+ # inplace modification of obj. We do not care about what the
+ # method might return, so its output is eventually removed from
+ # the stack.
+ write(pickle.POP)
+
+ def save_global(self, obj, name=None, pack=struct.pack):
+ """Main dispatch method.
+
+ The name of this method is somewhat misleading: all types get
+ dispatched here.
+ """
+ if obj is type(None): # noqa
+ return self.save_reduce(type, (None,), obj=obj)
+ elif obj is type(Ellipsis):
+ return self.save_reduce(type, (Ellipsis,), obj=obj)
+ elif obj is type(NotImplemented):
+ return self.save_reduce(type, (NotImplemented,), obj=obj)
+ elif obj in _BUILTIN_TYPE_NAMES:
+ return self.save_reduce(
+ _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj
+ )
+
+ if name is not None:
+ super().save_global(obj, name=name)
+ elif not _should_pickle_by_reference(obj, name=name):
+ self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj)
+ else:
+ super().save_global(obj, name=name)
+
+ dispatch[type] = save_global
+
+ def save_function(self, obj, name=None):
+ """Registered with the dispatch to handle all function types.
+
+ Determines what kind of function obj is (e.g. lambda, defined at
+ interactive prompt, etc) and handles the pickling appropriately.
+ """
+ if _should_pickle_by_reference(obj, name=name):
+ return super().save_global(obj, name=name)
+ elif PYPY and isinstance(obj.__code__, builtin_code_type):
+ return self.save_pypy_builtin_func(obj)
+ else:
+ return self._save_reduce_pickle5(
+ *self._dynamic_function_reduce(obj), obj=obj
+ )
+
+ def save_pypy_builtin_func(self, obj):
+ """Save pypy equivalent of builtin functions.
+
+ PyPy does not have the concept of builtin-functions. Instead,
+ builtin-functions are simple function instances, but with a
+ builtin-code attribute.
+ Most of the time, builtin functions should be pickled by attribute.
+ But PyPy has flaky support for __qualname__, so some builtin
+ functions such as float.__new__ will be classified as dynamic. For
+ this reason only, we created this special routine. Because
+ builtin-functions are not expected to have closure or globals,
+ there is no additional hack (compared the one already implemented
+ in pickle) to protect ourselves from reference cycles. A simple
+ (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note
+ also that PyPy improved their support for __qualname__ in v3.6, so
+ this routing should be removed when cloudpickle supports only PyPy
+ 3.6 and later.
+ """
+ rv = (
+ types.FunctionType,
+ (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__),
+ obj.__dict__,
+ )
+ self.save_reduce(*rv, obj=obj)
+
+ dispatch[types.FunctionType] = save_function
+
+
+# Shorthands similar to pickle.dump/pickle.dumps
+
+
+def dump(obj, file, protocol=None, buffer_callback=None):
+ """Serialize obj as bytes streamed into file
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python (although this is not always
+ guaranteed to work because cloudpickle relies on some internal
+ implementation details that can change from one Python version to the
+ next).
+ """
+ Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj)
+
+
+def dumps(obj, protocol=None, buffer_callback=None):
+ """Serialize obj as a string of bytes allocated in memory
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python (although this is not always
+ guaranteed to work because cloudpickle relies on some internal
+ implementation details that can change from one Python version to the
+ next).
+ """
+ with io.BytesIO() as file:
+ cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback)
+ cp.dump(obj)
+ return file.getvalue()
+
+
+# Include pickles unloading functions in this namespace for convenience.
+load, loads = pickle.load, pickle.loads
+
+# Backward compat alias.
+CloudPickler = Pickler
diff --git a/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py b/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..52d6732e44ebcc0053b24969943f7c3b742268bb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cloudpickle/cloudpickle_fast.py
@@ -0,0 +1,13 @@
+"""Compatibility module.
+
+It can be necessary to load files generated by previous versions of cloudpickle
+that rely on symbols being defined under the `cloudpickle.cloudpickle_fast`
+namespace.
+
+See: tests/test_backward_compat.py
+"""
+from . import cloudpickle
+
+
+def __getattr__(name):
+ return getattr(cloudpickle, name)
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/METADATA b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..bced4ff4560cae375d2b699cd0aee6a6a17c27ee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/METADATA
@@ -0,0 +1,134 @@
+Metadata-Version: 2.4
+Name: cpplint
+Version: 2.0.2
+Summary: Check C++ files configurably against Google's style guide
+Author: Google Inc., Thibault Kruse, cpplint developers
+Author-email: Andrew Davis
+Maintainer-email: Aaron Liu , Christian Clauss , John Vandenberg
+License: BSD-3-Clause
+Project-URL: Homepage, https://github.com/cpplint/cpplint
+Keywords: c++,cpp,google style,lint
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: End Users/Desktop
+Classifier: License :: Freely Distributable
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Natural Language :: English
+Classifier: Programming Language :: C++
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Topic :: Software Development :: Quality Assurance
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: dev
+Requires-Dist: mypy; extra == "dev"
+Requires-Dist: pylint>=3.3.4; extra == "dev"
+Requires-Dist: pytest; extra == "dev"
+Requires-Dist: pytest-cov; extra == "dev"
+Requires-Dist: pytest-timeout; extra == "dev"
+Requires-Dist: testfixtures; extra == "dev"
+Requires-Dist: tox<5; extra == "dev"
+Dynamic: license-file
+
+#####################################
+cpplint - static code checker for C++
+#####################################
+
+.. image:: https://img.shields.io/pypi/v/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/pyversions/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/status/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/l/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/dd/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/dw/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+.. image:: https://img.shields.io/pypi/dm/cpplint.svg
+ :target: https://pypi.python.org/pypi/cpplint
+
+Cpplint is a command-line tool to check C/C++ files for style issues according to `Google's C++ style guide `_.
+
+Cpplint used to be developed and maintained by Google Inc. at `google/styleguide `_. Nowadays, `Google is no longer maintaining the public version of cpplint `_, and pretty much everything in their repo's PRs and issues about cpplint have gone unimplemented.
+
+This fork aims to update cpplint to modern specifications, and be (somewhat) more open to adding fixes and features to make cpplint usable in wider contexts.
+
+
+Installation
+============
+
+Use [`pipx`](https://pipx.pypa.io) to install cpplint from PyPI, run:
+
+.. code-block:: bash
+
+ $ pipx install cpplint
+
+Usage
+-----
+.. code-block:: bash
+
+ $ cpplint [OPTIONS] files
+
+For full usage instructions, run:
+
+.. code-block:: bash
+
+ $ cpplint --help
+
+cpplint can also be run as a pre-commit hook by adding to `.pre-commit-config.yaml`:
+
+.. code-block:: yaml
+
+ - repo: https://github.com/cpplint/cpplint
+ rev: 2.0.0
+ hooks:
+ - id: cpplint
+ args:
+ - --filter=-whitespace/line_length,-whitespace/parens
+
+Changes
+=======
+
+* python 3 compatibility
+* more default file extensions
+* customizable file extensions with the --extensions argument
+* continuous integration on github
+* support for recursive file discovery via the --recursive argument
+* support for excluding files via --exclude
+* JUnit XML output format
+* Overriding repository root auto-detection via --repository
+* Support ``#pragma once`` as an alternative to header include guards
+* ... and `quite a bit `_ more
+
+Acknowledgements
+================
+
+Thanks to Google Inc. for open-sourcing their in-house tool.
+
+Thanks to `our contributors `_.
+
+Maintainers
+-----------
+
+* `@aaronliu0130 `_
+* `@jayvdb `_
+
+Former
+^^^^^^
+
+* `@tkruse `_
+* `@mattyclarkson `_
+* `@theandrewdavis `_
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/RECORD b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..04ad365d8b954976c7dabfd9e13e75289ae6cf46
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/RECORD
@@ -0,0 +1,10 @@
+../../../bin/cpplint,sha256=aZyJ2_4Fz9LkvV2l_dGnbi0X4AdVvvI0TcA34JsGgXU,276
+__pycache__/cpplint.cpython-310.pyc,,
+cpplint-2.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+cpplint-2.0.2.dist-info/METADATA,sha256=e2pXQKDZVf9NoNYj_Ss6HGKEAPuRv7WCwvGIi7xQ4u4,4699
+cpplint-2.0.2.dist-info/RECORD,,
+cpplint-2.0.2.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
+cpplint-2.0.2.dist-info/entry_points.txt,sha256=WTpnXGuiAx1LIMn9hX-zhXrIWjbb7gd8HgfSclZOzuo,41
+cpplint-2.0.2.dist-info/licenses/LICENSE,sha256=Av1lW5rbeedx_WAmenIvCGLUM4H5W7OL1q2l4ggCcsQ,1502
+cpplint-2.0.2.dist-info/top_level.txt,sha256=nhyCGV6AXa7TDfpFgUmZDnmliwJGHCWtsNMr-M0cEc0,8
+cpplint.py,sha256=85IOR9ieunOfhmQFdFzmuI2xOVuNrPg9iAuslQQ_qNU,299442
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/WHEEL b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (78.1.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e7964af4d6def21cd62d3376ed22dc53c41821b6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+cpplint = cpplint:main
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1756a599c18e1350cd51ffeac17f2cc8be568350
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/licenses/LICENSE
@@ -0,0 +1,27 @@
+cpplint.py and its corresponding unit tests are Copyright (C) 2009 Google Inc.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2432204571bc4ece673df9ad1a31ad4adf925099
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/cpplint-2.0.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+cpplint
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/LICENSE.txt b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3e01d05b189d7ebe54b01717c4e365fe45bb765b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/LICENSE.txt
@@ -0,0 +1,27 @@
+Copyright (c) 2005-2025, Michele Simionato
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..be5072eb0dd78161fe026992cf7010d5a05a8adb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/METADATA
@@ -0,0 +1,124 @@
+Metadata-Version: 2.2
+Name: decorator
+Version: 5.2.1
+Summary: Decorators for Humans
+Author-email: Michele Simionato
+License: BSD-2-Clause
+Keywords: decorators
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Natural Language :: English
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Utilities
+Requires-Python: >=3.8
+Description-Content-Type: text/x-rst
+License-File: LICENSE.txt
+
+Decorators for Humans
+=====================
+
+The goal of the decorator module is to make it easy to define
+signature-preserving function decorators and decorator factories.
+It also includes an implementation of multiple dispatch and other niceties
+(please check the docs). It is released under a two-clauses
+BSD license, i.e. basically you can do whatever you want with it but I am not
+responsible.
+
+Installation
+-------------
+
+If you are lazy, just perform
+
+ ``$ pip install decorator``
+
+which will install just the module on your system.
+
+If you prefer to install the full distribution from source, including
+the documentation, clone the `GitHub repo`_ or download the tarball_, unpack it and run
+
+ ``$ pip install .``
+
+in the main directory, possibly as superuser.
+
+.. _tarball: https://pypi.org/project/decorator/#files
+.. _GitHub repo: https://github.com/micheles/decorator
+
+Testing
+--------
+
+If you have the source code installation you can run the tests with
+
+ `$ python src/tests/test.py -v`
+
+or (if you have setuptools installed)
+
+ `$ python setup.py test`
+
+Notice that you may run into trouble if in your system there
+is an older version of the decorator module; in such a case remove the
+old version. It is safe even to copy the module `decorator.py` over
+an existing one, since we kept backward-compatibility for a long time.
+
+Repository
+---------------
+
+The project is hosted on GitHub. You can look at the source here:
+
+ https://github.com/micheles/decorator
+
+Documentation
+---------------
+
+The documentation has been moved to https://github.com/micheles/decorator/blob/master/docs/documentation.md
+
+From there you can get a PDF version by simply using the print
+functionality of your browser.
+
+Here is the documentation for previous versions of the module:
+
+https://github.com/micheles/decorator/blob/4.3.2/docs/tests.documentation.rst
+https://github.com/micheles/decorator/blob/4.2.1/docs/tests.documentation.rst
+https://github.com/micheles/decorator/blob/4.1.2/docs/tests.documentation.rst
+https://github.com/micheles/decorator/blob/4.0.0/documentation.rst
+https://github.com/micheles/decorator/blob/3.4.2/documentation.rst
+
+For the impatient
+-----------------
+
+Here is an example of how to define a family of decorators tracing slow
+operations:
+
+.. code-block:: python
+
+ from decorator import decorator
+
+ @decorator
+ def warn_slow(func, timelimit=60, *args, **kw):
+ t0 = time.time()
+ result = func(*args, **kw)
+ dt = time.time() - t0
+ if dt > timelimit:
+ logging.warning('%s took %d seconds', func.__name__, dt)
+ else:
+ logging.info('%s took %d seconds', func.__name__, dt)
+ return result
+
+ @warn_slow # warn if it takes more than 1 minute
+ def preprocess_input_files(inputdir, tempdir):
+ ...
+
+ @warn_slow(timelimit=600) # warn if it takes more than 10 minutes
+ def run_calculation(tempdir, outdir):
+ ...
+
+Enjoy!
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..9305e883028816986e3c036940909ff712e6dcbe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/RECORD
@@ -0,0 +1,9 @@
+__pycache__/decorator.cpython-310.pyc,,
+decorator-5.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+decorator-5.2.1.dist-info/LICENSE.txt,sha256=kU7m7Xil78FzvaaY8nCERMqdFA_MQIDGDQUD1A2znaY,1308
+decorator-5.2.1.dist-info/METADATA,sha256=i76fp7lNo0QbinX3NBJjSu_GhVp9A8iuab--m-8mKB4,3934
+decorator-5.2.1.dist-info/RECORD,,
+decorator-5.2.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
+decorator-5.2.1.dist-info/pbr.json,sha256=AL84oUUWQHwkd8OCPhLRo2NJjU5MDdmXMqRHv-posqs,47
+decorator-5.2.1.dist-info/top_level.txt,sha256=Kn6eQjo83ctWxXVyBMOYt0_YpjRjBznKYVuNyuC_DSI,10
+decorator.py,sha256=cWnO6cKKohQrXNEG1-Fauiw8djwE3f2PA2gJGofwgXA,17067
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..505164bc02d63fe6b0b3299f849a77c5f1beeb41
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (75.8.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/pbr.json b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/pbr.json
new file mode 100644
index 0000000000000000000000000000000000000000..cd04599789742039ac2f3b2b5cd60ce7a6d81c71
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/pbr.json
@@ -0,0 +1 @@
+{"is_release": false, "git_version": "8608a46"}
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3fe18a4d1c20592171597e32e7f633bc61fff1ed
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/decorator-5.2.1.dist-info/top_level.txt
@@ -0,0 +1 @@
+decorator
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/LICENSE b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..76f67efdc6470081b512a8db5bf2b1d4962d9c3c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023 Georgi Gerganov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..9e4fb97c351b77c21be3ba04cdfe8c6c6b420ee4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/METADATA
@@ -0,0 +1,126 @@
+Metadata-Version: 2.3
+Name: gguf
+Version: 0.17.1
+Summary: Read and write ML models in GGUF for GGML
+Keywords: ggml,gguf,llama.cpp
+Author: GGML
+Author-email: ggml@ggml.ai
+Requires-Python: >=3.8
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Provides-Extra: gui
+Requires-Dist: PySide6 (>=6.9,<7.0) ; (python_version >= "3.9" and python_version < "3.14") and (extra == "gui")
+Requires-Dist: numpy (>=1.17)
+Requires-Dist: pyyaml (>=5.1)
+Requires-Dist: tqdm (>=4.27)
+Project-URL: Homepage, https://ggml.ai
+Project-URL: Repository, https://github.com/ggml-org/llama.cpp
+Description-Content-Type: text/markdown
+
+## gguf
+
+This is a Python package for writing binary files in the [GGUF](https://github.com/ggml-org/ggml/pull/302)
+(GGML Universal File) format.
+
+See [convert_hf_to_gguf.py](https://github.com/ggml-org/llama.cpp/blob/master/convert_hf_to_gguf.py)
+as an example for its usage.
+
+## Installation
+```sh
+pip install gguf
+```
+
+Optionally, you can install gguf with the extra 'gui' to enable the visual GGUF editor.
+```sh
+pip install gguf[gui]
+```
+
+## API Examples/Simple Tools
+
+[examples/writer.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/examples/writer.py) — Generates `example.gguf` in the current directory to demonstrate generating a GGUF file. Note that this file cannot be used as a model.
+
+[examples/reader.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/examples/reader.py) — Extracts and displays key-value pairs and tensor details from a GGUF file in a readable format.
+
+[gguf/scripts/gguf_dump.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/gguf/scripts/gguf_dump.py) — Dumps a GGUF file's metadata to the console.
+
+[gguf/scripts/gguf_set_metadata.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/gguf/scripts/gguf_set_metadata.py) — Allows changing simple metadata values in a GGUF file by key.
+
+[gguf/scripts/gguf_convert_endian.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/gguf/scripts/gguf_convert_endian.py) — Allows converting the endianness of GGUF files.
+
+[gguf/scripts/gguf_new_metadata.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/gguf/scripts/gguf_new_metadata.py) — Copies a GGUF file with added/modified/removed metadata values.
+
+[gguf/scripts/gguf_editor_gui.py](https://github.com/ggml-org/llama.cpp/blob/master/gguf-py/gguf/scripts/gguf_editor_gui.py) — Allows for viewing, editing, adding, or removing metadata values within a GGUF file as well as viewing its tensors with a Qt interface.
+
+## Development
+Maintainers who participate in development of this package are advised to install it in editable mode:
+
+```sh
+cd /path/to/llama.cpp/gguf-py
+
+pip install --editable .
+```
+
+**Note**: This may require to upgrade your Pip installation, with a message saying that editable installation currently requires `setup.py`.
+In this case, upgrade Pip to the latest:
+
+```sh
+pip install --upgrade pip
+```
+
+## Automatic publishing with CI
+
+There's a GitHub workflow to make a release automatically upon creation of tags in a specified format.
+
+1. Bump the version in `pyproject.toml`.
+2. Create a tag named `gguf-vx.x.x` where `x.x.x` is the semantic version number.
+
+```sh
+git tag -a gguf-v1.0.0 -m "Version 1.0 release"
+```
+
+3. Push the tags.
+
+```sh
+git push origin --tags
+```
+
+## Manual publishing
+If you want to publish the package manually for any reason, you need to have `twine` and `build` installed:
+
+```sh
+pip install build twine
+```
+
+Then, follow these steps to release a new version:
+
+1. Bump the version in `pyproject.toml`.
+2. Build the package:
+
+```sh
+python -m build
+```
+
+3. Upload the generated distribution archives:
+
+```sh
+python -m twine upload dist/*
+```
+
+## Run Unit Tests
+
+From root of this repository you can run this command to run all the unit tests
+
+```bash
+python -m unittest discover ./gguf-py -v
+```
+
+## TODO
+- [ ] Include conversion scripts as command line entry points in this package.
+
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..18edfdf56f3a4a44a974e064e4dbeb3fe6eaac13
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/RECORD
@@ -0,0 +1,46 @@
+../../../bin/gguf-convert-endian,sha256=ChqZB9PUO-1EftYi7BgmrPc9EtEJpxwYdoXo9ed4Lm0,301
+../../../bin/gguf-dump,sha256=ZChkqUV4Vz2sx6v8g5Jk3IkcztHepZpALHuPJ5WGMwQ,291
+../../../bin/gguf-editor-gui,sha256=WKsAVl6G5nCiacuPbr9tMKR0Yp8blfv0J4mdqKo8I9o,297
+../../../bin/gguf-new-metadata,sha256=neHKZhfXtCaJa8b1wyYZSrYrnNTPUAa-Cwp4Z5VkhLw,299
+../../../bin/gguf-set-metadata,sha256=-ylZPWTs6gFpchkPkYmeOUrN4bvqN0Qt2Neezo_cs30,299
+gguf-0.17.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+gguf-0.17.1.dist-info/LICENSE,sha256=73jH5mWeNMeYGU8NNE6AfHIt5wy8oTWe9UdyZh4Ryjg,1072
+gguf-0.17.1.dist-info/METADATA,sha256=pa8_ce5ufoWKHq1zzh97He53EZjFtRFONFDWtl7mkAI,4348
+gguf-0.17.1.dist-info/RECORD,,
+gguf-0.17.1.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
+gguf-0.17.1.dist-info/entry_points.txt,sha256=TozYSFmMxpOaKE3brn9nWp-QkgM_sZ3a_uFDOXUCYig,273
+gguf/__init__.py,sha256=PM_AEEzX6ojGAodDt78_LIm19HRCXeA6IXpgcjINfC8,219
+gguf/__pycache__/__init__.cpython-310.pyc,,
+gguf/__pycache__/constants.cpython-310.pyc,,
+gguf/__pycache__/gguf.cpython-310.pyc,,
+gguf/__pycache__/gguf_reader.cpython-310.pyc,,
+gguf/__pycache__/gguf_writer.cpython-310.pyc,,
+gguf/__pycache__/lazy.cpython-310.pyc,,
+gguf/__pycache__/metadata.cpython-310.pyc,,
+gguf/__pycache__/quants.cpython-310.pyc,,
+gguf/__pycache__/tensor_mapping.cpython-310.pyc,,
+gguf/__pycache__/utility.cpython-310.pyc,,
+gguf/__pycache__/vocab.cpython-310.pyc,,
+gguf/constants.py,sha256=-92nfNa8XjXbHsMV9Hf0iGHwcmoXzH2JJ73rAv73NPE,89508
+gguf/gguf.py,sha256=8MDu7a0JEXhLUv_tjhYqDrWubVNc41cFvBYZbkZZenI,478
+gguf/gguf_reader.py,sha256=6uI4vaLeRC2MJV-uUjgsRoUZ-Rdszi8mE_bEPwnk6QE,14828
+gguf/gguf_writer.py,sha256=UJXqFa3T2EOLfPZ6ej3vuyV7OBfKXXaszvHKeHIWmSI,43935
+gguf/lazy.py,sha256=Axy_plbHoC34nMeK_ORbbxEyEFm-Fz8BxFIeqeipSYA,9214
+gguf/metadata.py,sha256=v0kxoYfCk_yXZSnzlSO9AhQ6z_HOUpzs0c6ZV4BRSbA,33301
+gguf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+gguf/quants.py,sha256=BLtCCqhHBtabaYaAp7EckyYOR5idmoKWhu_Hy3glotk,60771
+gguf/scripts/__pycache__/gguf_convert_endian.cpython-310.pyc,,
+gguf/scripts/__pycache__/gguf_dump.cpython-310.pyc,,
+gguf/scripts/__pycache__/gguf_editor_gui.cpython-310.pyc,,
+gguf/scripts/__pycache__/gguf_hash.cpython-310.pyc,,
+gguf/scripts/__pycache__/gguf_new_metadata.cpython-310.pyc,,
+gguf/scripts/__pycache__/gguf_set_metadata.cpython-310.pyc,,
+gguf/scripts/gguf_convert_endian.py,sha256=yzl_MAQ3jyn_9MmOWV1CksHqlohd7DmrG7REwas0rlo,7365
+gguf/scripts/gguf_dump.py,sha256=zDgZSSQLyO3S4YJsSUzdebDfwmdqQPN7_VtFZ5BkGAk,21785
+gguf/scripts/gguf_editor_gui.py,sha256=frdErSIB90N-sAvqUpbLfdDsaUGMMOWQ-0iumwzzm_M,64398
+gguf/scripts/gguf_hash.py,sha256=nyd8kzjRKnOFek5UaD19pNXeAVMXUfFEASZ8konkGX8,3725
+gguf/scripts/gguf_new_metadata.py,sha256=U_v5FgbH292x7bsi2dG4rbQcWc14nmAtZEWdLnbkIZs,9767
+gguf/scripts/gguf_set_metadata.py,sha256=yGEqcQlCimd-pVl23V7u1giJNN3vfvASRqW8em5YWzs,4145
+gguf/tensor_mapping.py,sha256=6pUDYgly0-yErLV8HSZFSnqyFKAp7SieditMEHMsYGI,55999
+gguf/utility.py,sha256=80rZ3MdGZ6bX0_yFvLoPTTOlxga8THcihF0q38y5h6M,10808
+gguf/vocab.py,sha256=Gr43idKqc4yBHQh20HfeW9oegYWLpM-L0ZKCVxPj4Lc,20788
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..9ed4d8facdffc976b12b8144fcda70b971ffea8f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: poetry-core 2.1.3
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5502bee07257f9f8e862720f7253205ff217f4d3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf-0.17.1.dist-info/entry_points.txt
@@ -0,0 +1,7 @@
+[console_scripts]
+gguf-convert-endian=gguf.scripts.gguf_convert_endian:main
+gguf-dump=gguf.scripts.gguf_dump:main
+gguf-editor-gui=gguf.scripts.gguf_editor_gui:main
+gguf-new-metadata=gguf.scripts.gguf_new_metadata:main
+gguf-set-metadata=gguf.scripts.gguf_set_metadata:main
+
diff --git a/venv/lib/python3.10/site-packages/gguf/__init__.py b/venv/lib/python3.10/site-packages/gguf/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..243defc4c1ca42d3713017d8902592f54ac849cd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/__init__.py
@@ -0,0 +1,9 @@
+from .constants import *
+from .lazy import *
+from .gguf_reader import *
+from .gguf_writer import *
+from .quants import *
+from .tensor_mapping import *
+from .vocab import *
+from .utility import *
+from .metadata import *
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0dc798c099a0cc6af3935d4499d39e07df504393
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3aa4d4922d292f1ad217a3d982f6543f42410709
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/constants.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4685f6f904976675e18ad6d2e54663867cb97d4d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_reader.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_reader.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5634ff685ccbaa9ab4d93c35a8ce3527d15bb4d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_reader.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_writer.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_writer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfe9090f4dec214aa3666c715788265b1f33f097
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/gguf_writer.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/lazy.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/lazy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f6393e78cb954356a0d7a4ecadf357e3207fa27
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/lazy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/metadata.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/metadata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0da325069c5e66bf1894fe7c6cd627a1ad5cfd1a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/metadata.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/quants.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/quants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..544c565f8fd55a2a12a15ee88a74f0ef291a464d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/quants.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/tensor_mapping.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/tensor_mapping.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be0e9bfd6f2c97bc5925f9d8e83dd28a6f4c4380
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/tensor_mapping.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/utility.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/utility.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db76a4accf74bec967c09a5881397f6b3112ac83
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/utility.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/__pycache__/vocab.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/__pycache__/vocab.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a006f5d2f05d305d6cee5d699dfb11a660eea47
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/__pycache__/vocab.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/constants.py b/venv/lib/python3.10/site-packages/gguf/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..834a1d5e1a97ed98f01196e0a0542afa95739b8c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/constants.py
@@ -0,0 +1,2438 @@
+from __future__ import annotations
+
+from enum import Enum, IntEnum, auto
+from typing import Any
+
+#
+# constants
+#
+
+GGUF_MAGIC = 0x46554747 # "GGUF"
+GGUF_VERSION = 3
+GGUF_DEFAULT_ALIGNMENT = 32
+GGML_QUANT_VERSION = 2 # GGML_QNT_VERSION from ggml.h
+
+#
+# metadata keys
+#
+
+
+class Keys:
+ class General:
+ TYPE = "general.type"
+ ARCHITECTURE = "general.architecture"
+ QUANTIZATION_VERSION = "general.quantization_version"
+ ALIGNMENT = "general.alignment"
+ FILE_TYPE = "general.file_type"
+
+ # Authorship Metadata
+ NAME = "general.name"
+ AUTHOR = "general.author"
+ VERSION = "general.version"
+ ORGANIZATION = "general.organization"
+
+ FINETUNE = "general.finetune"
+ BASENAME = "general.basename"
+
+ DESCRIPTION = "general.description"
+ QUANTIZED_BY = "general.quantized_by"
+
+ SIZE_LABEL = "general.size_label"
+
+ # Licensing details
+ LICENSE = "general.license"
+ LICENSE_NAME = "general.license.name"
+ LICENSE_LINK = "general.license.link"
+
+ # Typically represents the converted GGUF repo (Unless native)
+ URL = "general.url" # Model Website/Paper
+ DOI = "general.doi"
+ UUID = "general.uuid"
+ REPO_URL = "general.repo_url" # Model Source Repository (git/svn/etc...)
+
+ # Model Source during conversion
+ SOURCE_URL = "general.source.url" # Model Website/Paper
+ SOURCE_DOI = "general.source.doi"
+ SOURCE_UUID = "general.source.uuid"
+ SOURCE_REPO_URL = "general.source.repo_url" # Model Source Repository (git/svn/etc...)
+
+ # Base Model Source. There can be more than one source if it's a merged
+ # model like with 'Mistral-7B-Merge-14-v0.1'. This will assist in
+ # tracing linage of models as it is finetuned or merged over time.
+ BASE_MODEL_COUNT = "general.base_model.count"
+ BASE_MODEL_NAME = "general.base_model.{id}.name"
+ BASE_MODEL_AUTHOR = "general.base_model.{id}.author"
+ BASE_MODEL_VERSION = "general.base_model.{id}.version"
+ BASE_MODEL_ORGANIZATION = "general.base_model.{id}.organization"
+ BASE_MODEL_DESCRIPTION = "general.base_model.{id}.description"
+ BASE_MODEL_URL = "general.base_model.{id}.url" # Model Website/Paper
+ BASE_MODEL_DOI = "general.base_model.{id}.doi"
+ BASE_MODEL_UUID = "general.base_model.{id}.uuid"
+ BASE_MODEL_REPO_URL = "general.base_model.{id}.repo_url" # Model Source Repository (git/svn/etc...)
+
+ # Dataset Source
+ DATASET_COUNT = "general.dataset.count"
+ DATASET_NAME = "general.dataset.{id}.name"
+ DATASET_AUTHOR = "general.dataset.{id}.author"
+ DATASET_VERSION = "general.dataset.{id}.version"
+ DATASET_ORGANIZATION = "general.dataset.{id}.organization"
+ DATASET_DESCRIPTION = "general.dataset.{id}.description"
+ DATASET_URL = "general.dataset.{id}.url" # Model Website/Paper
+ DATASET_DOI = "general.dataset.{id}.doi"
+ DATASET_UUID = "general.dataset.{id}.uuid"
+ DATASET_REPO_URL = "general.dataset.{id}.repo_url" # Model Source Repository (git/svn/etc...)
+
+ # Array based KV stores
+ TAGS = "general.tags"
+ LANGUAGES = "general.languages"
+
+ class LLM:
+ VOCAB_SIZE = "{arch}.vocab_size"
+ CONTEXT_LENGTH = "{arch}.context_length"
+ EMBEDDING_LENGTH = "{arch}.embedding_length"
+ FEATURES_LENGTH = "{arch}.features_length"
+ BLOCK_COUNT = "{arch}.block_count"
+ LEADING_DENSE_BLOCK_COUNT = "{arch}.leading_dense_block_count"
+ FEED_FORWARD_LENGTH = "{arch}.feed_forward_length"
+ EXPERT_FEED_FORWARD_LENGTH = "{arch}.expert_feed_forward_length"
+ EXPERT_SHARED_FEED_FORWARD_LENGTH = "{arch}.expert_shared_feed_forward_length"
+ USE_PARALLEL_RESIDUAL = "{arch}.use_parallel_residual"
+ TENSOR_DATA_LAYOUT = "{arch}.tensor_data_layout"
+ EXPERT_COUNT = "{arch}.expert_count"
+ EXPERT_USED_COUNT = "{arch}.expert_used_count"
+ EXPERT_SHARED_COUNT = "{arch}.expert_shared_count"
+ EXPERT_WEIGHTS_SCALE = "{arch}.expert_weights_scale"
+ EXPERT_WEIGHTS_NORM = "{arch}.expert_weights_norm"
+ EXPERT_GATING_FUNC = "{arch}.expert_gating_func"
+ MOE_EVERY_N_LAYERS = "{arch}.moe_every_n_layers"
+ POOLING_TYPE = "{arch}.pooling_type"
+ LOGIT_SCALE = "{arch}.logit_scale"
+ DECODER_START_TOKEN_ID = "{arch}.decoder_start_token_id"
+ ATTN_LOGIT_SOFTCAPPING = "{arch}.attn_logit_softcapping"
+ FINAL_LOGIT_SOFTCAPPING = "{arch}.final_logit_softcapping"
+ SWIN_NORM = "{arch}.swin_norm"
+ RESCALE_EVERY_N_LAYERS = "{arch}.rescale_every_n_layers"
+ TIME_MIX_EXTRA_DIM = "{arch}.time_mix_extra_dim"
+ TIME_DECAY_EXTRA_DIM = "{arch}.time_decay_extra_dim"
+ RESIDUAL_SCALE = "{arch}.residual_scale"
+ EMBEDDING_SCALE = "{arch}.embedding_scale"
+ TOKEN_SHIFT_COUNT = "{arch}.token_shift_count"
+ INTERLEAVE_MOE_LAYER_STEP = "{arch}.interleave_moe_layer_step"
+
+ class Attention:
+ HEAD_COUNT = "{arch}.attention.head_count"
+ HEAD_COUNT_KV = "{arch}.attention.head_count_kv"
+ MAX_ALIBI_BIAS = "{arch}.attention.max_alibi_bias"
+ CLAMP_KQV = "{arch}.attention.clamp_kqv"
+ KEY_LENGTH = "{arch}.attention.key_length"
+ VALUE_LENGTH = "{arch}.attention.value_length"
+ LAYERNORM_EPS = "{arch}.attention.layer_norm_epsilon"
+ LAYERNORM_RMS_EPS = "{arch}.attention.layer_norm_rms_epsilon"
+ GROUPNORM_EPS = "{arch}.attention.group_norm_epsilon"
+ GROUPNORM_GROUPS = "{arch}.attention.group_norm_groups"
+ CAUSAL = "{arch}.attention.causal"
+ Q_LORA_RANK = "{arch}.attention.q_lora_rank"
+ KV_LORA_RANK = "{arch}.attention.kv_lora_rank"
+ DECAY_LORA_RANK = "{arch}.attention.decay_lora_rank"
+ ICLR_LORA_RANK = "{arch}.attention.iclr_lora_rank"
+ VALUE_RESIDUAL_MIX_LORA_RANK = "{arch}.attention.value_residual_mix_lora_rank"
+ GATE_LORA_RANK = "{arch}.attention.gate_lora_rank"
+ REL_BUCKETS_COUNT = "{arch}.attention.relative_buckets_count"
+ SLIDING_WINDOW = "{arch}.attention.sliding_window"
+ SCALE = "{arch}.attention.scale"
+ KEY_LENGTH_MLA = "{arch}.attention.key_length_mla"
+ VALUE_LENGTH_MLA = "{arch}.attention.value_length_mla"
+
+ class Rope:
+ DIMENSION_COUNT = "{arch}.rope.dimension_count"
+ DIMENSION_SECTIONS = "{arch}.rope.dimension_sections"
+ FREQ_BASE = "{arch}.rope.freq_base"
+ SCALING_TYPE = "{arch}.rope.scaling.type"
+ SCALING_FACTOR = "{arch}.rope.scaling.factor"
+ SCALING_ATTN_FACTOR = "{arch}.rope.scaling.attn_factor"
+ SCALING_ORIG_CTX_LEN = "{arch}.rope.scaling.original_context_length"
+ SCALING_FINETUNED = "{arch}.rope.scaling.finetuned"
+ SCALING_YARN_LOG_MUL = "{arch}.rope.scaling.yarn_log_multiplier"
+
+ class Split:
+ LLM_KV_SPLIT_NO = "split.no"
+ LLM_KV_SPLIT_COUNT = "split.count"
+ LLM_KV_SPLIT_TENSORS_COUNT = "split.tensors.count"
+
+ class SSM:
+ CONV_KERNEL = "{arch}.ssm.conv_kernel"
+ INNER_SIZE = "{arch}.ssm.inner_size"
+ STATE_SIZE = "{arch}.ssm.state_size"
+ TIME_STEP_RANK = "{arch}.ssm.time_step_rank"
+ DT_B_C_RMS = "{arch}.ssm.dt_b_c_rms"
+
+ class WKV:
+ HEAD_SIZE = "{arch}.wkv.head_size"
+
+ class PosNet:
+ EMBEDDING_LENGTH = "{arch}.posnet.embedding_length"
+ BLOCK_COUNT = "{arch}.posnet.block_count"
+
+ class ConvNext:
+ EMBEDDING_LENGTH = "{arch}.convnext.embedding_length"
+ BLOCK_COUNT = "{arch}.convnext.block_count"
+
+ class Classifier:
+ OUTPUT_LABELS = "{arch}.classifier.output_labels"
+
+ class Tokenizer:
+ MODEL = "tokenizer.ggml.model"
+ PRE = "tokenizer.ggml.pre"
+ LIST = "tokenizer.ggml.tokens"
+ TOKEN_TYPE = "tokenizer.ggml.token_type"
+ TOKEN_TYPE_COUNT = "tokenizer.ggml.token_type_count" # for BERT-style token types
+ SCORES = "tokenizer.ggml.scores"
+ MERGES = "tokenizer.ggml.merges"
+ BOS_ID = "tokenizer.ggml.bos_token_id"
+ EOS_ID = "tokenizer.ggml.eos_token_id"
+ EOT_ID = "tokenizer.ggml.eot_token_id"
+ EOM_ID = "tokenizer.ggml.eom_token_id"
+ UNK_ID = "tokenizer.ggml.unknown_token_id"
+ SEP_ID = "tokenizer.ggml.seperator_token_id"
+ PAD_ID = "tokenizer.ggml.padding_token_id"
+ MASK_ID = "tokenizer.ggml.mask_token_id"
+ ADD_BOS = "tokenizer.ggml.add_bos_token"
+ ADD_EOS = "tokenizer.ggml.add_eos_token"
+ ADD_PREFIX = "tokenizer.ggml.add_space_prefix"
+ REMOVE_EXTRA_WS = "tokenizer.ggml.remove_extra_whitespaces"
+ PRECOMPILED_CHARSMAP = "tokenizer.ggml.precompiled_charsmap"
+ HF_JSON = "tokenizer.huggingface.json"
+ RWKV = "tokenizer.rwkv.world"
+ CHAT_TEMPLATE = "tokenizer.chat_template"
+ CHAT_TEMPLATE_N = "tokenizer.chat_template.{name}"
+ CHAT_TEMPLATES = "tokenizer.chat_templates"
+ # FIM/Infill special tokens constants
+ FIM_PRE_ID = "tokenizer.ggml.fim_pre_token_id"
+ FIM_SUF_ID = "tokenizer.ggml.fim_suf_token_id"
+ FIM_MID_ID = "tokenizer.ggml.fim_mid_token_id"
+ FIM_PAD_ID = "tokenizer.ggml.fim_pad_token_id"
+ FIM_REP_ID = "tokenizer.ggml.fim_rep_token_id"
+ FIM_SEP_ID = "tokenizer.ggml.fim_sep_token_id"
+ # deprecated:
+ PREFIX_ID = "tokenizer.ggml.prefix_token_id"
+ SUFFIX_ID = "tokenizer.ggml.suffix_token_id"
+ MIDDLE_ID = "tokenizer.ggml.middle_token_id"
+
+ class Adapter:
+ TYPE = "adapter.type"
+ LORA_ALPHA = "adapter.lora.alpha"
+
+ class Clip:
+ PROJECTOR_TYPE = "clip.projector_type"
+ HAS_VISION_ENCODER = "clip.has_vision_encoder"
+ HAS_AUDIO_ENCODER = "clip.has_audio_encoder"
+ HAS_LLAVA_PROJECTOR = "clip.has_llava_projector"
+
+ class ClipVision:
+ IMAGE_SIZE = "clip.vision.image_size"
+ PATCH_SIZE = "clip.vision.patch_size"
+ EMBEDDING_LENGTH = "clip.vision.embedding_length"
+ FEED_FORWARD_LENGTH = "clip.vision.feed_forward_length"
+ PROJECTION_DIM = "clip.vision.projection_dim"
+ BLOCK_COUNT = "clip.vision.block_count"
+ IMAGE_MEAN = "clip.vision.image_mean"
+ IMAGE_STD = "clip.vision.image_std"
+ SPATIAL_MERGE_SIZE = "clip.vision.spatial_merge_size"
+ USE_GELU = "clip.use_gelu"
+ USE_SILU = "clip.use_silu"
+ N_WA_PATTERN = "clip.vision.n_wa_pattern" # used by qwen2.5vl
+
+ class Attention:
+ HEAD_COUNT = "clip.vision.attention.head_count"
+ LAYERNORM_EPS = "clip.vision.attention.layer_norm_epsilon"
+
+ class Projector:
+ SCALE_FACTOR = "clip.vision.projector.scale_factor"
+
+ class ClipAudio:
+ NUM_MEL_BINS = "clip.audio.num_mel_bins"
+ EMBEDDING_LENGTH = "clip.audio.embedding_length"
+ FEED_FORWARD_LENGTH = "clip.audio.feed_forward_length"
+ PROJECTION_DIM = "clip.audio.projection_dim"
+ BLOCK_COUNT = "clip.audio.block_count"
+
+ class Attention:
+ HEAD_COUNT = "clip.audio.attention.head_count"
+ LAYERNORM_EPS = "clip.audio.attention.layer_norm_epsilon"
+
+ class Projector:
+ STACK_FACTOR = "clip.audio.projector.stack_factor"
+
+#
+# recommended mapping of model tensor names for storage in gguf
+#
+
+
+class GGUFType:
+ MODEL = "model"
+ ADAPTER = "adapter"
+ MMPROJ = "mmproj" # dummy, unused for now
+
+
+class MODEL_ARCH(IntEnum):
+ MMPROJ = auto() # dummy arch for clip.cpp
+ LLAMA = auto()
+ LLAMA4 = auto()
+ DECI = auto()
+ FALCON = auto()
+ BAICHUAN = auto()
+ GROK = auto()
+ GPT2 = auto()
+ GPTJ = auto()
+ GPTNEOX = auto()
+ MPT = auto()
+ STARCODER = auto()
+ REFACT = auto()
+ BERT = auto()
+ NOMIC_BERT = auto()
+ NOMIC_BERT_MOE = auto()
+ NEO_BERT = auto()
+ JINA_BERT_V2 = auto()
+ BLOOM = auto()
+ STABLELM = auto()
+ QWEN = auto()
+ QWEN2 = auto()
+ QWEN2MOE = auto()
+ QWEN2VL = auto()
+ QWEN3 = auto()
+ QWEN3MOE = auto()
+ PHI2 = auto()
+ PHI3 = auto()
+ PHIMOE = auto()
+ PLAMO = auto()
+ CODESHELL = auto()
+ ORION = auto()
+ INTERNLM2 = auto()
+ MINICPM = auto()
+ MINICPM3 = auto()
+ GEMMA = auto()
+ GEMMA2 = auto()
+ GEMMA3 = auto()
+ STARCODER2 = auto()
+ RWKV6 = auto()
+ RWKV6QWEN2 = auto()
+ RWKV7 = auto()
+ ARWKV7 = auto()
+ MAMBA = auto()
+ XVERSE = auto()
+ COMMAND_R = auto()
+ COHERE2 = auto()
+ DBRX = auto()
+ OLMO = auto()
+ OLMO2 = auto()
+ OLMOE = auto()
+ OPENELM = auto()
+ ARCTIC = auto()
+ DEEPSEEK = auto()
+ DEEPSEEK2 = auto()
+ CHATGLM = auto()
+ GLM4 = auto()
+ BITNET = auto()
+ T5 = auto()
+ T5ENCODER = auto()
+ JAIS = auto()
+ NEMOTRON = auto()
+ EXAONE = auto()
+ GRANITE = auto()
+ GRANITE_MOE = auto()
+ CHAMELEON = auto()
+ WAVTOKENIZER_DEC = auto()
+ PLM = auto()
+ BAILINGMOE = auto()
+ DOTS1 = auto()
+ ARCEE = auto()
+
+
+class VISION_PROJECTOR_TYPE(IntEnum):
+ MLP = auto()
+ LDP = auto()
+ LDPV2 = auto()
+ RESAMPLER = auto()
+ GLM_EDGE = auto()
+ MERGER = auto()
+ GEMMA3 = auto()
+
+
+class MODEL_TENSOR(IntEnum):
+ TOKEN_EMBD = auto()
+ TOKEN_EMBD_NORM = auto()
+ TOKEN_TYPES = auto()
+ POS_EMBD = auto()
+ OUTPUT = auto()
+ OUTPUT_NORM = auto()
+ ROPE_FREQS = auto()
+ ROPE_FACTORS_LONG = auto()
+ ROPE_FACTORS_SHORT = auto()
+ ATTN_Q = auto()
+ ATTN_K = auto()
+ ATTN_V = auto()
+ ATTN_QKV = auto()
+ ATTN_OUT = auto()
+ ATTN_NORM = auto()
+ ATTN_NORM_2 = auto()
+ ATTN_OUT_NORM = auto()
+ ATTN_POST_NORM = auto()
+ ATTN_ROT_EMBD = auto()
+ FFN_GATE_INP = auto()
+ FFN_GATE_INP_SHEXP = auto()
+ FFN_NORM = auto()
+ FFN_PRE_NORM = auto()
+ FFN_POST_NORM = auto()
+ FFN_GATE = auto()
+ FFN_DOWN = auto()
+ FFN_UP = auto()
+ FFN_ACT = auto()
+ FFN_NORM_EXP = auto()
+ FFN_GATE_EXP = auto()
+ FFN_DOWN_EXP = auto()
+ FFN_UP_EXP = auto()
+ FFN_GATE_SHEXP = auto()
+ FFN_DOWN_SHEXP = auto()
+ FFN_UP_SHEXP = auto()
+ FFN_EXP_PROBS_B = auto()
+ ATTN_Q_NORM = auto()
+ ATTN_K_NORM = auto()
+ LAYER_OUT_NORM = auto()
+ SSM_IN = auto()
+ SSM_CONV1D = auto()
+ SSM_X = auto()
+ SSM_DT = auto()
+ SSM_A = auto()
+ SSM_D = auto()
+ SSM_OUT = auto()
+ TIME_MIX_W0 = auto()
+ TIME_MIX_W1 = auto()
+ TIME_MIX_W2 = auto()
+ TIME_MIX_A0 = auto()
+ TIME_MIX_A1 = auto()
+ TIME_MIX_A2 = auto()
+ TIME_MIX_V0 = auto()
+ TIME_MIX_V1 = auto()
+ TIME_MIX_V2 = auto()
+ TIME_MIX_G1 = auto()
+ TIME_MIX_G2 = auto()
+ TIME_MIX_K_K = auto()
+ TIME_MIX_K_A = auto()
+ TIME_MIX_R_K = auto()
+ TIME_MIX_LERP_X = auto()
+ TIME_MIX_LERP_K = auto()
+ TIME_MIX_LERP_V = auto()
+ TIME_MIX_LERP_R = auto()
+ TIME_MIX_LERP_G = auto()
+ TIME_MIX_LERP_FUSED = auto()
+ TIME_MIX_LERP_W = auto()
+ TIME_MIX_FIRST = auto()
+ TIME_MIX_DECAY = auto()
+ TIME_MIX_DECAY_W1 = auto()
+ TIME_MIX_DECAY_W2 = auto()
+ TIME_MIX_KEY = auto()
+ TIME_MIX_VALUE = auto()
+ TIME_MIX_RECEPTANCE = auto()
+ TIME_MIX_GATE = auto()
+ TIME_MIX_LN = auto()
+ TIME_MIX_OUTPUT = auto()
+ CHANNEL_MIX_LERP_K = auto()
+ CHANNEL_MIX_LERP_R = auto()
+ CHANNEL_MIX_KEY = auto()
+ CHANNEL_MIX_RECEPTANCE = auto()
+ CHANNEL_MIX_VALUE = auto()
+ ATTN_Q_A = auto()
+ ATTN_Q_B = auto()
+ ATTN_KV_A_MQA = auto()
+ ATTN_KV_B = auto()
+ ATTN_K_B = auto()
+ ATTN_V_B = auto()
+ ATTN_Q_A_NORM = auto()
+ ATTN_KV_A_NORM = auto()
+ FFN_SUB_NORM = auto()
+ ATTN_SUB_NORM = auto()
+ DEC_ATTN_NORM = auto()
+ DEC_ATTN_Q = auto()
+ DEC_ATTN_K = auto()
+ DEC_ATTN_V = auto()
+ DEC_ATTN_OUT = auto()
+ DEC_ATTN_REL_B = auto()
+ DEC_CROSS_ATTN_NORM = auto()
+ DEC_CROSS_ATTN_Q = auto()
+ DEC_CROSS_ATTN_K = auto()
+ DEC_CROSS_ATTN_V = auto()
+ DEC_CROSS_ATTN_OUT = auto()
+ DEC_CROSS_ATTN_REL_B = auto()
+ DEC_FFN_NORM = auto()
+ DEC_FFN_GATE = auto()
+ DEC_FFN_DOWN = auto()
+ DEC_FFN_UP = auto()
+ DEC_OUTPUT_NORM = auto()
+ ENC_ATTN_NORM = auto()
+ ENC_ATTN_Q = auto()
+ ENC_ATTN_K = auto()
+ ENC_ATTN_V = auto()
+ ENC_ATTN_OUT = auto()
+ ENC_ATTN_REL_B = auto()
+ ENC_FFN_NORM = auto()
+ ENC_FFN_GATE = auto()
+ ENC_FFN_DOWN = auto()
+ ENC_FFN_UP = auto()
+ ENC_OUTPUT_NORM = auto()
+ CLS = auto() # classifier
+ CLS_OUT = auto() # classifier output projection
+ CONV1D = auto()
+ CONVNEXT_DW = auto()
+ CONVNEXT_NORM = auto()
+ CONVNEXT_PW1 = auto()
+ CONVNEXT_PW2 = auto()
+ CONVNEXT_GAMMA = auto()
+ POSNET_CONV1 = auto()
+ POSNET_CONV2 = auto()
+ POSNET_NORM = auto()
+ POSNET_NORM1 = auto()
+ POSNET_NORM2 = auto()
+ POSNET_ATTN_NORM = auto()
+ POSNET_ATTN_Q = auto()
+ POSNET_ATTN_K = auto()
+ POSNET_ATTN_V = auto()
+ POSNET_ATTN_OUT = auto()
+ # vision
+ V_MMPROJ = auto()
+ V_MMPROJ_FC = auto()
+ V_MMPROJ_MLP = auto()
+ V_MMPROJ_PEG = auto()
+ V_ENC_EMBD_CLS = auto()
+ V_ENC_EMBD_PATCH = auto()
+ V_ENC_EMBD_POS = auto()
+ V_ENC_INPUT_NORM = auto()
+ V_ENC_ATTN_Q = auto()
+ V_ENC_ATTN_Q_NORM = auto()
+ V_ENC_ATTN_K = auto()
+ V_ENC_ATTN_K_NORM = auto()
+ V_ENC_ATTN_V = auto()
+ V_ENC_ATTN_O = auto()
+ V_ENC_ATTN_O_NORM = auto()
+ V_ENC_POST_ATTN_NORM = auto()
+ V_ENC_FFN_UP = auto()
+ V_ENC_FFN_GATE = auto()
+ V_ENC_FFN_DOWN = auto()
+ V_LAYER_SCALE_1 = auto()
+ V_LAYER_SCALE_2 = auto()
+ V_PRE_NORM = auto()
+ V_POST_NORM = auto()
+ V_MM_INP_NORM = auto()
+ V_MM_INP_PROJ = auto() # gemma3
+ V_MM_SOFT_EMB_NORM = auto() # gemma3
+ V_RESMPL_POS_EMBD_K = auto() # minicpmv
+ V_RESMPL_ATTN_Q = auto() # minicpmv
+ V_RESMPL_ATTN_K = auto() # minicpmv
+ V_RESMPL_ATTN_V = auto() # minicpmv
+ V_RESMPL_ATTN_OUT = auto() # minicpmv
+ V_RESMPL_KV = auto() # minicpmv
+ V_RESMPL_KV_NORM = auto() # minicpmv
+ V_RESMPL_POST_NORM = auto() # minicpmv
+ V_RESMPL_Q_NORM = auto() # minicpmv
+ V_RESMPL_PROJ = auto() # minicpmv
+ V_RESMPL_QUERY = auto() # minicpmv
+ V_TOK_EMBD_IMG_BREAK = auto() # pixtral
+ V_MM_PATCH_MERGER = auto() # mistral small 3.1
+ # audio (mtmd)
+ A_ENC_EMBD_POS = auto()
+ A_ENC_CONV1D = auto()
+ A_PRE_NORM = auto()
+ A_POST_NORM = auto()
+ A_ENC_ATTN_Q = auto()
+ A_ENC_ATTN_K = auto()
+ A_ENC_ATTN_V = auto()
+ A_ENC_INPUT_NORM = auto()
+ A_ENC_OUTPUT = auto()
+ A_ENC_OUTPUT_NORM = auto()
+ A_ENC_FFN_UP = auto()
+ A_ENC_FFN_GATE = auto()
+ A_ENC_FFN_DOWN = auto()
+ A_MMPROJ = auto()
+ A_MMPROJ_FC = auto()
+ A_MM_NORM_PRE = auto()
+ A_MM_NORM_MID = auto()
+
+
+MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
+ MODEL_ARCH.MMPROJ: "clip", # dummy arch for clip.cpp
+ MODEL_ARCH.LLAMA: "llama",
+ MODEL_ARCH.LLAMA4: "llama4",
+ MODEL_ARCH.DECI: "deci",
+ MODEL_ARCH.FALCON: "falcon",
+ MODEL_ARCH.BAICHUAN: "baichuan",
+ MODEL_ARCH.GROK: "grok",
+ MODEL_ARCH.GPT2: "gpt2",
+ MODEL_ARCH.GPTJ: "gptj",
+ MODEL_ARCH.GPTNEOX: "gptneox",
+ MODEL_ARCH.MPT: "mpt",
+ MODEL_ARCH.STARCODER: "starcoder",
+ MODEL_ARCH.REFACT: "refact",
+ MODEL_ARCH.BERT: "bert",
+ MODEL_ARCH.NOMIC_BERT: "nomic-bert",
+ MODEL_ARCH.NOMIC_BERT_MOE: "nomic-bert-moe",
+ MODEL_ARCH.NEO_BERT: "neo-bert",
+ MODEL_ARCH.JINA_BERT_V2: "jina-bert-v2",
+ MODEL_ARCH.BLOOM: "bloom",
+ MODEL_ARCH.STABLELM: "stablelm",
+ MODEL_ARCH.QWEN: "qwen",
+ MODEL_ARCH.QWEN2: "qwen2",
+ MODEL_ARCH.QWEN2MOE: "qwen2moe",
+ MODEL_ARCH.QWEN2VL: "qwen2vl",
+ MODEL_ARCH.QWEN3: "qwen3",
+ MODEL_ARCH.QWEN3MOE: "qwen3moe",
+ MODEL_ARCH.PHI2: "phi2",
+ MODEL_ARCH.PHI3: "phi3",
+ MODEL_ARCH.PHIMOE: "phimoe",
+ MODEL_ARCH.PLAMO: "plamo",
+ MODEL_ARCH.CODESHELL: "codeshell",
+ MODEL_ARCH.ORION: "orion",
+ MODEL_ARCH.INTERNLM2: "internlm2",
+ MODEL_ARCH.MINICPM: "minicpm",
+ MODEL_ARCH.MINICPM3: "minicpm3",
+ MODEL_ARCH.GEMMA: "gemma",
+ MODEL_ARCH.GEMMA2: "gemma2",
+ MODEL_ARCH.GEMMA3: "gemma3",
+ MODEL_ARCH.STARCODER2: "starcoder2",
+ MODEL_ARCH.RWKV6: "rwkv6",
+ MODEL_ARCH.RWKV6QWEN2: "rwkv6qwen2",
+ MODEL_ARCH.RWKV7: "rwkv7",
+ MODEL_ARCH.ARWKV7: "arwkv7",
+ MODEL_ARCH.MAMBA: "mamba",
+ MODEL_ARCH.XVERSE: "xverse",
+ MODEL_ARCH.COMMAND_R: "command-r",
+ MODEL_ARCH.COHERE2: "cohere2",
+ MODEL_ARCH.DBRX: "dbrx",
+ MODEL_ARCH.OLMO: "olmo",
+ MODEL_ARCH.OLMO2: "olmo2",
+ MODEL_ARCH.OLMOE: "olmoe",
+ MODEL_ARCH.OPENELM: "openelm",
+ MODEL_ARCH.ARCTIC: "arctic",
+ MODEL_ARCH.DEEPSEEK: "deepseek",
+ MODEL_ARCH.DEEPSEEK2: "deepseek2",
+ MODEL_ARCH.CHATGLM: "chatglm",
+ MODEL_ARCH.GLM4: "glm4",
+ MODEL_ARCH.BITNET: "bitnet",
+ MODEL_ARCH.T5: "t5",
+ MODEL_ARCH.T5ENCODER: "t5encoder",
+ MODEL_ARCH.JAIS: "jais",
+ MODEL_ARCH.NEMOTRON: "nemotron",
+ MODEL_ARCH.EXAONE: "exaone",
+ MODEL_ARCH.GRANITE: "granite",
+ MODEL_ARCH.GRANITE_MOE: "granitemoe",
+ MODEL_ARCH.CHAMELEON: "chameleon",
+ MODEL_ARCH.WAVTOKENIZER_DEC: "wavtokenizer-dec",
+ MODEL_ARCH.PLM: "plm",
+ MODEL_ARCH.BAILINGMOE: "bailingmoe",
+ MODEL_ARCH.DOTS1: "dots1",
+ MODEL_ARCH.ARCEE: "arcee",
+}
+
+VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = {
+ VISION_PROJECTOR_TYPE.MLP: "mlp",
+ VISION_PROJECTOR_TYPE.LDP: "ldp",
+ VISION_PROJECTOR_TYPE.LDPV2: "ldpv2",
+ VISION_PROJECTOR_TYPE.RESAMPLER: "resampler",
+ VISION_PROJECTOR_TYPE.GLM_EDGE: "adapter",
+ VISION_PROJECTOR_TYPE.MERGER: "qwen2vl_merger",
+ VISION_PROJECTOR_TYPE.GEMMA3: "gemma3",
+}
+
+TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
+ MODEL_TENSOR.TOKEN_EMBD: "token_embd",
+ MODEL_TENSOR.TOKEN_EMBD_NORM: "token_embd_norm",
+ MODEL_TENSOR.TOKEN_TYPES: "token_types",
+ MODEL_TENSOR.POS_EMBD: "position_embd",
+ MODEL_TENSOR.OUTPUT_NORM: "output_norm",
+ MODEL_TENSOR.OUTPUT: "output",
+ MODEL_TENSOR.ROPE_FREQS: "rope_freqs",
+ MODEL_TENSOR.ROPE_FACTORS_LONG: "rope_factors_long",
+ MODEL_TENSOR.ROPE_FACTORS_SHORT: "rope_factors_short",
+ MODEL_TENSOR.ATTN_NORM: "blk.{bid}.attn_norm",
+ MODEL_TENSOR.ATTN_NORM_2: "blk.{bid}.attn_norm_2",
+ MODEL_TENSOR.ATTN_QKV: "blk.{bid}.attn_qkv",
+ MODEL_TENSOR.ATTN_Q: "blk.{bid}.attn_q",
+ MODEL_TENSOR.ATTN_K: "blk.{bid}.attn_k",
+ MODEL_TENSOR.ATTN_V: "blk.{bid}.attn_v",
+ MODEL_TENSOR.ATTN_OUT: "blk.{bid}.attn_output",
+ MODEL_TENSOR.ATTN_ROT_EMBD: "blk.{bid}.attn_rot_embd",
+ MODEL_TENSOR.ATTN_Q_NORM: "blk.{bid}.attn_q_norm",
+ MODEL_TENSOR.ATTN_K_NORM: "blk.{bid}.attn_k_norm",
+ MODEL_TENSOR.ATTN_OUT_NORM: "blk.{bid}.attn_output_norm",
+ MODEL_TENSOR.ATTN_POST_NORM: "blk.{bid}.post_attention_norm",
+ MODEL_TENSOR.FFN_GATE_INP: "blk.{bid}.ffn_gate_inp",
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP: "blk.{bid}.ffn_gate_inp_shexp",
+ MODEL_TENSOR.FFN_NORM: "blk.{bid}.ffn_norm",
+ MODEL_TENSOR.FFN_PRE_NORM: "blk.{bid}.ffn_norm",
+ MODEL_TENSOR.FFN_POST_NORM: "blk.{bid}.post_ffw_norm",
+ MODEL_TENSOR.FFN_GATE: "blk.{bid}.ffn_gate",
+ MODEL_TENSOR.FFN_DOWN: "blk.{bid}.ffn_down",
+ MODEL_TENSOR.FFN_UP: "blk.{bid}.ffn_up",
+ MODEL_TENSOR.FFN_GATE_SHEXP: "blk.{bid}.ffn_gate_shexp",
+ MODEL_TENSOR.FFN_DOWN_SHEXP: "blk.{bid}.ffn_down_shexp",
+ MODEL_TENSOR.FFN_UP_SHEXP: "blk.{bid}.ffn_up_shexp",
+ MODEL_TENSOR.FFN_ACT: "blk.{bid}.ffn",
+ MODEL_TENSOR.FFN_NORM_EXP: "blk.{bid}.ffn_norm_exps",
+ MODEL_TENSOR.FFN_GATE_EXP: "blk.{bid}.ffn_gate_exps",
+ MODEL_TENSOR.FFN_DOWN_EXP: "blk.{bid}.ffn_down_exps",
+ MODEL_TENSOR.FFN_UP_EXP: "blk.{bid}.ffn_up_exps",
+ MODEL_TENSOR.FFN_EXP_PROBS_B: "blk.{bid}.exp_probs_b",
+ MODEL_TENSOR.LAYER_OUT_NORM: "blk.{bid}.layer_output_norm",
+ MODEL_TENSOR.SSM_IN: "blk.{bid}.ssm_in",
+ MODEL_TENSOR.SSM_CONV1D: "blk.{bid}.ssm_conv1d",
+ MODEL_TENSOR.SSM_X: "blk.{bid}.ssm_x",
+ MODEL_TENSOR.SSM_DT: "blk.{bid}.ssm_dt",
+ MODEL_TENSOR.SSM_A: "blk.{bid}.ssm_a",
+ MODEL_TENSOR.SSM_D: "blk.{bid}.ssm_d",
+ MODEL_TENSOR.SSM_OUT: "blk.{bid}.ssm_out",
+ MODEL_TENSOR.TIME_MIX_W0: "blk.{bid}.time_mix_w0",
+ MODEL_TENSOR.TIME_MIX_W1: "blk.{bid}.time_mix_w1",
+ MODEL_TENSOR.TIME_MIX_W2: "blk.{bid}.time_mix_w2",
+ MODEL_TENSOR.TIME_MIX_A0: "blk.{bid}.time_mix_a0",
+ MODEL_TENSOR.TIME_MIX_A1: "blk.{bid}.time_mix_a1",
+ MODEL_TENSOR.TIME_MIX_A2: "blk.{bid}.time_mix_a2",
+ MODEL_TENSOR.TIME_MIX_V0: "blk.{bid}.time_mix_v0",
+ MODEL_TENSOR.TIME_MIX_V1: "blk.{bid}.time_mix_v1",
+ MODEL_TENSOR.TIME_MIX_V2: "blk.{bid}.time_mix_v2",
+ MODEL_TENSOR.TIME_MIX_G1: "blk.{bid}.time_mix_g1",
+ MODEL_TENSOR.TIME_MIX_G2: "blk.{bid}.time_mix_g2",
+ MODEL_TENSOR.TIME_MIX_K_K: "blk.{bid}.time_mix_k_k",
+ MODEL_TENSOR.TIME_MIX_K_A: "blk.{bid}.time_mix_k_a",
+ MODEL_TENSOR.TIME_MIX_R_K: "blk.{bid}.time_mix_r_k",
+ MODEL_TENSOR.TIME_MIX_LERP_X: "blk.{bid}.time_mix_lerp_x",
+ MODEL_TENSOR.TIME_MIX_LERP_K: "blk.{bid}.time_mix_lerp_k",
+ MODEL_TENSOR.TIME_MIX_LERP_V: "blk.{bid}.time_mix_lerp_v",
+ MODEL_TENSOR.TIME_MIX_LERP_R: "blk.{bid}.time_mix_lerp_r",
+ MODEL_TENSOR.TIME_MIX_LERP_G: "blk.{bid}.time_mix_lerp_g",
+ MODEL_TENSOR.TIME_MIX_LERP_FUSED: "blk.{bid}.time_mix_lerp_fused",
+ MODEL_TENSOR.TIME_MIX_LERP_W: "blk.{bid}.time_mix_lerp_w",
+ MODEL_TENSOR.TIME_MIX_FIRST: "blk.{bid}.time_mix_first",
+ MODEL_TENSOR.TIME_MIX_DECAY: "blk.{bid}.time_mix_decay",
+ MODEL_TENSOR.TIME_MIX_DECAY_W1: "blk.{bid}.time_mix_decay_w1",
+ MODEL_TENSOR.TIME_MIX_DECAY_W2: "blk.{bid}.time_mix_decay_w2",
+ MODEL_TENSOR.TIME_MIX_KEY: "blk.{bid}.time_mix_key",
+ MODEL_TENSOR.TIME_MIX_VALUE: "blk.{bid}.time_mix_value",
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE: "blk.{bid}.time_mix_receptance",
+ MODEL_TENSOR.TIME_MIX_GATE: "blk.{bid}.time_mix_gate",
+ MODEL_TENSOR.TIME_MIX_LN: "blk.{bid}.time_mix_ln",
+ MODEL_TENSOR.TIME_MIX_OUTPUT: "blk.{bid}.time_mix_output",
+ MODEL_TENSOR.CHANNEL_MIX_LERP_K: "blk.{bid}.channel_mix_lerp_k",
+ MODEL_TENSOR.CHANNEL_MIX_LERP_R: "blk.{bid}.channel_mix_lerp_r",
+ MODEL_TENSOR.CHANNEL_MIX_KEY: "blk.{bid}.channel_mix_key",
+ MODEL_TENSOR.CHANNEL_MIX_RECEPTANCE: "blk.{bid}.channel_mix_receptance",
+ MODEL_TENSOR.CHANNEL_MIX_VALUE: "blk.{bid}.channel_mix_value",
+ MODEL_TENSOR.ATTN_Q_A: "blk.{bid}.attn_q_a",
+ MODEL_TENSOR.ATTN_Q_B: "blk.{bid}.attn_q_b",
+ MODEL_TENSOR.ATTN_KV_A_MQA: "blk.{bid}.attn_kv_a_mqa",
+ MODEL_TENSOR.ATTN_KV_B: "blk.{bid}.attn_kv_b",
+ MODEL_TENSOR.ATTN_K_B: "blk.{bid}.attn_k_b",
+ MODEL_TENSOR.ATTN_V_B: "blk.{bid}.attn_v_b",
+ MODEL_TENSOR.ATTN_Q_A_NORM: "blk.{bid}.attn_q_a_norm",
+ MODEL_TENSOR.ATTN_KV_A_NORM: "blk.{bid}.attn_kv_a_norm",
+ MODEL_TENSOR.ATTN_SUB_NORM: "blk.{bid}.attn_sub_norm",
+ MODEL_TENSOR.FFN_SUB_NORM: "blk.{bid}.ffn_sub_norm",
+ MODEL_TENSOR.DEC_ATTN_NORM: "dec.blk.{bid}.attn_norm",
+ MODEL_TENSOR.DEC_ATTN_Q: "dec.blk.{bid}.attn_q",
+ MODEL_TENSOR.DEC_ATTN_K: "dec.blk.{bid}.attn_k",
+ MODEL_TENSOR.DEC_ATTN_V: "dec.blk.{bid}.attn_v",
+ MODEL_TENSOR.DEC_ATTN_OUT: "dec.blk.{bid}.attn_o",
+ MODEL_TENSOR.DEC_ATTN_REL_B: "dec.blk.{bid}.attn_rel_b",
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM: "dec.blk.{bid}.cross_attn_norm",
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q: "dec.blk.{bid}.cross_attn_q",
+ MODEL_TENSOR.DEC_CROSS_ATTN_K: "dec.blk.{bid}.cross_attn_k",
+ MODEL_TENSOR.DEC_CROSS_ATTN_V: "dec.blk.{bid}.cross_attn_v",
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT: "dec.blk.{bid}.cross_attn_o",
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B: "dec.blk.{bid}.cross_attn_rel_b",
+ MODEL_TENSOR.DEC_FFN_NORM: "dec.blk.{bid}.ffn_norm",
+ MODEL_TENSOR.DEC_FFN_GATE: "dec.blk.{bid}.ffn_gate",
+ MODEL_TENSOR.DEC_FFN_DOWN: "dec.blk.{bid}.ffn_down",
+ MODEL_TENSOR.DEC_FFN_UP: "dec.blk.{bid}.ffn_up",
+ MODEL_TENSOR.DEC_OUTPUT_NORM: "dec.output_norm",
+ MODEL_TENSOR.ENC_ATTN_NORM: "enc.blk.{bid}.attn_norm",
+ MODEL_TENSOR.ENC_ATTN_Q: "enc.blk.{bid}.attn_q",
+ MODEL_TENSOR.ENC_ATTN_K: "enc.blk.{bid}.attn_k",
+ MODEL_TENSOR.ENC_ATTN_V: "enc.blk.{bid}.attn_v",
+ MODEL_TENSOR.ENC_ATTN_OUT: "enc.blk.{bid}.attn_o",
+ MODEL_TENSOR.ENC_ATTN_REL_B: "enc.blk.{bid}.attn_rel_b",
+ MODEL_TENSOR.ENC_FFN_NORM: "enc.blk.{bid}.ffn_norm",
+ MODEL_TENSOR.ENC_FFN_GATE: "enc.blk.{bid}.ffn_gate",
+ MODEL_TENSOR.ENC_FFN_DOWN: "enc.blk.{bid}.ffn_down",
+ MODEL_TENSOR.ENC_FFN_UP: "enc.blk.{bid}.ffn_up",
+ MODEL_TENSOR.ENC_OUTPUT_NORM: "enc.output_norm",
+ MODEL_TENSOR.CLS: "cls",
+ MODEL_TENSOR.CLS_OUT: "cls.output",
+ MODEL_TENSOR.CONV1D: "conv1d",
+ MODEL_TENSOR.CONVNEXT_DW: "convnext.{bid}.dw",
+ MODEL_TENSOR.CONVNEXT_NORM: "convnext.{bid}.norm",
+ MODEL_TENSOR.CONVNEXT_PW1: "convnext.{bid}.pw1",
+ MODEL_TENSOR.CONVNEXT_PW2: "convnext.{bid}.pw2",
+ MODEL_TENSOR.CONVNEXT_GAMMA: "convnext.{bid}.gamma",
+ MODEL_TENSOR.POSNET_CONV1: "posnet.{bid}.conv1",
+ MODEL_TENSOR.POSNET_CONV2: "posnet.{bid}.conv2",
+ MODEL_TENSOR.POSNET_NORM: "posnet.{bid}.norm",
+ MODEL_TENSOR.POSNET_NORM1: "posnet.{bid}.norm1",
+ MODEL_TENSOR.POSNET_NORM2: "posnet.{bid}.norm2",
+ MODEL_TENSOR.POSNET_ATTN_NORM: "posnet.{bid}.attn_norm",
+ MODEL_TENSOR.POSNET_ATTN_Q: "posnet.{bid}.attn_q",
+ MODEL_TENSOR.POSNET_ATTN_K: "posnet.{bid}.attn_k",
+ MODEL_TENSOR.POSNET_ATTN_V: "posnet.{bid}.attn_v",
+ MODEL_TENSOR.POSNET_ATTN_OUT: "posnet.{bid}.attn_output",
+ # vision
+ MODEL_TENSOR.V_MMPROJ: "mm.{bid}",
+ MODEL_TENSOR.V_MMPROJ_FC: "mm.model.fc",
+ MODEL_TENSOR.V_MMPROJ_MLP: "mm.model.mlp.{bid}",
+ MODEL_TENSOR.V_MMPROJ_PEG: "mm.model.peg.{bid}",
+ MODEL_TENSOR.V_ENC_EMBD_CLS: "v.class_embd",
+ MODEL_TENSOR.V_ENC_EMBD_PATCH: "v.patch_embd",
+ MODEL_TENSOR.V_ENC_EMBD_POS: "v.position_embd",
+ MODEL_TENSOR.V_ENC_ATTN_Q: "v.blk.{bid}.attn_q",
+ MODEL_TENSOR.V_ENC_ATTN_Q_NORM: "v.blk.{bid}.attn_q_norm",
+ MODEL_TENSOR.V_ENC_ATTN_K: "v.blk.{bid}.attn_k",
+ MODEL_TENSOR.V_ENC_ATTN_K_NORM: "v.blk.{bid}.attn_k_norm",
+ MODEL_TENSOR.V_ENC_ATTN_V: "v.blk.{bid}.attn_v",
+ MODEL_TENSOR.V_ENC_INPUT_NORM: "v.blk.{bid}.ln1",
+ MODEL_TENSOR.V_ENC_ATTN_O: "v.blk.{bid}.attn_out",
+ MODEL_TENSOR.V_ENC_ATTN_O_NORM: "v.blk.{bid}.attn_out_norm",
+ MODEL_TENSOR.V_ENC_POST_ATTN_NORM: "v.blk.{bid}.ln2",
+ MODEL_TENSOR.V_ENC_FFN_UP: "v.blk.{bid}.ffn_up",
+ MODEL_TENSOR.V_ENC_FFN_GATE: "v.blk.{bid}.ffn_gate",
+ MODEL_TENSOR.V_ENC_FFN_DOWN: "v.blk.{bid}.ffn_down",
+ MODEL_TENSOR.V_LAYER_SCALE_1: "v.blk.{bid}.ls1",
+ MODEL_TENSOR.V_LAYER_SCALE_2: "v.blk.{bid}.ls2",
+ MODEL_TENSOR.V_PRE_NORM: "v.pre_ln",
+ MODEL_TENSOR.V_POST_NORM: "v.post_ln",
+ MODEL_TENSOR.V_MM_INP_PROJ: "mm.input_projection",
+ MODEL_TENSOR.V_MM_INP_NORM: "mm.input_norm",
+ MODEL_TENSOR.V_MM_SOFT_EMB_NORM: "mm.soft_emb_norm",
+ MODEL_TENSOR.V_RESMPL_POS_EMBD_K: "resampler.pos_embd_k",
+ MODEL_TENSOR.V_RESMPL_ATTN_Q: "resampler.attn.q",
+ MODEL_TENSOR.V_RESMPL_ATTN_K: "resampler.attn.k",
+ MODEL_TENSOR.V_RESMPL_ATTN_V: "resampler.attn.v",
+ MODEL_TENSOR.V_RESMPL_ATTN_OUT: "resampler.attn.out",
+ MODEL_TENSOR.V_RESMPL_KV: "resampler.kv",
+ MODEL_TENSOR.V_RESMPL_KV_NORM: "resampler.ln_kv",
+ MODEL_TENSOR.V_RESMPL_POST_NORM: "resampler.ln_post",
+ MODEL_TENSOR.V_RESMPL_Q_NORM: "resampler.ln_q",
+ MODEL_TENSOR.V_RESMPL_PROJ: "resampler.proj",
+ MODEL_TENSOR.V_RESMPL_QUERY: "resampler.query",
+ MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK: "v.token_embd.img_break", # pixtral
+ MODEL_TENSOR.V_MM_PATCH_MERGER: "mm.patch_merger", # mistral small 3.1
+ # audio (mtmd)
+ MODEL_TENSOR.A_ENC_EMBD_POS: "a.position_embd",
+ MODEL_TENSOR.A_ENC_CONV1D: "a.conv1d.{bid}",
+ MODEL_TENSOR.A_PRE_NORM: "a.pre_ln",
+ MODEL_TENSOR.A_POST_NORM: "a.post_ln",
+ MODEL_TENSOR.A_ENC_ATTN_Q: "a.blk.{bid}.attn_q",
+ MODEL_TENSOR.A_ENC_ATTN_K: "a.blk.{bid}.attn_k",
+ MODEL_TENSOR.A_ENC_ATTN_V: "a.blk.{bid}.attn_v",
+ MODEL_TENSOR.A_ENC_INPUT_NORM: "a.blk.{bid}.ln1",
+ MODEL_TENSOR.A_ENC_OUTPUT: "a.blk.{bid}.attn_out",
+ MODEL_TENSOR.A_ENC_OUTPUT_NORM: "a.blk.{bid}.ln2",
+ MODEL_TENSOR.A_ENC_FFN_UP: "a.blk.{bid}.ffn_up",
+ MODEL_TENSOR.A_ENC_FFN_GATE: "a.blk.{bid}.ffn_gate",
+ MODEL_TENSOR.A_ENC_FFN_DOWN: "a.blk.{bid}.ffn_down",
+ MODEL_TENSOR.A_MMPROJ: "mm.a.mlp.{bid}",
+ MODEL_TENSOR.A_MMPROJ_FC: "mm.a.fc",
+ MODEL_TENSOR.A_MM_NORM_PRE: "mm.a.norm_pre",
+ MODEL_TENSOR.A_MM_NORM_MID: "mm.a.norm_mid",
+}
+
+MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
+ MODEL_ARCH.MMPROJ: [
+ MODEL_TENSOR.V_MMPROJ,
+ MODEL_TENSOR.V_MMPROJ_FC,
+ MODEL_TENSOR.V_MMPROJ_MLP,
+ MODEL_TENSOR.V_MMPROJ_PEG,
+ MODEL_TENSOR.V_ENC_EMBD_CLS,
+ MODEL_TENSOR.V_ENC_EMBD_PATCH,
+ MODEL_TENSOR.V_ENC_EMBD_POS,
+ MODEL_TENSOR.V_ENC_INPUT_NORM,
+ MODEL_TENSOR.V_ENC_ATTN_Q,
+ MODEL_TENSOR.V_ENC_ATTN_Q_NORM,
+ MODEL_TENSOR.V_ENC_ATTN_K,
+ MODEL_TENSOR.V_ENC_ATTN_K_NORM,
+ MODEL_TENSOR.V_ENC_ATTN_V,
+ MODEL_TENSOR.V_ENC_ATTN_O,
+ MODEL_TENSOR.V_ENC_ATTN_O_NORM,
+ MODEL_TENSOR.V_ENC_POST_ATTN_NORM,
+ MODEL_TENSOR.V_ENC_FFN_UP,
+ MODEL_TENSOR.V_ENC_FFN_GATE,
+ MODEL_TENSOR.V_ENC_FFN_DOWN,
+ MODEL_TENSOR.V_LAYER_SCALE_1,
+ MODEL_TENSOR.V_LAYER_SCALE_2,
+ MODEL_TENSOR.V_PRE_NORM,
+ MODEL_TENSOR.V_POST_NORM,
+ MODEL_TENSOR.V_MM_INP_PROJ,
+ MODEL_TENSOR.V_MM_INP_NORM,
+ MODEL_TENSOR.V_MM_SOFT_EMB_NORM,
+ MODEL_TENSOR.V_RESMPL_POS_EMBD_K,
+ MODEL_TENSOR.V_RESMPL_ATTN_Q,
+ MODEL_TENSOR.V_RESMPL_ATTN_K,
+ MODEL_TENSOR.V_RESMPL_ATTN_V,
+ MODEL_TENSOR.V_RESMPL_ATTN_OUT,
+ MODEL_TENSOR.V_RESMPL_KV,
+ MODEL_TENSOR.V_RESMPL_KV_NORM,
+ MODEL_TENSOR.V_RESMPL_POST_NORM,
+ MODEL_TENSOR.V_RESMPL_Q_NORM,
+ MODEL_TENSOR.V_RESMPL_PROJ,
+ MODEL_TENSOR.V_RESMPL_QUERY,
+ MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK,
+ MODEL_TENSOR.V_MM_PATCH_MERGER,
+ # audio
+ MODEL_TENSOR.A_ENC_EMBD_POS,
+ MODEL_TENSOR.A_ENC_CONV1D,
+ MODEL_TENSOR.A_PRE_NORM,
+ MODEL_TENSOR.A_POST_NORM,
+ MODEL_TENSOR.A_ENC_ATTN_Q,
+ MODEL_TENSOR.A_ENC_ATTN_K,
+ MODEL_TENSOR.A_ENC_ATTN_V,
+ MODEL_TENSOR.A_ENC_INPUT_NORM,
+ MODEL_TENSOR.A_ENC_OUTPUT,
+ MODEL_TENSOR.A_ENC_OUTPUT_NORM,
+ MODEL_TENSOR.A_ENC_FFN_UP,
+ MODEL_TENSOR.A_ENC_FFN_GATE,
+ MODEL_TENSOR.A_ENC_FFN_DOWN,
+ MODEL_TENSOR.A_MMPROJ,
+ MODEL_TENSOR.A_MMPROJ_FC,
+ MODEL_TENSOR.A_MM_NORM_PRE,
+ MODEL_TENSOR.A_MM_NORM_MID,
+ ],
+ MODEL_ARCH.LLAMA: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.LLAMA4: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
+ MODEL_ARCH.DECI: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.GROK: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.LAYER_OUT_NORM,
+ ],
+ MODEL_ARCH.GPTNEOX: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.FALCON: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_NORM_2,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.BAICHUAN: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.STARCODER: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.BERT: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.TOKEN_TYPES,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.LAYER_OUT_NORM,
+ MODEL_TENSOR.CLS,
+ MODEL_TENSOR.CLS_OUT,
+ ],
+ MODEL_ARCH.NOMIC_BERT: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.TOKEN_TYPES,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.LAYER_OUT_NORM,
+ ],
+ MODEL_ARCH.NOMIC_BERT_MOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.TOKEN_TYPES,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.LAYER_OUT_NORM,
+ ],
+ MODEL_ARCH.NEO_BERT: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ENC_OUTPUT_NORM,
+ MODEL_TENSOR.CLS,
+ MODEL_TENSOR.CLS_OUT,
+ ],
+ MODEL_ARCH.JINA_BERT_V2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.TOKEN_TYPES,
+ MODEL_TENSOR.ATTN_NORM_2,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.LAYER_OUT_NORM,
+ MODEL_TENSOR.CLS,
+ ],
+ MODEL_ARCH.MPT: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_ACT,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.POS_EMBD,
+ ],
+ MODEL_ARCH.GPTJ: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.REFACT: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.BLOOM: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.STABLELM: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K_NORM,
+ ],
+ MODEL_ARCH.QWEN: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.QWEN2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.QWEN2VL: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.QWEN2MOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
+ MODEL_ARCH.QWEN3: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.QWEN3MOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.PLAMO: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.GPT2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.PHI2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.PHI3: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FACTORS_LONG,
+ MODEL_TENSOR.ROPE_FACTORS_SHORT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.PHIMOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FACTORS_LONG,
+ MODEL_TENSOR.ROPE_FACTORS_SHORT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.CODESHELL: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.POS_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.ORION: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.INTERNLM2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.MINICPM: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ROPE_FACTORS_LONG,
+ MODEL_TENSOR.ROPE_FACTORS_SHORT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.MINICPM3: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FACTORS_LONG,
+ MODEL_TENSOR.ROPE_FACTORS_SHORT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q_A,
+ MODEL_TENSOR.ATTN_Q_B,
+ MODEL_TENSOR.ATTN_KV_A_MQA,
+ MODEL_TENSOR.ATTN_KV_B,
+ MODEL_TENSOR.ATTN_Q_A_NORM,
+ MODEL_TENSOR.ATTN_KV_A_NORM,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.GEMMA: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_NORM,
+ ],
+ MODEL_ARCH.GEMMA2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_POST_NORM,
+ MODEL_TENSOR.FFN_PRE_NORM,
+ MODEL_TENSOR.FFN_POST_NORM,
+ ],
+ MODEL_ARCH.GEMMA3: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_POST_NORM,
+ MODEL_TENSOR.FFN_PRE_NORM,
+ MODEL_TENSOR.FFN_POST_NORM,
+ ],
+ MODEL_ARCH.STARCODER2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.RWKV6: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_NORM_2,
+ MODEL_TENSOR.TIME_MIX_W1,
+ MODEL_TENSOR.TIME_MIX_W2,
+ MODEL_TENSOR.TIME_MIX_LERP_X,
+ MODEL_TENSOR.TIME_MIX_LERP_K,
+ MODEL_TENSOR.TIME_MIX_LERP_V,
+ MODEL_TENSOR.TIME_MIX_LERP_R,
+ MODEL_TENSOR.TIME_MIX_LERP_G,
+ MODEL_TENSOR.TIME_MIX_LERP_W,
+ MODEL_TENSOR.TIME_MIX_LERP_FUSED,
+ MODEL_TENSOR.TIME_MIX_FIRST,
+ MODEL_TENSOR.TIME_MIX_DECAY,
+ MODEL_TENSOR.TIME_MIX_DECAY_W1,
+ MODEL_TENSOR.TIME_MIX_DECAY_W2,
+ MODEL_TENSOR.TIME_MIX_KEY,
+ MODEL_TENSOR.TIME_MIX_VALUE,
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE,
+ MODEL_TENSOR.TIME_MIX_GATE,
+ MODEL_TENSOR.TIME_MIX_LN,
+ MODEL_TENSOR.TIME_MIX_OUTPUT,
+ MODEL_TENSOR.CHANNEL_MIX_LERP_K,
+ MODEL_TENSOR.CHANNEL_MIX_LERP_R,
+ MODEL_TENSOR.CHANNEL_MIX_KEY,
+ MODEL_TENSOR.CHANNEL_MIX_RECEPTANCE,
+ MODEL_TENSOR.CHANNEL_MIX_VALUE,
+ ],
+ MODEL_ARCH.RWKV6QWEN2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.TIME_MIX_W1,
+ MODEL_TENSOR.TIME_MIX_W2,
+ MODEL_TENSOR.TIME_MIX_LERP_X,
+ MODEL_TENSOR.TIME_MIX_LERP_K,
+ MODEL_TENSOR.TIME_MIX_LERP_V,
+ MODEL_TENSOR.TIME_MIX_LERP_R,
+ MODEL_TENSOR.TIME_MIX_LERP_G,
+ MODEL_TENSOR.TIME_MIX_LERP_W,
+ MODEL_TENSOR.TIME_MIX_LERP_FUSED,
+ MODEL_TENSOR.TIME_MIX_FIRST,
+ MODEL_TENSOR.TIME_MIX_DECAY,
+ MODEL_TENSOR.TIME_MIX_DECAY_W1,
+ MODEL_TENSOR.TIME_MIX_DECAY_W2,
+ MODEL_TENSOR.TIME_MIX_KEY,
+ MODEL_TENSOR.TIME_MIX_VALUE,
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE,
+ MODEL_TENSOR.TIME_MIX_GATE,
+ MODEL_TENSOR.TIME_MIX_LN,
+ MODEL_TENSOR.TIME_MIX_OUTPUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.RWKV7: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_NORM_2,
+ MODEL_TENSOR.TIME_MIX_LERP_FUSED,
+ MODEL_TENSOR.TIME_MIX_W0,
+ MODEL_TENSOR.TIME_MIX_W1,
+ MODEL_TENSOR.TIME_MIX_W2,
+ MODEL_TENSOR.TIME_MIX_A0,
+ MODEL_TENSOR.TIME_MIX_A1,
+ MODEL_TENSOR.TIME_MIX_A2,
+ MODEL_TENSOR.TIME_MIX_V0,
+ MODEL_TENSOR.TIME_MIX_V1,
+ MODEL_TENSOR.TIME_MIX_V2,
+ MODEL_TENSOR.TIME_MIX_G1,
+ MODEL_TENSOR.TIME_MIX_G2,
+ MODEL_TENSOR.TIME_MIX_K_K,
+ MODEL_TENSOR.TIME_MIX_K_A,
+ MODEL_TENSOR.TIME_MIX_R_K,
+ MODEL_TENSOR.TIME_MIX_KEY,
+ MODEL_TENSOR.TIME_MIX_VALUE,
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE,
+ MODEL_TENSOR.TIME_MIX_LN,
+ MODEL_TENSOR.TIME_MIX_OUTPUT,
+ MODEL_TENSOR.CHANNEL_MIX_LERP_K,
+ MODEL_TENSOR.CHANNEL_MIX_KEY,
+ MODEL_TENSOR.CHANNEL_MIX_VALUE,
+ ],
+ MODEL_ARCH.ARWKV7: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.TIME_MIX_LERP_FUSED,
+ MODEL_TENSOR.TIME_MIX_W0,
+ MODEL_TENSOR.TIME_MIX_W1,
+ MODEL_TENSOR.TIME_MIX_W2,
+ MODEL_TENSOR.TIME_MIX_A0,
+ MODEL_TENSOR.TIME_MIX_A1,
+ MODEL_TENSOR.TIME_MIX_A2,
+ MODEL_TENSOR.TIME_MIX_V0,
+ MODEL_TENSOR.TIME_MIX_V1,
+ MODEL_TENSOR.TIME_MIX_V2,
+ MODEL_TENSOR.TIME_MIX_G1,
+ MODEL_TENSOR.TIME_MIX_G2,
+ MODEL_TENSOR.TIME_MIX_K_K,
+ MODEL_TENSOR.TIME_MIX_K_A,
+ MODEL_TENSOR.TIME_MIX_R_K,
+ MODEL_TENSOR.TIME_MIX_KEY,
+ MODEL_TENSOR.TIME_MIX_VALUE,
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE,
+ MODEL_TENSOR.TIME_MIX_LN,
+ MODEL_TENSOR.TIME_MIX_OUTPUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.MAMBA: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.SSM_IN,
+ MODEL_TENSOR.SSM_CONV1D,
+ MODEL_TENSOR.SSM_X,
+ MODEL_TENSOR.SSM_DT,
+ MODEL_TENSOR.SSM_A,
+ MODEL_TENSOR.SSM_D,
+ MODEL_TENSOR.SSM_OUT,
+ ],
+ MODEL_ARCH.XVERSE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.COMMAND_R: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ ],
+ MODEL_ARCH.COHERE2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.DBRX: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_OUT_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.OLMO: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.OLMO2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_POST_NORM,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.FFN_POST_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.OLMOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ ],
+ MODEL_ARCH.OPENELM: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.ARCTIC: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_NORM_EXP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ ],
+ MODEL_ARCH.DEEPSEEK: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
+ MODEL_ARCH.DEEPSEEK2: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_A,
+ MODEL_TENSOR.ATTN_Q_B,
+ MODEL_TENSOR.ATTN_KV_A_MQA,
+ MODEL_TENSOR.ATTN_KV_B,
+ MODEL_TENSOR.ATTN_K_B,
+ MODEL_TENSOR.ATTN_V_B,
+ MODEL_TENSOR.ATTN_Q_A_NORM,
+ MODEL_TENSOR.ATTN_KV_A_NORM,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ MODEL_TENSOR.FFN_EXP_PROBS_B,
+ ],
+ MODEL_ARCH.PLM: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_KV_A_MQA,
+ MODEL_TENSOR.ATTN_KV_A_NORM,
+ MODEL_TENSOR.ATTN_KV_B,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_DOWN,
+ ],
+ MODEL_ARCH.CHATGLM : [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.GLM4 : [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_POST_NORM,
+ MODEL_TENSOR.FFN_POST_NORM,
+ ],
+ MODEL_ARCH.BITNET: [
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.ATTN_SUB_NORM,
+ MODEL_TENSOR.FFN_SUB_NORM,
+ ],
+ MODEL_ARCH.T5: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.DEC_ATTN_NORM,
+ MODEL_TENSOR.DEC_ATTN_Q,
+ MODEL_TENSOR.DEC_ATTN_K,
+ MODEL_TENSOR.DEC_ATTN_V,
+ MODEL_TENSOR.DEC_ATTN_OUT,
+ MODEL_TENSOR.DEC_ATTN_REL_B,
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM,
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q,
+ MODEL_TENSOR.DEC_CROSS_ATTN_K,
+ MODEL_TENSOR.DEC_CROSS_ATTN_V,
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT,
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B,
+ MODEL_TENSOR.DEC_FFN_NORM,
+ MODEL_TENSOR.DEC_FFN_GATE,
+ MODEL_TENSOR.DEC_FFN_DOWN,
+ MODEL_TENSOR.DEC_FFN_UP,
+ MODEL_TENSOR.DEC_OUTPUT_NORM,
+ MODEL_TENSOR.ENC_ATTN_NORM,
+ MODEL_TENSOR.ENC_ATTN_Q,
+ MODEL_TENSOR.ENC_ATTN_K,
+ MODEL_TENSOR.ENC_ATTN_V,
+ MODEL_TENSOR.ENC_ATTN_OUT,
+ MODEL_TENSOR.ENC_ATTN_REL_B,
+ MODEL_TENSOR.ENC_FFN_NORM,
+ MODEL_TENSOR.ENC_FFN_GATE,
+ MODEL_TENSOR.ENC_FFN_DOWN,
+ MODEL_TENSOR.ENC_FFN_UP,
+ MODEL_TENSOR.ENC_OUTPUT_NORM,
+ ],
+ MODEL_ARCH.T5ENCODER: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ENC_ATTN_NORM,
+ MODEL_TENSOR.ENC_ATTN_Q,
+ MODEL_TENSOR.ENC_ATTN_K,
+ MODEL_TENSOR.ENC_ATTN_V,
+ MODEL_TENSOR.ENC_ATTN_OUT,
+ MODEL_TENSOR.ENC_ATTN_REL_B,
+ MODEL_TENSOR.ENC_FFN_NORM,
+ MODEL_TENSOR.ENC_FFN_GATE,
+ MODEL_TENSOR.ENC_FFN_DOWN,
+ MODEL_TENSOR.ENC_FFN_UP,
+ MODEL_TENSOR.ENC_OUTPUT_NORM,
+ ],
+ MODEL_ARCH.JAIS: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_QKV,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.NEMOTRON: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.EXAONE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.GRANITE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.GRANITE_MOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ ],
+ MODEL_ARCH.CHAMELEON: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ MODEL_ARCH.WAVTOKENIZER_DEC: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.TOKEN_EMBD_NORM,
+ MODEL_TENSOR.CONV1D,
+ MODEL_TENSOR.CONVNEXT_DW,
+ MODEL_TENSOR.CONVNEXT_NORM,
+ MODEL_TENSOR.CONVNEXT_PW1,
+ MODEL_TENSOR.CONVNEXT_PW2,
+ MODEL_TENSOR.CONVNEXT_GAMMA,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.POSNET_CONV1,
+ MODEL_TENSOR.POSNET_CONV2,
+ MODEL_TENSOR.POSNET_NORM,
+ MODEL_TENSOR.POSNET_NORM1,
+ MODEL_TENSOR.POSNET_NORM2,
+ MODEL_TENSOR.POSNET_ATTN_NORM,
+ MODEL_TENSOR.POSNET_ATTN_Q,
+ MODEL_TENSOR.POSNET_ATTN_K,
+ MODEL_TENSOR.POSNET_ATTN_V,
+ MODEL_TENSOR.POSNET_ATTN_OUT,
+ ],
+ MODEL_ARCH.BAILINGMOE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
+ MODEL_ARCH.DOTS1: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_Q_NORM,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_K_NORM,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.FFN_EXP_PROBS_B,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_GATE,
+ MODEL_TENSOR.FFN_GATE_EXP,
+ MODEL_TENSOR.FFN_GATE_INP,
+ MODEL_TENSOR.FFN_GATE_SHEXP,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_DOWN_EXP,
+ MODEL_TENSOR.FFN_DOWN_SHEXP,
+ MODEL_TENSOR.FFN_UP,
+ MODEL_TENSOR.FFN_UP_EXP,
+ MODEL_TENSOR.FFN_UP_SHEXP,
+ ],
+ MODEL_ARCH.ARCEE: [
+ MODEL_TENSOR.TOKEN_EMBD,
+ MODEL_TENSOR.OUTPUT_NORM,
+ MODEL_TENSOR.OUTPUT,
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_NORM,
+ MODEL_TENSOR.ATTN_Q,
+ MODEL_TENSOR.ATTN_K,
+ MODEL_TENSOR.ATTN_V,
+ MODEL_TENSOR.ATTN_OUT,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ MODEL_TENSOR.FFN_NORM,
+ MODEL_TENSOR.FFN_DOWN,
+ MODEL_TENSOR.FFN_UP,
+ ],
+ # TODO
+}
+
+# tensors that will not be serialized
+MODEL_TENSOR_SKIP: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
+ MODEL_ARCH.LLAMA: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.DECI: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.BAICHUAN: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.QWEN: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.CODESHELL: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.ORION: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.STARCODER2: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.XVERSE: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.DEEPSEEK: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.DEEPSEEK2: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.CHATGLM: [
+ MODEL_TENSOR.ROPE_FREQS,
+ ],
+ MODEL_ARCH.NEMOTRON: [
+ MODEL_TENSOR.ROPE_FREQS,
+ MODEL_TENSOR.ATTN_ROT_EMBD,
+ ],
+ MODEL_ARCH.BAILINGMOE: [
+ MODEL_TENSOR.ROPE_FREQS,
+ ],
+}
+
+#
+# types
+#
+
+
+class TokenType(IntEnum):
+ NORMAL = 1
+ UNKNOWN = 2
+ CONTROL = 3
+ USER_DEFINED = 4
+ UNUSED = 5
+ BYTE = 6
+
+
+class RopeScalingType(Enum):
+ NONE = 'none'
+ LINEAR = 'linear'
+ YARN = 'yarn'
+ LONGROPE = 'longrope'
+
+
+class PoolingType(IntEnum):
+ NONE = 0
+ MEAN = 1
+ CLS = 2
+ LAST = 3
+ RANK = 4
+
+
+class GGMLQuantizationType(IntEnum):
+ F32 = 0
+ F16 = 1
+ Q4_0 = 2
+ Q4_1 = 3
+ Q5_0 = 6
+ Q5_1 = 7
+ Q8_0 = 8
+ Q8_1 = 9
+ Q2_K = 10
+ Q3_K = 11
+ Q4_K = 12
+ Q5_K = 13
+ Q6_K = 14
+ Q8_K = 15
+ IQ2_XXS = 16
+ IQ2_XS = 17
+ IQ3_XXS = 18
+ IQ1_S = 19
+ IQ4_NL = 20
+ IQ3_S = 21
+ IQ2_S = 22
+ IQ4_XS = 23
+ I8 = 24
+ I16 = 25
+ I32 = 26
+ I64 = 27
+ F64 = 28
+ IQ1_M = 29
+ BF16 = 30
+ TQ1_0 = 34
+ TQ2_0 = 35
+
+
+class ExpertGatingFuncType(IntEnum):
+ SOFTMAX = 1
+ SIGMOID = 2
+
+
+# TODO: add GGMLFileType from ggml_ftype in ggml.h
+
+
+# from llama_ftype in llama.h
+# ALL VALUES SHOULD BE THE SAME HERE AS THEY ARE OVER THERE.
+class LlamaFileType(IntEnum):
+ ALL_F32 = 0
+ MOSTLY_F16 = 1 # except 1d tensors
+ MOSTLY_Q4_0 = 2 # except 1d tensors
+ MOSTLY_Q4_1 = 3 # except 1d tensors
+ # MOSTLY_Q4_1_SOME_F16 = 4 # tok_embeddings.weight and output.weight are F16
+ # MOSTLY_Q4_2 = 5 # support has been removed
+ # MOSTLY_Q4_3 = 6 # support has been removed
+ MOSTLY_Q8_0 = 7 # except 1d tensors
+ MOSTLY_Q5_0 = 8 # except 1d tensors
+ MOSTLY_Q5_1 = 9 # except 1d tensors
+ MOSTLY_Q2_K = 10 # except 1d tensors
+ MOSTLY_Q3_K_S = 11 # except 1d tensors
+ MOSTLY_Q3_K_M = 12 # except 1d tensors
+ MOSTLY_Q3_K_L = 13 # except 1d tensors
+ MOSTLY_Q4_K_S = 14 # except 1d tensors
+ MOSTLY_Q4_K_M = 15 # except 1d tensors
+ MOSTLY_Q5_K_S = 16 # except 1d tensors
+ MOSTLY_Q5_K_M = 17 # except 1d tensors
+ MOSTLY_Q6_K = 18 # except 1d tensors
+ MOSTLY_IQ2_XXS = 19 # except 1d tensors
+ MOSTLY_IQ2_XS = 20 # except 1d tensors
+ MOSTLY_Q2_K_S = 21 # except 1d tensors
+ MOSTLY_IQ3_XS = 22 # except 1d tensors
+ MOSTLY_IQ3_XXS = 23 # except 1d tensors
+ MOSTLY_IQ1_S = 24 # except 1d tensors
+ MOSTLY_IQ4_NL = 25 # except 1d tensors
+ MOSTLY_IQ3_S = 26 # except 1d tensors
+ MOSTLY_IQ3_M = 27 # except 1d tensors
+ MOSTLY_IQ2_S = 28 # except 1d tensors
+ MOSTLY_IQ2_M = 29 # except 1d tensors
+ MOSTLY_IQ4_XS = 30 # except 1d tensors
+ MOSTLY_IQ1_M = 31 # except 1d tensors
+ MOSTLY_BF16 = 32 # except 1d tensors
+ # MOSTLY_Q4_0_4_4 = 33 # removed from gguf files, use Q4_0 and runtime repack
+ # MOSTLY_Q4_0_4_8 = 34 # removed from gguf files, use Q4_0 and runtime repack
+ # MOSTLY_Q4_0_8_8 = 35 # removed from gguf files, use Q4_0 and runtime repack
+ MOSTLY_TQ1_0 = 36 # except 1d tensors
+ MOSTLY_TQ2_0 = 37 # except 1d tensors
+
+ GUESSED = 1024 # not specified in the model file
+
+
+class GGUFEndian(IntEnum):
+ LITTLE = 0
+ BIG = 1
+
+
+class GGUFValueType(IntEnum):
+ UINT8 = 0
+ INT8 = 1
+ UINT16 = 2
+ INT16 = 3
+ UINT32 = 4
+ INT32 = 5
+ FLOAT32 = 6
+ BOOL = 7
+ STRING = 8
+ ARRAY = 9
+ UINT64 = 10
+ INT64 = 11
+ FLOAT64 = 12
+
+ @staticmethod
+ def get_type(val: Any) -> GGUFValueType:
+ if isinstance(val, (str, bytes, bytearray)):
+ return GGUFValueType.STRING
+ elif isinstance(val, list):
+ return GGUFValueType.ARRAY
+ elif isinstance(val, float):
+ return GGUFValueType.FLOAT32
+ elif isinstance(val, bool):
+ return GGUFValueType.BOOL
+ elif isinstance(val, int):
+ return GGUFValueType.INT32
+ # TODO: need help with 64-bit types in Python
+ else:
+ raise ValueError(f"Unknown type: {type(val)}")
+
+
+class VisionProjectorType:
+ GEMMA3 = "gemma3"
+ IDEFICS3 = "idefics3"
+ PIXTRAL = "pixtral"
+ LLAMA4 = "llama4"
+ QWEN2VL = "qwen2vl_merger"
+ QWEN25VL = "qwen2.5vl_merger"
+ ULTRAVOX = "ultravox"
+ INTERNVL = "internvl"
+ QWEN2A = "qwen2a" # audio
+ QWEN25O = "qwen2.5o" # omni
+
+
+# Items here are (block size, type size)
+QK_K = 256
+GGML_QUANT_SIZES: dict[GGMLQuantizationType, tuple[int, int]] = {
+ GGMLQuantizationType.F32: (1, 4),
+ GGMLQuantizationType.F16: (1, 2),
+ GGMLQuantizationType.Q4_0: (32, 2 + 16),
+ GGMLQuantizationType.Q4_1: (32, 2 + 2 + 16),
+ GGMLQuantizationType.Q5_0: (32, 2 + 4 + 16),
+ GGMLQuantizationType.Q5_1: (32, 2 + 2 + 4 + 16),
+ GGMLQuantizationType.Q8_0: (32, 2 + 32),
+ GGMLQuantizationType.Q8_1: (32, 4 + 4 + 32),
+ GGMLQuantizationType.Q2_K: (256, 2 + 2 + QK_K // 16 + QK_K // 4),
+ GGMLQuantizationType.Q3_K: (256, 2 + QK_K // 4 + QK_K // 8 + 12),
+ GGMLQuantizationType.Q4_K: (256, 2 + 2 + QK_K // 2 + 12),
+ GGMLQuantizationType.Q5_K: (256, 2 + 2 + QK_K // 2 + QK_K // 8 + 12),
+ GGMLQuantizationType.Q6_K: (256, 2 + QK_K // 2 + QK_K // 4 + QK_K // 16),
+ GGMLQuantizationType.Q8_K: (256, 4 + QK_K + QK_K // 8),
+ GGMLQuantizationType.IQ2_XXS: (256, 2 + QK_K // 4),
+ GGMLQuantizationType.IQ2_XS: (256, 2 + QK_K // 4 + QK_K // 32),
+ GGMLQuantizationType.IQ3_XXS: (256, 2 + QK_K // 4 + QK_K // 8),
+ GGMLQuantizationType.IQ1_S: (256, 2 + QK_K // 8 + QK_K // 16),
+ GGMLQuantizationType.IQ4_NL: (32, 2 + 16),
+ GGMLQuantizationType.IQ3_S: (256, 2 + QK_K // 4 + QK_K // 8 + QK_K // 32 + 4),
+ GGMLQuantizationType.IQ2_S: (256, 2 + QK_K // 4 + QK_K // 16),
+ GGMLQuantizationType.IQ4_XS: (256, 2 + 2 + QK_K // 2 + QK_K // 64),
+ GGMLQuantizationType.I8: (1, 1),
+ GGMLQuantizationType.I16: (1, 2),
+ GGMLQuantizationType.I32: (1, 4),
+ GGMLQuantizationType.I64: (1, 8),
+ GGMLQuantizationType.F64: (1, 8),
+ GGMLQuantizationType.IQ1_M: (256, QK_K // 8 + QK_K // 16 + QK_K // 32),
+ GGMLQuantizationType.BF16: (1, 2),
+ GGMLQuantizationType.TQ1_0: (256, 2 + 4 * 13),
+ GGMLQuantizationType.TQ2_0: (256, 2 + 64),
+}
+
+
+# Aliases for backward compatibility.
+
+# general
+KEY_GENERAL_ARCHITECTURE = Keys.General.ARCHITECTURE
+KEY_GENERAL_QUANTIZATION_VERSION = Keys.General.QUANTIZATION_VERSION
+KEY_GENERAL_ALIGNMENT = Keys.General.ALIGNMENT
+KEY_GENERAL_NAME = Keys.General.NAME
+KEY_GENERAL_AUTHOR = Keys.General.AUTHOR
+KEY_GENERAL_URL = Keys.General.URL
+KEY_GENERAL_DESCRIPTION = Keys.General.DESCRIPTION
+KEY_GENERAL_LICENSE = Keys.General.LICENSE
+KEY_GENERAL_SOURCE_URL = Keys.General.SOURCE_URL
+KEY_GENERAL_FILE_TYPE = Keys.General.FILE_TYPE
+
+# LLM
+KEY_VOCAB_SIZE = Keys.LLM.VOCAB_SIZE
+KEY_CONTEXT_LENGTH = Keys.LLM.CONTEXT_LENGTH
+KEY_EMBEDDING_LENGTH = Keys.LLM.EMBEDDING_LENGTH
+KEY_BLOCK_COUNT = Keys.LLM.BLOCK_COUNT
+KEY_FEED_FORWARD_LENGTH = Keys.LLM.FEED_FORWARD_LENGTH
+KEY_USE_PARALLEL_RESIDUAL = Keys.LLM.USE_PARALLEL_RESIDUAL
+KEY_TENSOR_DATA_LAYOUT = Keys.LLM.TENSOR_DATA_LAYOUT
+
+# attention
+KEY_ATTENTION_HEAD_COUNT = Keys.Attention.HEAD_COUNT
+KEY_ATTENTION_HEAD_COUNT_KV = Keys.Attention.HEAD_COUNT_KV
+KEY_ATTENTION_MAX_ALIBI_BIAS = Keys.Attention.MAX_ALIBI_BIAS
+KEY_ATTENTION_CLAMP_KQV = Keys.Attention.CLAMP_KQV
+KEY_ATTENTION_LAYERNORM_EPS = Keys.Attention.LAYERNORM_EPS
+KEY_ATTENTION_LAYERNORM_RMS_EPS = Keys.Attention.LAYERNORM_RMS_EPS
+
+# RoPE
+KEY_ROPE_DIMENSION_COUNT = Keys.Rope.DIMENSION_COUNT
+KEY_ROPE_FREQ_BASE = Keys.Rope.FREQ_BASE
+KEY_ROPE_SCALING_TYPE = Keys.Rope.SCALING_TYPE
+KEY_ROPE_SCALING_FACTOR = Keys.Rope.SCALING_FACTOR
+KEY_ROPE_SCALING_ORIG_CTX_LEN = Keys.Rope.SCALING_ORIG_CTX_LEN
+KEY_ROPE_SCALING_FINETUNED = Keys.Rope.SCALING_FINETUNED
+
+# SSM
+KEY_SSM_CONV_KERNEL = Keys.SSM.CONV_KERNEL
+KEY_SSM_INNER_SIZE = Keys.SSM.INNER_SIZE
+KEY_SSM_STATE_SIZE = Keys.SSM.STATE_SIZE
+KEY_SSM_TIME_STEP_RANK = Keys.SSM.TIME_STEP_RANK
+KEY_SSM_DT_B_C_RMS = Keys.SSM.DT_B_C_RMS
+
+# tokenization
+KEY_TOKENIZER_MODEL = Keys.Tokenizer.MODEL
+KEY_TOKENIZER_PRE = Keys.Tokenizer.PRE
+KEY_TOKENIZER_LIST = Keys.Tokenizer.LIST
+KEY_TOKENIZER_TOKEN_TYPE = Keys.Tokenizer.TOKEN_TYPE
+KEY_TOKENIZER_SCORES = Keys.Tokenizer.SCORES
+KEY_TOKENIZER_MERGES = Keys.Tokenizer.MERGES
+KEY_TOKENIZER_BOS_ID = Keys.Tokenizer.BOS_ID
+KEY_TOKENIZER_EOS_ID = Keys.Tokenizer.EOS_ID
+KEY_TOKENIZER_EOT_ID = Keys.Tokenizer.EOT_ID
+KEY_TOKENIZER_EOM_ID = Keys.Tokenizer.EOM_ID
+KEY_TOKENIZER_UNK_ID = Keys.Tokenizer.UNK_ID
+KEY_TOKENIZER_SEP_ID = Keys.Tokenizer.SEP_ID
+KEY_TOKENIZER_PAD_ID = Keys.Tokenizer.PAD_ID
+KEY_TOKENIZER_MASK_ID = Keys.Tokenizer.MASK_ID
+KEY_TOKENIZER_HF_JSON = Keys.Tokenizer.HF_JSON
+KEY_TOKENIZER_RWKV = Keys.Tokenizer.RWKV
+
+KEY_TOKENIZER_FIM_PRE_ID = Keys.Tokenizer.FIM_PRE_ID
+KEY_TOKENIZER_FIM_SUF_ID = Keys.Tokenizer.FIM_SUF_ID
+KEY_TOKENIZER_FIM_MID_ID = Keys.Tokenizer.FIM_MID_ID
+KEY_TOKENIZER_FIM_PAD_ID = Keys.Tokenizer.FIM_PAD_ID
+KEY_TOKENIZER_FIM_REP_ID = Keys.Tokenizer.FIM_REP_ID
+KEY_TOKENIZER_FIM_SEP_ID = Keys.Tokenizer.FIM_SEP_ID
+
+# deprecated
+KEY_TOKENIZER_PREFIX_ID = Keys.Tokenizer.PREFIX_ID
+KEY_TOKENIZER_SUFFIX_ID = Keys.Tokenizer.SUFFIX_ID
+KEY_TOKENIZER_MIDDLE_ID = Keys.Tokenizer.MIDDLE_ID
diff --git a/venv/lib/python3.10/site-packages/gguf/gguf.py b/venv/lib/python3.10/site-packages/gguf/gguf.py
new file mode 100644
index 0000000000000000000000000000000000000000..651a81eb828248728f854c85c1a437b52892f275
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/gguf.py
@@ -0,0 +1,15 @@
+# This file left for compatibility. If you want to use the GGUF API from Python
+# then don't import gguf/gguf.py directly. If you're looking for examples, see the
+# examples/ directory for gguf-py
+
+import importlib
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+# Compatibility for people trying to import gguf/gguf.py directly instead of as a package.
+importlib.invalidate_caches()
+import gguf # noqa: E402
+
+importlib.reload(gguf)
diff --git a/venv/lib/python3.10/site-packages/gguf/gguf_reader.py b/venv/lib/python3.10/site-packages/gguf/gguf_reader.py
new file mode 100644
index 0000000000000000000000000000000000000000..d87e8f72321b3f776cf214e117e21cdde9e1e18b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/gguf_reader.py
@@ -0,0 +1,367 @@
+#
+# GGUF file reading/modification support. For API usage information,
+# please see the files scripts/ for some fairly simple examples.
+#
+from __future__ import annotations
+
+import logging
+import os
+import sys
+from collections import OrderedDict
+from typing import Any, Literal, NamedTuple, TypeVar, Union
+
+import numpy as np
+import numpy.typing as npt
+
+from .quants import quant_shape_to_byte_shape
+
+if __name__ == "__main__":
+ from pathlib import Path
+
+ # Allow running file in package as a script.
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from gguf.constants import (
+ GGML_QUANT_SIZES,
+ GGUF_DEFAULT_ALIGNMENT,
+ GGUF_MAGIC,
+ GGUF_VERSION,
+ GGMLQuantizationType,
+ GGUFValueType,
+ GGUFEndian,
+)
+
+logger = logging.getLogger(__name__)
+
+READER_SUPPORTED_VERSIONS = [2, GGUF_VERSION]
+
+
+class ReaderField(NamedTuple):
+ # Offset to start of this field.
+ offset: int
+
+ # Name of the field (not necessarily from file data).
+ name: str
+
+ # Data parts. Some types have multiple components, such as strings
+ # that consist of a length followed by the string data.
+ parts: list[npt.NDArray[Any]] = []
+
+ # Indexes into parts that we can call the actual data. For example
+ # an array of strings will be populated with indexes to the actual
+ # string data.
+ data: list[int] = [-1]
+
+ types: list[GGUFValueType] = []
+
+ def contents(self, index_or_slice: int | slice = slice(None)) -> Any:
+ if self.types:
+ to_string = lambda x: str(x.tobytes(), encoding='utf-8') # noqa: E731
+ main_type = self.types[0]
+
+ if main_type == GGUFValueType.ARRAY:
+ sub_type = self.types[-1]
+
+ if sub_type == GGUFValueType.STRING:
+ indices = self.data[index_or_slice]
+
+ if isinstance(index_or_slice, int):
+ return to_string(self.parts[indices]) # type: ignore
+ else:
+ return [to_string(self.parts[idx]) for idx in indices] # type: ignore
+ else:
+ # FIXME: When/if _get_field_parts() support multi-dimensional arrays, this must do so too
+
+ # Check if it's unsafe to perform slice optimization on data
+ # if any(True for idx in self.data if len(self.parts[idx]) != 1):
+ # optim_slice = slice(None)
+ # else:
+ # optim_slice = index_or_slice
+ # index_or_slice = slice(None)
+
+ # if isinstance(optim_slice, int):
+ # return self.parts[self.data[optim_slice]].tolist()[0]
+ # else:
+ # return [pv for idx in self.data[optim_slice] for pv in self.parts[idx].tolist()][index_or_slice]
+
+ if isinstance(index_or_slice, int):
+ return self.parts[self.data[index_or_slice]].tolist()[0]
+ else:
+ return [pv for idx in self.data[index_or_slice] for pv in self.parts[idx].tolist()]
+
+ if main_type == GGUFValueType.STRING:
+ return to_string(self.parts[-1])
+ else:
+ return self.parts[-1].tolist()[0]
+
+ return None
+
+
+class ReaderTensor(NamedTuple):
+ name: str
+ tensor_type: GGMLQuantizationType
+ shape: npt.NDArray[np.uint32]
+ n_elements: int
+ n_bytes: int
+ data_offset: int
+ data: npt.NDArray[Any]
+ field: ReaderField
+
+
+class GGUFReader:
+ # I - same as host, S - swapped
+ byte_order: Literal['I', 'S'] = 'I'
+ alignment: int = GGUF_DEFAULT_ALIGNMENT
+ data_offset: int
+
+ # Note: Internal helper, API may change.
+ gguf_scalar_to_np: dict[GGUFValueType, type[np.generic]] = {
+ GGUFValueType.UINT8: np.uint8,
+ GGUFValueType.INT8: np.int8,
+ GGUFValueType.UINT16: np.uint16,
+ GGUFValueType.INT16: np.int16,
+ GGUFValueType.UINT32: np.uint32,
+ GGUFValueType.INT32: np.int32,
+ GGUFValueType.FLOAT32: np.float32,
+ GGUFValueType.UINT64: np.uint64,
+ GGUFValueType.INT64: np.int64,
+ GGUFValueType.FLOAT64: np.float64,
+ GGUFValueType.BOOL: np.bool_,
+ }
+
+ def __init__(self, path: os.PathLike[str] | str, mode: Literal['r', 'r+', 'c'] = 'r'):
+ self.data = np.memmap(path, mode = mode)
+ offs = 0
+
+ # Check for GGUF magic
+ if self._get(offs, np.uint32, override_order = '<')[0] != GGUF_MAGIC:
+ raise ValueError('GGUF magic invalid')
+ offs += 4
+
+ # Check GGUF version
+ temp_version = self._get(offs, np.uint32)
+ if temp_version[0] & 65535 == 0:
+ # If we get 0 here that means it's (probably) a GGUF file created for
+ # the opposite byte order of the machine this script is running on.
+ self.byte_order = 'S'
+ temp_version = temp_version.view(temp_version.dtype.newbyteorder(self.byte_order))
+ version = temp_version[0]
+ if version not in READER_SUPPORTED_VERSIONS:
+ raise ValueError(f'Sorry, file appears to be version {version} which we cannot handle')
+ if sys.byteorder == "little":
+ # Host is little endian
+ host_endian = GGUFEndian.LITTLE
+ swapped_endian = GGUFEndian.BIG
+ else:
+ # Sorry PDP or other weird systems that don't use BE or LE.
+ host_endian = GGUFEndian.BIG
+ swapped_endian = GGUFEndian.LITTLE
+ self.endianess = swapped_endian if self.byte_order == "S" else host_endian
+ self.fields: OrderedDict[str, ReaderField] = OrderedDict()
+ self.tensors: list[ReaderTensor] = []
+ offs += self._push_field(ReaderField(offs, 'GGUF.version', [temp_version], [0], [GGUFValueType.UINT32]))
+
+ # Check tensor count and kv count
+ temp_counts = self._get(offs, np.uint64, 2)
+ offs += self._push_field(ReaderField(offs, 'GGUF.tensor_count', [temp_counts[:1]], [0], [GGUFValueType.UINT64]))
+ offs += self._push_field(ReaderField(offs, 'GGUF.kv_count', [temp_counts[1:]], [0], [GGUFValueType.UINT64]))
+ tensor_count, kv_count = temp_counts
+ offs = self._build_fields(offs, kv_count)
+
+ # Build Tensor Info Fields
+ offs, tensors_fields = self._build_tensor_info(offs, tensor_count)
+ new_align = self.fields.get('general.alignment')
+ if new_align is not None:
+ if new_align.types != [GGUFValueType.UINT32]:
+ raise ValueError('Bad type for general.alignment field')
+ self.alignment = new_align.parts[-1][0]
+ padding = offs % self.alignment
+ if padding != 0:
+ offs += self.alignment - padding
+ self.data_offset = offs
+ self._build_tensors(offs, tensors_fields)
+
+ _DT = TypeVar('_DT', bound = npt.DTypeLike)
+
+ # Fetch a key/value metadata field by key.
+ def get_field(self, key: str) -> Union[ReaderField, None]:
+ return self.fields.get(key, None)
+
+ # Fetch a tensor from the list by index.
+ def get_tensor(self, idx: int) -> ReaderTensor:
+ return self.tensors[idx]
+
+ def _get(
+ self, offset: int, dtype: npt.DTypeLike, count: int = 1, override_order: None | Literal['I', 'S', '<'] = None,
+ ) -> npt.NDArray[Any]:
+ count = int(count)
+ itemsize = int(np.empty([], dtype = dtype).itemsize)
+ end_offs = offset + itemsize * count
+ arr = self.data[offset:end_offs].view(dtype=dtype)[:count]
+ return arr.view(arr.dtype.newbyteorder(self.byte_order if override_order is None else override_order))
+
+ def _push_field(self, field: ReaderField, skip_sum: bool = False) -> int:
+ if field.name in self.fields:
+ # TODO: add option to generate error on duplicate keys
+ # raise KeyError(f'Duplicate {field.name} already in list at offset {field.offset}')
+
+ logger.warning(f'Duplicate key {field.name} at offset {field.offset}')
+ self.fields[field.name + '_{}'.format(field.offset)] = field
+ else:
+ self.fields[field.name] = field
+ return 0 if skip_sum else sum(int(part.nbytes) for part in field.parts)
+
+ def _get_str(self, offset: int) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint8]]:
+ slen = self._get(offset, np.uint64)
+ return slen, self._get(offset + 8, np.uint8, slen[0])
+
+ def _get_field_parts(
+ self, orig_offs: int, raw_type: int,
+ ) -> tuple[int, list[npt.NDArray[Any]], list[int], list[GGUFValueType]]:
+ offs = orig_offs
+ types: list[GGUFValueType] = []
+ gtype = GGUFValueType(raw_type)
+ types.append(gtype)
+ # Handle strings.
+ if gtype == GGUFValueType.STRING:
+ sparts: list[npt.NDArray[Any]] = list(self._get_str(offs))
+ size = sum(int(part.nbytes) for part in sparts)
+ return size, sparts, [1], types
+ # Check if it's a simple scalar type.
+ nptype = self.gguf_scalar_to_np.get(gtype)
+ if nptype is not None:
+ val = self._get(offs, nptype)
+ return int(val.nbytes), [val], [0], types
+ # Handle arrays.
+ if gtype == GGUFValueType.ARRAY:
+ raw_itype = self._get(offs, np.uint32)
+ offs += int(raw_itype.nbytes)
+ alen = self._get(offs, np.uint64)
+ offs += int(alen.nbytes)
+ aparts: list[npt.NDArray[Any]] = [raw_itype, alen]
+ data_idxs: list[int] = []
+ # FIXME: Handle multi-dimensional arrays properly instead of flattening
+ for idx in range(alen[0]):
+ curr_size, curr_parts, curr_idxs, curr_types = self._get_field_parts(offs, raw_itype[0])
+ if idx == 0:
+ types += curr_types
+ idxs_offs = len(aparts)
+ aparts += curr_parts
+ data_idxs += (idx + idxs_offs for idx in curr_idxs)
+ offs += curr_size
+ return offs - orig_offs, aparts, data_idxs, types
+ # We can't deal with this one.
+ raise ValueError(f'Unknown/unhandled field type {gtype}')
+
+ def _get_tensor_info_field(self, orig_offs: int) -> ReaderField:
+ offs = orig_offs
+
+ # Get Tensor Name
+ name_len, name_data = self._get_str(offs)
+ offs += int(name_len.nbytes + name_data.nbytes)
+
+ # Get Tensor Dimensions Count
+ n_dims = self._get(offs, np.uint32)
+ offs += int(n_dims.nbytes)
+
+ # Get Tensor Dimension Array
+ dims = self._get(offs, np.uint64, n_dims[0])
+ offs += int(dims.nbytes)
+
+ # Get Tensor Encoding Scheme Type
+ raw_dtype = self._get(offs, np.uint32)
+ offs += int(raw_dtype.nbytes)
+
+ # Get Tensor Offset
+ offset_tensor = self._get(offs, np.uint64)
+ offs += int(offset_tensor.nbytes)
+
+ return ReaderField(
+ orig_offs,
+ str(bytes(name_data), encoding = 'utf-8'),
+ [name_len, name_data, n_dims, dims, raw_dtype, offset_tensor],
+ [1, 3, 4, 5],
+ )
+
+ def _build_fields(self, offs: int, count: int) -> int:
+ for _ in range(count):
+ orig_offs = offs
+ kv_klen, kv_kdata = self._get_str(offs)
+ offs += int(kv_klen.nbytes + kv_kdata.nbytes)
+ raw_kv_type = self._get(offs, np.uint32)
+ offs += int(raw_kv_type.nbytes)
+ parts: list[npt.NDArray[Any]] = [kv_klen, kv_kdata, raw_kv_type]
+ idxs_offs = len(parts)
+ field_size, field_parts, field_idxs, field_types = self._get_field_parts(offs, raw_kv_type[0])
+ parts += field_parts
+ self._push_field(ReaderField(
+ orig_offs,
+ str(bytes(kv_kdata), encoding = 'utf-8'),
+ parts,
+ [idx + idxs_offs for idx in field_idxs],
+ field_types,
+ ), skip_sum = True)
+ offs += field_size
+ return offs
+
+ def _build_tensor_info(self, offs: int, count: int) -> tuple[int, list[ReaderField]]:
+ tensor_fields = []
+ for _ in range(count):
+ field = self._get_tensor_info_field(offs)
+ offs += sum(int(part.nbytes) for part in field.parts)
+ tensor_fields.append(field)
+ return offs, tensor_fields
+
+ def _build_tensors(self, start_offs: int, fields: list[ReaderField]) -> None:
+ tensors = []
+ tensor_names = set() # keep track of name to prevent duplicated tensors
+ for field in fields:
+ _name_len, name_data, _n_dims, dims, raw_dtype, offset_tensor = field.parts
+ # check if there's any tensor having same name already in the list
+ tensor_name = str(bytes(name_data), encoding = 'utf-8')
+ if tensor_name in tensor_names:
+ raise ValueError(f'Found duplicated tensor with name {tensor_name}')
+ tensor_names.add(tensor_name)
+ ggml_type = GGMLQuantizationType(raw_dtype[0])
+ n_elems = int(np.prod(dims))
+ np_dims = tuple(reversed(dims.tolist()))
+ block_size, type_size = GGML_QUANT_SIZES[ggml_type]
+ n_bytes = n_elems * type_size // block_size
+ data_offs = int(start_offs + offset_tensor[0])
+ item_type: npt.DTypeLike
+ if ggml_type == GGMLQuantizationType.F16:
+ item_count = n_elems
+ item_type = np.float16
+ elif ggml_type == GGMLQuantizationType.F32:
+ item_count = n_elems
+ item_type = np.float32
+ elif ggml_type == GGMLQuantizationType.F64:
+ item_count = n_elems
+ item_type = np.float64
+ elif ggml_type == GGMLQuantizationType.I8:
+ item_count = n_elems
+ item_type = np.int8
+ elif ggml_type == GGMLQuantizationType.I16:
+ item_count = n_elems
+ item_type = np.int16
+ elif ggml_type == GGMLQuantizationType.I32:
+ item_count = n_elems
+ item_type = np.int32
+ elif ggml_type == GGMLQuantizationType.I64:
+ item_count = n_elems
+ item_type = np.int64
+ else:
+ item_count = n_bytes
+ item_type = np.uint8
+ np_dims = quant_shape_to_byte_shape(np_dims, ggml_type)
+ tensors.append(ReaderTensor(
+ name = tensor_name,
+ tensor_type = ggml_type,
+ shape = dims,
+ n_elements = n_elems,
+ n_bytes = n_bytes,
+ data_offset = data_offs,
+ data = self._get(data_offs, item_type, item_count).reshape(np_dims),
+ field = field,
+ ))
+ self.tensors = tensors
diff --git a/venv/lib/python3.10/site-packages/gguf/gguf_writer.py b/venv/lib/python3.10/site-packages/gguf/gguf_writer.py
new file mode 100644
index 0000000000000000000000000000000000000000..54ca0c33fd3368daa6a19a15023b792da88951d2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/gguf_writer.py
@@ -0,0 +1,1076 @@
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+import struct
+import tempfile
+from dataclasses import dataclass
+from enum import Enum, auto
+from math import prod
+from pathlib import Path
+from io import BufferedWriter
+from typing import IO, Any, Sequence, Mapping
+from string import ascii_letters, digits
+
+import numpy as np
+
+from .constants import (
+ GGUF_DEFAULT_ALIGNMENT,
+ GGUF_MAGIC,
+ GGUF_VERSION,
+ GGMLQuantizationType,
+ GGUFEndian,
+ GGUFValueType,
+ Keys,
+ RopeScalingType,
+ PoolingType,
+ TokenType,
+ ExpertGatingFuncType,
+)
+
+from .quants import quant_shape_from_byte_shape
+
+logger = logging.getLogger(__name__)
+
+
+SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf"
+
+
+@dataclass
+class TensorInfo:
+ shape: Sequence[int]
+ dtype: GGMLQuantizationType
+ nbytes: int
+ tensor: np.ndarray[Any, Any] | None = None
+
+
+@dataclass
+class GGUFValue:
+ value: Any
+ type: GGUFValueType
+ sub_type: GGUFValueType | None = None
+
+
+class WriterState(Enum):
+ NO_FILE = auto()
+ EMPTY = auto()
+ HEADER = auto()
+ KV_DATA = auto()
+ TI_DATA = auto()
+ WEIGHTS = auto()
+
+
+class GGUFWriter:
+ fout: list[BufferedWriter] | None
+ path: Path | None
+ temp_file: tempfile.SpooledTemporaryFile[bytes] | None
+ tensors: list[dict[str, TensorInfo]]
+ kv_data: list[dict[str, GGUFValue]]
+ state: WriterState
+ _simple_value_packing = {
+ GGUFValueType.UINT8: "B",
+ GGUFValueType.INT8: "b",
+ GGUFValueType.UINT16: "H",
+ GGUFValueType.INT16: "h",
+ GGUFValueType.UINT32: "I",
+ GGUFValueType.INT32: "i",
+ GGUFValueType.FLOAT32: "f",
+ GGUFValueType.UINT64: "Q",
+ GGUFValueType.INT64: "q",
+ GGUFValueType.FLOAT64: "d",
+ GGUFValueType.BOOL: "?",
+ }
+
+ def __init__(
+ self, path: os.PathLike[str] | str | None, arch: str, use_temp_file: bool = False, endianess: GGUFEndian = GGUFEndian.LITTLE,
+ split_max_tensors: int = 0, split_max_size: int = 0, dry_run: bool = False, small_first_shard: bool = False
+ ):
+ self.fout = None
+ self.path = Path(path) if path else None
+ self.arch = arch
+ self.endianess = endianess
+ self.data_alignment = GGUF_DEFAULT_ALIGNMENT
+ self.use_temp_file = use_temp_file
+ self.temp_file = None
+ self.tensors = [{}]
+ self.kv_data = [{}]
+ self.split_max_tensors = split_max_tensors
+ self.split_max_size = split_max_size
+ self.dry_run = dry_run
+ self.small_first_shard = small_first_shard
+ logger.info("gguf: This GGUF file is for {0} Endian only".format(
+ "Big" if self.endianess == GGUFEndian.BIG else "Little",
+ ))
+ self.state = WriterState.NO_FILE
+
+ if self.small_first_shard:
+ self.tensors.append({})
+
+ self.add_architecture()
+
+ def get_total_parameter_count(self) -> tuple[int, int, int, int]:
+ total_params = 0
+ shared_params = 0
+ expert_params = 0
+
+ expert_sum = 0
+ n_expert_tensors = 0
+
+ last_lora_a: tuple[str, TensorInfo] | None = None
+
+ for tensors in self.tensors:
+ for name, info in tensors.items():
+
+ shape = info.shape
+
+ if name.endswith(".lora_a"):
+ last_lora_a = (name, info)
+ continue
+ elif name.endswith(".lora_b"):
+ if last_lora_a is None or last_lora_a[0] != name[:-1] + "a":
+ # Bail when the LoRA pair can't be found trivially
+ logger.warning("can't measure LoRA size correctly, tensor order is unusual")
+ return 0, 0, 0, 0
+ else:
+ shape = (*shape[:-1], last_lora_a[1].shape[-1])
+
+ size = prod(shape)
+
+ if "_exps." in name:
+ expert_params += (size // shape[-3])
+ expert_sum += shape[-3]
+ n_expert_tensors += 1
+ else:
+ shared_params += size
+
+ total_params += size
+
+ # Hopefully this should work even for variable-expert-count models
+ expert_count = (expert_sum // n_expert_tensors) if n_expert_tensors > 0 else 0
+
+ # Negate the total to signal it's likely not exact
+ if last_lora_a is not None:
+ total_params = -total_params
+
+ # NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py
+ return total_params, shared_params, expert_params, expert_count
+
+ def format_shard_names(self, path: Path) -> list[Path]:
+ if len(self.tensors) == 1:
+ return [path]
+ return [path.with_name(SHARD_NAME_FORMAT.format(path.stem, i + 1, len(self.tensors))) for i in range(len(self.tensors))]
+
+ def open_output_file(self, path: Path | None = None) -> None:
+ if self.state is WriterState.EMPTY and self.fout is not None and (path is None or path == self.path):
+ # allow calling this multiple times as long as the path is the same
+ return
+
+ if self.state is not WriterState.NO_FILE:
+ raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
+
+ if path is not None:
+ self.path = path
+
+ if self.path is not None:
+ filenames = self.print_plan()
+ self.fout = [open(filename, "wb") for filename in filenames]
+ self.state = WriterState.EMPTY
+
+ def print_plan(self) -> list[Path]:
+ logger.info("Writing the following files:")
+ assert self.path is not None
+ filenames = self.format_shard_names(self.path)
+ assert len(filenames) == len(self.tensors)
+ for name, tensors in zip(filenames, self.tensors):
+ logger.info(f"{name}: n_tensors = {len(tensors)}, total_size = {GGUFWriter.format_n_bytes_to_str(sum(ti.nbytes for ti in tensors.values()))}")
+
+ if self.dry_run:
+ logger.info("Dry run, not writing files")
+ for name in filenames:
+ print(name) # noqa: NP100
+ exit()
+
+ return filenames
+
+ def add_shard_kv_data(self) -> None:
+ if len(self.tensors) == 1:
+ return
+
+ total_tensors = sum(len(t) for t in self.tensors)
+ assert self.fout is not None
+ total_splits = len(self.fout)
+ self.kv_data.extend({} for _ in range(len(self.kv_data), total_splits))
+ for i, kv_data in enumerate(self.kv_data):
+ kv_data[Keys.Split.LLM_KV_SPLIT_NO] = GGUFValue(i, GGUFValueType.UINT16)
+ kv_data[Keys.Split.LLM_KV_SPLIT_COUNT] = GGUFValue(total_splits, GGUFValueType.UINT16)
+ kv_data[Keys.Split.LLM_KV_SPLIT_TENSORS_COUNT] = GGUFValue(total_tensors, GGUFValueType.INT32)
+
+ def write_header_to_file(self, path: Path | None = None) -> None:
+ if len(self.tensors) == 1 and (self.split_max_tensors != 0 or self.split_max_size != 0):
+ logger.warning("Model fails split requirements, not splitting")
+
+ self.open_output_file(path)
+
+ if self.state is not WriterState.EMPTY:
+ raise ValueError(f'Expected output file to be empty, got {self.state}')
+
+ assert self.fout is not None
+ assert len(self.fout) == len(self.tensors)
+ assert len(self.kv_data) == 1
+
+ self.add_shard_kv_data()
+
+ for fout, tensors, kv_data in zip(self.fout, self.tensors, self.kv_data):
+ fout.write(self._pack(" None:
+ if self.state is not WriterState.HEADER:
+ raise ValueError(f'Expected output file to contain the header, got {self.state}')
+ assert self.fout is not None
+
+ for fout, kv_data in zip(self.fout, self.kv_data):
+ kv_bytes = bytearray()
+
+ for key, val in kv_data.items():
+ kv_bytes += self._pack_val(key, GGUFValueType.STRING, add_vtype=False)
+ kv_bytes += self._pack_val(val.value, val.type, add_vtype=True, sub_type=val.sub_type)
+
+ fout.write(kv_bytes)
+
+ self.flush()
+ self.state = WriterState.KV_DATA
+
+ def write_ti_data_to_file(self) -> None:
+ if self.state is not WriterState.KV_DATA:
+ raise ValueError(f'Expected output file to contain KV data, got {self.state}')
+ assert self.fout is not None
+
+ for fout, tensors in zip(self.fout, self.tensors):
+ ti_data = bytearray()
+ offset_tensor = 0
+
+ for name, ti in tensors.items():
+ ti_data += self._pack_val(name, GGUFValueType.STRING, add_vtype=False)
+ n_dims = len(ti.shape)
+ ti_data += self._pack("I", n_dims)
+ for j in range(n_dims):
+ ti_data += self._pack("Q", ti.shape[n_dims - 1 - j])
+ ti_data += self._pack("I", ti.dtype)
+ ti_data += self._pack("Q", offset_tensor)
+ offset_tensor += GGUFWriter.ggml_pad(ti.nbytes, self.data_alignment)
+
+ fout.write(ti_data)
+ fout.flush()
+ self.state = WriterState.TI_DATA
+
+ def add_key_value(self, key: str, val: Any, vtype: GGUFValueType, sub_type: GGUFValueType | None = None) -> None:
+ if any(key in kv_data for kv_data in self.kv_data):
+ logger.warning(f'Duplicated key name {key!r}, overwriting it with new value {val!r} of type {vtype.name}')
+
+ self.kv_data[0][key] = GGUFValue(value=val, type=vtype, sub_type=sub_type)
+
+ def add_uint8(self, key: str, val: int) -> None:
+ self.add_key_value(key,val, GGUFValueType.UINT8)
+
+ def add_int8(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.INT8)
+
+ def add_uint16(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.UINT16)
+
+ def add_int16(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.INT16)
+
+ def add_uint32(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.UINT32)
+
+ def add_int32(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.INT32)
+
+ def add_float32(self, key: str, val: float) -> None:
+ self.add_key_value(key, val, GGUFValueType.FLOAT32)
+
+ def add_uint64(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.UINT64)
+
+ def add_int64(self, key: str, val: int) -> None:
+ self.add_key_value(key, val, GGUFValueType.INT64)
+
+ def add_float64(self, key: str, val: float) -> None:
+ self.add_key_value(key, val, GGUFValueType.FLOAT64)
+
+ def add_bool(self, key: str, val: bool) -> None:
+ self.add_key_value(key, val, GGUFValueType.BOOL)
+
+ def add_string(self, key: str, val: str) -> None:
+ if not val:
+ return
+ self.add_key_value(key, val, GGUFValueType.STRING)
+
+ def add_array(self, key: str, val: Sequence[Any]) -> None:
+ if len(val) == 0:
+ return
+ self.add_key_value(key, val, GGUFValueType.ARRAY)
+
+ @staticmethod
+ def ggml_pad(x: int, n: int) -> int:
+ return ((x + n - 1) // n) * n
+
+ def add_tensor_info(
+ self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype,
+ tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
+ ) -> None:
+ if self.state is not WriterState.NO_FILE:
+ raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
+
+ if any(name in tensors for tensors in self.tensors):
+ raise ValueError(f'Duplicated tensor name {name!r}')
+
+ if raw_dtype is None:
+ if tensor_dtype == np.float16:
+ dtype = GGMLQuantizationType.F16
+ elif tensor_dtype == np.float32:
+ dtype = GGMLQuantizationType.F32
+ elif tensor_dtype == np.float64:
+ dtype = GGMLQuantizationType.F64
+ elif tensor_dtype == np.int8:
+ dtype = GGMLQuantizationType.I8
+ elif tensor_dtype == np.int16:
+ dtype = GGMLQuantizationType.I16
+ elif tensor_dtype == np.int32:
+ dtype = GGMLQuantizationType.I32
+ elif tensor_dtype == np.int64:
+ dtype = GGMLQuantizationType.I64
+ else:
+ raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
+ else:
+ dtype = raw_dtype
+ if tensor_dtype == np.uint8:
+ tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
+
+ # make sure there is at least one tensor before splitting
+ if len(self.tensors[-1]) > 0:
+ if ( # split when over tensor limit
+ self.split_max_tensors != 0
+ and len(self.tensors[-1]) >= self.split_max_tensors
+ ) or ( # split when over size limit
+ self.split_max_size != 0
+ and sum(ti.nbytes for ti in self.tensors[-1].values()) + tensor_nbytes > self.split_max_size
+ ):
+ self.tensors.append({})
+
+ self.tensors[-1][name] = TensorInfo(shape=tensor_shape, dtype=dtype, nbytes=tensor_nbytes)
+
+ def add_tensor(
+ self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
+ raw_dtype: GGMLQuantizationType | None = None,
+ ) -> None:
+ if self.endianess == GGUFEndian.BIG:
+ tensor.byteswap(inplace=True)
+ if self.use_temp_file and self.temp_file is None:
+ fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
+ fp.seek(0)
+ self.temp_file = fp
+
+ shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
+ self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype)
+
+ if self.temp_file is None:
+ self.tensors[-1][name].tensor = tensor
+ return
+
+ tensor.tofile(self.temp_file)
+ self.write_padding(self.temp_file, tensor.nbytes)
+
+ def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
+ pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
+ if pad != 0:
+ fp.write(bytes([0] * pad))
+
+ def write_tensor_data(self, tensor: np.ndarray[Any, Any]) -> None:
+ if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
+ raise ValueError(f'Expected output file to contain tensor info or weights, got {self.state}')
+ assert self.fout is not None
+
+ if self.endianess == GGUFEndian.BIG:
+ tensor.byteswap(inplace=True)
+
+ file_id = -1
+ for i, tensors in enumerate(self.tensors):
+ if len(tensors) > 0:
+ file_id = i
+ break
+
+ fout = self.fout[file_id]
+
+ # pop the first tensor info
+ # TODO: cleaner way to get the first key
+ first_tensor_name = [name for name, _ in zip(self.tensors[file_id].keys(), range(1))][0]
+ ti = self.tensors[file_id].pop(first_tensor_name)
+ assert ti.nbytes == tensor.nbytes
+
+ self.write_padding(fout, fout.tell())
+ tensor.tofile(fout)
+ self.write_padding(fout, tensor.nbytes)
+
+ self.state = WriterState.WEIGHTS
+
+ def write_tensors_to_file(self, *, progress: bool = False) -> None:
+ self.write_ti_data_to_file()
+
+ assert self.fout is not None
+
+ for fout in self.fout:
+ self.write_padding(fout, fout.tell())
+
+ if self.temp_file is None:
+ shard_bar = None
+ bar = None
+
+ if progress:
+ from tqdm import tqdm
+
+ total_bytes = sum(ti.nbytes for t in self.tensors for ti in t.values())
+
+ if len(self.fout) > 1:
+ shard_bar = tqdm(desc=f"Shard (0/{len(self.fout)})", total=None, unit="byte", unit_scale=True)
+ bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
+
+ for i, (fout, tensors) in enumerate(zip(self.fout, self.tensors)):
+ if shard_bar is not None:
+ shard_bar.set_description(f"Shard ({i + 1}/{len(self.fout)})")
+ total = sum(ti.nbytes for ti in tensors.values())
+ shard_bar.reset(total=(total if total > 0 else None))
+
+ # relying on the fact that Python dicts preserve insertion order (since 3.7)
+ for ti in tensors.values():
+ assert ti.tensor is not None # can only iterate once over the tensors
+ assert ti.tensor.nbytes == ti.nbytes
+ ti.tensor.tofile(fout)
+ if shard_bar is not None:
+ shard_bar.update(ti.nbytes)
+ if bar is not None:
+ bar.update(ti.nbytes)
+ self.write_padding(fout, ti.nbytes)
+ ti.tensor = None
+ else:
+ self.temp_file.seek(0)
+
+ shutil.copyfileobj(self.temp_file, self.fout[0 if not self.small_first_shard else 1])
+ self.flush()
+ self.temp_file.close()
+
+ self.state = WriterState.WEIGHTS
+
+ def flush(self) -> None:
+ assert self.fout is not None
+ for fout in self.fout:
+ fout.flush()
+
+ def close(self) -> None:
+ if self.fout is not None:
+ for fout in self.fout:
+ fout.close()
+ self.fout = None
+
+ def add_type(self, type_name: str) -> None:
+ self.add_string(Keys.General.TYPE, type_name)
+
+ def add_architecture(self) -> None:
+ self.add_string(Keys.General.ARCHITECTURE, self.arch)
+
+ def add_quantization_version(self, quantization_version: int) -> None:
+ self.add_uint32(Keys.General.QUANTIZATION_VERSION, quantization_version)
+
+ def add_custom_alignment(self, alignment: int) -> None:
+ self.data_alignment = alignment
+ self.add_uint32(Keys.General.ALIGNMENT, alignment)
+
+ def add_file_type(self, ftype: int) -> None:
+ self.add_uint32(Keys.General.FILE_TYPE, ftype)
+
+ def add_name(self, name: str) -> None:
+ self.add_string(Keys.General.NAME, name)
+
+ def add_author(self, author: str) -> None:
+ self.add_string(Keys.General.AUTHOR, author)
+
+ def add_version(self, version: str) -> None:
+ self.add_string(Keys.General.VERSION, version)
+
+ def add_organization(self, organization: str) -> None:
+ self.add_string(Keys.General.ORGANIZATION, organization)
+
+ def add_finetune(self, finetune: str) -> None:
+ self.add_string(Keys.General.FINETUNE, finetune)
+
+ def add_basename(self, basename: str) -> None:
+ self.add_string(Keys.General.BASENAME, basename)
+
+ def add_description(self, description: str) -> None:
+ self.add_string(Keys.General.DESCRIPTION, description)
+
+ def add_quantized_by(self, quantized: str) -> None:
+ self.add_string(Keys.General.QUANTIZED_BY, quantized)
+
+ def add_size_label(self, size_label: str) -> None:
+ self.add_string(Keys.General.SIZE_LABEL, size_label)
+
+ def add_license(self, license: str) -> None:
+ self.add_string(Keys.General.LICENSE, license)
+
+ def add_license_name(self, license: str) -> None:
+ self.add_string(Keys.General.LICENSE_NAME, license)
+
+ def add_license_link(self, license: str) -> None:
+ self.add_string(Keys.General.LICENSE_LINK, license)
+
+ def add_url(self, url: str) -> None:
+ self.add_string(Keys.General.URL, url)
+
+ def add_doi(self, doi: str) -> None:
+ self.add_string(Keys.General.DOI, doi)
+
+ def add_uuid(self, uuid: str) -> None:
+ self.add_string(Keys.General.UUID, uuid)
+
+ def add_repo_url(self, repo_url: str) -> None:
+ self.add_string(Keys.General.REPO_URL, repo_url)
+
+ def add_source_url(self, url: str) -> None:
+ self.add_string(Keys.General.SOURCE_URL, url)
+
+ def add_source_doi(self, doi: str) -> None:
+ self.add_string(Keys.General.SOURCE_DOI, doi)
+
+ def add_source_uuid(self, uuid: str) -> None:
+ self.add_string(Keys.General.SOURCE_UUID, uuid)
+
+ def add_source_repo_url(self, repo_url: str) -> None:
+ self.add_string(Keys.General.SOURCE_REPO_URL, repo_url)
+
+ def add_base_model_count(self, source_count: int) -> None:
+ self.add_uint32(Keys.General.BASE_MODEL_COUNT, source_count)
+
+ def add_base_model_name(self, source_id: int, name: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_NAME.format(id=source_id), name)
+
+ def add_base_model_author(self, source_id: int, author: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_AUTHOR.format(id=source_id), author)
+
+ def add_base_model_version(self, source_id: int, version: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_VERSION.format(id=source_id), version)
+
+ def add_base_model_organization(self, source_id: int, organization: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_ORGANIZATION.format(id=source_id), organization)
+
+ def add_base_model_description(self, source_id: int, description: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_DESCRIPTION.format(id=source_id), description)
+
+ def add_base_model_url(self, source_id: int, url: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_URL.format(id=source_id), url)
+
+ def add_base_model_doi(self, source_id: int, doi: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_DOI.format(id=source_id), doi)
+
+ def add_base_model_uuid(self, source_id: int, uuid: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_UUID.format(id=source_id), uuid)
+
+ def add_base_model_repo_url(self, source_id: int, repo_url: str) -> None:
+ self.add_string(Keys.General.BASE_MODEL_REPO_URL.format(id=source_id), repo_url)
+
+ def add_dataset_count(self, source_count: int) -> None:
+ self.add_uint32(Keys.General.DATASET_COUNT, source_count)
+
+ def add_dataset_name(self, source_id: int, name: str) -> None:
+ self.add_string(Keys.General.DATASET_NAME.format(id=source_id), name)
+
+ def add_dataset_author(self, source_id: int, author: str) -> None:
+ self.add_string(Keys.General.DATASET_AUTHOR.format(id=source_id), author)
+
+ def add_dataset_version(self, source_id: int, version: str) -> None:
+ self.add_string(Keys.General.DATASET_VERSION.format(id=source_id), version)
+
+ def add_dataset_organization(self, source_id: int, organization: str) -> None:
+ self.add_string(Keys.General.DATASET_ORGANIZATION.format(id=source_id), organization)
+
+ def add_dataset_description(self, source_id: int, description: str) -> None:
+ self.add_string(Keys.General.DATASET_DESCRIPTION.format(id=source_id), description)
+
+ def add_dataset_url(self, source_id: int, url: str) -> None:
+ self.add_string(Keys.General.DATASET_URL.format(id=source_id), url)
+
+ def add_dataset_doi(self, source_id: int, doi: str) -> None:
+ self.add_string(Keys.General.DATASET_DOI.format(id=source_id), doi)
+
+ def add_dataset_uuid(self, source_id: int, uuid: str) -> None:
+ self.add_string(Keys.General.DATASET_UUID.format(id=source_id), uuid)
+
+ def add_dataset_repo_url(self, source_id: int, repo_url: str) -> None:
+ self.add_string(Keys.General.DATASET_REPO_URL.format(id=source_id), repo_url)
+
+ def add_tags(self, tags: Sequence[str]) -> None:
+ self.add_array(Keys.General.TAGS, tags)
+
+ def add_languages(self, languages: Sequence[str]) -> None:
+ self.add_array(Keys.General.LANGUAGES, languages)
+
+ def add_tensor_data_layout(self, layout: str) -> None:
+ self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
+
+ def add_vocab_size(self, size: int) -> None:
+ self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
+
+ def add_context_length(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
+
+ def add_embedding_length(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
+
+ def add_features_length(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.FEATURES_LENGTH.format(arch=self.arch), length)
+
+ def add_posnet_embedding_length(self, length: int) -> None:
+ self.add_uint32(Keys.PosNet.EMBEDDING_LENGTH.format(arch=self.arch), length)
+
+ def add_posnet_block_count(self, length: int) -> None:
+ self.add_uint32(Keys.PosNet.BLOCK_COUNT.format(arch=self.arch), length)
+
+ def add_convnext_embedding_length(self, length: int) -> None:
+ self.add_uint32(Keys.ConvNext.EMBEDDING_LENGTH.format(arch=self.arch), length)
+
+ def add_convnext_block_count(self, length: int) -> None:
+ self.add_uint32(Keys.ConvNext.BLOCK_COUNT.format(arch=self.arch), length)
+
+ def add_block_count(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
+
+ def add_leading_dense_block_count(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.LEADING_DENSE_BLOCK_COUNT.format(arch=self.arch), length)
+
+ def add_feed_forward_length(self, length: int | Sequence[int]) -> None:
+ if isinstance(length, int):
+ self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
+ else:
+ self.add_array(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
+
+ def add_expert_feed_forward_length(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
+
+ def add_expert_shared_feed_forward_length(self, length: int) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_SHARED_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
+
+ def add_parallel_residual(self, use: bool) -> None:
+ self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
+
+ def add_decoder_start_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.LLM.DECODER_START_TOKEN_ID.format(arch=self.arch), id)
+
+ def add_head_count(self, count: int | Sequence[int]) -> None:
+ if isinstance(count, int):
+ self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
+ else:
+ self.add_array(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
+
+ def add_head_count_kv(self, count: int | Sequence[int]) -> None:
+ if isinstance(count, int):
+ self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
+ else:
+ self.add_array(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
+
+ def add_key_length(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
+
+ def add_value_length(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
+
+ def add_key_length_mla(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.KEY_LENGTH_MLA.format(arch=self.arch), length)
+
+ def add_value_length_mla(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.VALUE_LENGTH_MLA.format(arch=self.arch), length)
+
+ def add_max_alibi_bias(self, bias: float) -> None:
+ self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
+
+ def add_clamp_kqv(self, value: float) -> None:
+ self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
+
+ def add_logit_scale(self, value: float) -> None:
+ self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
+
+ def add_attn_logit_softcapping(self, value: float) -> None:
+ self.add_float32(Keys.LLM.ATTN_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
+
+ def add_final_logit_softcapping(self, value: float) -> None:
+ self.add_float32(Keys.LLM.FINAL_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
+
+ def add_expert_count(self, count: int) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
+
+ def add_expert_used_count(self, count: int) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
+
+ def add_expert_shared_count(self, count: int) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_SHARED_COUNT.format(arch=self.arch), count)
+
+ def add_expert_weights_scale(self, value: float) -> None:
+ self.add_float32(Keys.LLM.EXPERT_WEIGHTS_SCALE.format(arch=self.arch), value)
+
+ def add_expert_weights_norm(self, value: bool) -> None:
+ self.add_bool(Keys.LLM.EXPERT_WEIGHTS_NORM.format(arch=self.arch), value)
+
+ def add_expert_gating_func(self, value: ExpertGatingFuncType) -> None:
+ self.add_uint32(Keys.LLM.EXPERT_GATING_FUNC.format(arch=self.arch), value.value)
+
+ def add_moe_every_n_layers(self, value: int) -> None:
+ self.add_uint32(Keys.LLM.MOE_EVERY_N_LAYERS.format(arch=self.arch), value)
+
+ def add_swin_norm(self, value: bool) -> None:
+ self.add_bool(Keys.LLM.SWIN_NORM.format(arch=self.arch), value)
+
+ def add_rescale_every_n_layers(self, count: int) -> None:
+ self.add_uint32(Keys.LLM.RESCALE_EVERY_N_LAYERS.format(arch=self.arch), count)
+
+ def add_time_mix_extra_dim(self, dim: int) -> None:
+ self.add_uint32(Keys.LLM.TIME_MIX_EXTRA_DIM.format(arch=self.arch), dim)
+
+ def add_time_decay_extra_dim(self, dim: int) -> None:
+ self.add_uint32(Keys.LLM.TIME_DECAY_EXTRA_DIM.format(arch=self.arch), dim)
+
+ def add_residual_scale(self, value: float) -> None:
+ self.add_float32(Keys.LLM.RESIDUAL_SCALE.format(arch=self.arch), value)
+
+ def add_embedding_scale(self, value: float) -> None:
+ self.add_float32(Keys.LLM.EMBEDDING_SCALE.format(arch=self.arch), value)
+
+ def add_wkv_head_size(self, size: int) -> None:
+ self.add_uint32(Keys.WKV.HEAD_SIZE.format(arch=self.arch), size)
+
+ def add_token_shift_count(self, count: int) -> None:
+ self.add_uint32(Keys.LLM.TOKEN_SHIFT_COUNT.format(arch=self.arch), count)
+
+ def add_interleave_moe_layer_step(self, value: int) -> None:
+ self.add_uint32(Keys.LLM.INTERLEAVE_MOE_LAYER_STEP.format(arch=self.arch), value)
+
+ def add_layer_norm_eps(self, value: float) -> None:
+ self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
+
+ def add_layer_norm_rms_eps(self, value: float) -> None:
+ self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
+
+ def add_group_norm_eps(self, value: float) -> None:
+ self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value)
+
+ def add_group_norm_groups(self, value: int) -> None:
+ self.add_uint32(Keys.Attention.GROUPNORM_GROUPS.format(arch=self.arch), value)
+
+ def add_causal_attention(self, value: bool) -> None:
+ self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
+
+ def add_q_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.Q_LORA_RANK.format(arch=self.arch), length)
+
+ def add_kv_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
+
+ def add_decay_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.DECAY_LORA_RANK.format(arch=self.arch), length)
+
+ def add_iclr_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.ICLR_LORA_RANK.format(arch=self.arch), length)
+
+ def add_value_residual_mix_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.VALUE_RESIDUAL_MIX_LORA_RANK.format(arch=self.arch), length)
+
+ def add_gate_lora_rank(self, length: int) -> None:
+ self.add_uint32(Keys.Attention.GATE_LORA_RANK.format(arch=self.arch), length)
+
+ def add_relative_attn_buckets_count(self, value: int) -> None:
+ self.add_uint32(Keys.Attention.REL_BUCKETS_COUNT.format(arch=self.arch), value)
+
+ def add_sliding_window(self, value: int) -> None:
+ self.add_uint32(Keys.Attention.SLIDING_WINDOW.format(arch=self.arch), value)
+
+ def add_attention_scale(self, value: float) -> None:
+ self.add_float32(Keys.Attention.SCALE.format(arch=self.arch), value)
+
+ def add_pooling_type(self, value: PoolingType) -> None:
+ self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
+
+ def add_rope_dimension_count(self, count: int) -> None:
+ self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
+
+ def add_rope_dimension_sections(self, dims: Sequence[int]) -> None:
+ self.add_array(Keys.Rope.DIMENSION_SECTIONS.format(arch=self.arch), dims)
+
+ def add_rope_freq_base(self, value: float) -> None:
+ self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
+
+ def add_rope_scaling_type(self, value: RopeScalingType) -> None:
+ self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
+
+ def add_rope_scaling_factor(self, value: float) -> None:
+ self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
+
+ def add_rope_scaling_attn_factors(self, value: float) -> None:
+ self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
+
+ def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
+ self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
+
+ def add_rope_scaling_finetuned(self, value: bool) -> None:
+ self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
+
+ def add_rope_scaling_yarn_log_mul(self, value: float) -> None:
+ self.add_float32(Keys.Rope.SCALING_YARN_LOG_MUL.format(arch=self.arch), value)
+
+ def add_ssm_conv_kernel(self, value: int) -> None:
+ self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
+
+ def add_ssm_inner_size(self, value: int) -> None:
+ self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
+
+ def add_ssm_state_size(self, value: int) -> None:
+ self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
+
+ def add_ssm_time_step_rank(self, value: int) -> None:
+ self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
+
+ def add_ssm_dt_b_c_rms(self, value: bool) -> None:
+ self.add_bool(Keys.SSM.DT_B_C_RMS.format(arch=self.arch), value)
+
+ def add_tokenizer_model(self, model: str) -> None:
+ self.add_string(Keys.Tokenizer.MODEL, model)
+
+ def add_tokenizer_pre(self, pre: str) -> None:
+ self.add_string(Keys.Tokenizer.PRE, pre)
+
+ def add_token_list(self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
+ self.add_array(Keys.Tokenizer.LIST, tokens)
+
+ def add_token_merges(self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
+ self.add_array(Keys.Tokenizer.MERGES, merges)
+
+ def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
+ self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
+
+ def add_token_type_count(self, value: int) -> None:
+ self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
+
+ def add_token_scores(self, scores: Sequence[float]) -> None:
+ self.add_array(Keys.Tokenizer.SCORES, scores)
+
+ def add_bos_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.BOS_ID, id)
+
+ def add_eos_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.EOS_ID, id)
+
+ def add_unk_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.UNK_ID, id)
+
+ def add_sep_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.SEP_ID, id)
+
+ def add_pad_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.PAD_ID, id)
+
+ def add_mask_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.MASK_ID, id)
+
+ def add_add_bos_token(self, value: bool) -> None:
+ self.add_bool(Keys.Tokenizer.ADD_BOS, value)
+
+ def add_add_eos_token(self, value: bool) -> None:
+ self.add_bool(Keys.Tokenizer.ADD_EOS, value)
+
+ def add_add_space_prefix(self, value: bool) -> None:
+ self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
+
+ def add_remove_extra_whitespaces(self, value: bool) -> None:
+ self.add_bool(Keys.Tokenizer.REMOVE_EXTRA_WS, value)
+
+ def add_precompiled_charsmap(self, charsmap: bytes) -> None:
+ self.add_array(Keys.Tokenizer.PRECOMPILED_CHARSMAP, charsmap)
+
+ def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
+ if not isinstance(value, str):
+ template_default = None
+ template_names = set()
+
+ for choice in value:
+ name = choice.get('name', '')
+ template = choice.get('template')
+
+ # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
+ name = ''.join((c if c in ascii_letters + digits else '_' for c in name))
+
+ if name and template is not None:
+ if name == 'default':
+ template_default = template
+ else:
+ template_names.add(name)
+ self.add_string(Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template)
+
+ if template_names:
+ self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
+
+ if template_default is None:
+ return
+
+ value = template_default
+
+ self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
+
+ def add_eot_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.EOT_ID, id)
+
+ def add_eom_token_id(self, id: int) -> None:
+ self.add_uint32(Keys.Tokenizer.EOM_ID, id)
+
+ def add_classifier_output_labels(self, labels: Sequence[str]) -> None:
+ self.add_array(Keys.Classifier.OUTPUT_LABELS.format(arch=self.arch), labels)
+
+ # for vision models
+
+ def add_clip_has_vision_encoder(self, value: bool) -> None:
+ self.add_bool(Keys.Clip.HAS_VISION_ENCODER, value)
+
+ def add_clip_has_audio_encoder(self, value: bool) -> None:
+ self.add_bool(Keys.Clip.HAS_AUDIO_ENCODER, value)
+
+ def add_clip_projector_type(self, value: str) -> None:
+ self.add_string(Keys.Clip.PROJECTOR_TYPE, value)
+
+ def add_vision_projection_dim(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.PROJECTION_DIM, value)
+
+ def add_vision_patch_size(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.PATCH_SIZE, value)
+
+ def add_vision_embedding_length(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.EMBEDDING_LENGTH, value)
+
+ def add_vision_feed_forward_length(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.FEED_FORWARD_LENGTH, value)
+
+ def add_vision_block_count(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.BLOCK_COUNT, value)
+
+ def add_vision_head_count(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.Attention.HEAD_COUNT, value)
+
+ def add_vision_attention_layernorm_eps(self, value: float) -> None:
+ self.add_float32(Keys.ClipVision.Attention.LAYERNORM_EPS, value)
+
+ def add_vision_image_size(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.IMAGE_SIZE, value)
+
+ def add_vision_image_mean(self, values: Sequence[float]) -> None:
+ self.add_array(Keys.ClipVision.IMAGE_MEAN, values)
+
+ def add_vision_image_std(self, values: Sequence[float]) -> None:
+ self.add_array(Keys.ClipVision.IMAGE_STD, values)
+
+ def add_vision_spatial_merge_size(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.SPATIAL_MERGE_SIZE, value)
+
+ def add_vision_use_gelu(self, value: bool) -> None:
+ self.add_bool(Keys.ClipVision.USE_GELU, value)
+
+ def add_vision_use_silu(self, value: bool) -> None:
+ self.add_bool(Keys.ClipVision.USE_SILU, value)
+
+ def add_vision_projector_scale_factor(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.Projector.SCALE_FACTOR, value)
+
+ def add_vision_n_wa_pattern(self, value: int) -> None:
+ self.add_uint32(Keys.ClipVision.N_WA_PATTERN, value)
+
+ # audio models
+
+ def add_audio_projection_dim(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.PROJECTION_DIM, value)
+
+ def add_audio_embedding_length(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.EMBEDDING_LENGTH, value)
+
+ def add_audio_feed_forward_length(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.FEED_FORWARD_LENGTH, value)
+
+ def add_audio_block_count(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.BLOCK_COUNT, value)
+
+ def add_audio_head_count(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.Attention.HEAD_COUNT, value)
+
+ def add_audio_attention_layernorm_eps(self, value: float) -> None:
+ self.add_float32(Keys.ClipAudio.Attention.LAYERNORM_EPS, value)
+
+ def add_audio_num_mel_bins(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.NUM_MEL_BINS, value)
+
+ def add_audio_stack_factor(self, value: int) -> None:
+ self.add_uint32(Keys.ClipAudio.Projector.STACK_FACTOR, value)
+
+ def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
+ pack_prefix = ''
+ if not skip_pack_prefix:
+ pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
+ return struct.pack(f'{pack_prefix}{fmt}', value)
+
+ def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool, sub_type: GGUFValueType | None = None) -> bytes:
+ kv_data = bytearray()
+
+ if add_vtype:
+ kv_data += self._pack("I", vtype)
+
+ pack_fmt = self._simple_value_packing.get(vtype)
+ if pack_fmt is not None:
+ kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
+ elif vtype == GGUFValueType.STRING:
+ encoded_val = val.encode("utf-8") if isinstance(val, str) else val
+ kv_data += self._pack("Q", len(encoded_val))
+ kv_data += encoded_val
+ elif vtype == GGUFValueType.ARRAY:
+
+ if not isinstance(val, Sequence):
+ raise ValueError("Invalid GGUF metadata array, expecting sequence")
+
+ if len(val) == 0:
+ raise ValueError("Invalid GGUF metadata array. Empty array")
+
+ if sub_type is not None:
+ ltype = sub_type
+ elif isinstance(val, bytes):
+ ltype = GGUFValueType.UINT8
+ else:
+ ltype = GGUFValueType.get_type(val[0])
+ if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
+ raise ValueError("All items in a GGUF array should be of the same type")
+ kv_data += self._pack("I", ltype)
+ kv_data += self._pack("Q", len(val))
+ for item in val:
+ kv_data += self._pack_val(item, ltype, add_vtype=False)
+ else:
+ raise ValueError("Invalid GGUF metadata value type or value")
+
+ return kv_data
+
+ @staticmethod
+ def format_n_bytes_to_str(num: int) -> str:
+ if num == 0:
+ return "negligible - metadata only"
+ fnum = float(num)
+ for unit in ("", "K", "M", "G"):
+ if abs(fnum) < 1000.0:
+ return f"{fnum:3.1f}{unit}"
+ fnum /= 1000.0
+ return f"{fnum:.1f}T - over 1TB, split recommended"
diff --git a/venv/lib/python3.10/site-packages/gguf/lazy.py b/venv/lib/python3.10/site-packages/gguf/lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9bcadae0224bac5f922ce6565dd1e3883a923e1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/lazy.py
@@ -0,0 +1,223 @@
+from __future__ import annotations
+from abc import ABC, ABCMeta, abstractmethod
+
+import logging
+from typing import Any, Callable
+
+import numpy as np
+from numpy.typing import DTypeLike
+
+
+logger = logging.getLogger(__name__)
+
+
+class LazyMeta(ABCMeta):
+
+ def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs):
+ def __getattr__(self, name: str) -> Any:
+ meta_attr = getattr(self._meta, name)
+ if callable(meta_attr):
+ return type(self)._wrap_fn(
+ (lambda s, *args, **kwargs: getattr(s, name)(*args, **kwargs)),
+ use_self=self,
+ )
+ elif isinstance(meta_attr, self._tensor_type):
+ # e.g. self.T with torch.Tensor should still be wrapped
+ return type(self)._wrap_fn(lambda s: getattr(s, name))(self)
+ else:
+ # no need to wrap non-tensor properties,
+ # and they likely don't depend on the actual contents of the tensor
+ return meta_attr
+
+ namespace["__getattr__"] = __getattr__
+
+ # need to make a builder for the wrapped wrapper to copy the name,
+ # or else it fails with very cryptic error messages,
+ # because somehow the same string would end up in every closures
+ def mk_wrap(op_name: str, *, meta_noop: bool = False):
+ # need to wrap the wrapper to get self
+ def wrapped_special_op(self, *args, **kwargs):
+ return type(self)._wrap_fn(
+ getattr(type(self)._tensor_type, op_name),
+ meta_noop=meta_noop,
+ )(self, *args, **kwargs)
+ return wrapped_special_op
+
+ # special methods bypass __getattr__, so they need to be added manually
+ # ref: https://docs.python.org/3/reference/datamodel.html#special-lookup
+ # NOTE: doing this from a metaclass is very convenient
+ # TODO: make this even more comprehensive
+ for binary_op in (
+ "lt", "le", "eq", "ne", "ge", "gt", "not"
+ "abs", "add", "and", "floordiv", "invert", "lshift", "mod", "mul", "matmul",
+ "neg", "or", "pos", "pow", "rshift", "sub", "truediv", "xor",
+ "iadd", "iand", "ifloordiv", "ilshift", "imod", "imul", "ior", "irshift", "isub", "ixor",
+ "radd", "rand", "rfloordiv", "rmul", "ror", "rpow", "rsub", "rtruediv", "rxor",
+ ):
+ attr_name = f"__{binary_op}__"
+ # the result of these operators usually has the same shape and dtype as the input,
+ # so evaluation on the meta tensor can be skipped.
+ namespace[attr_name] = mk_wrap(attr_name, meta_noop=True)
+
+ for special_op in (
+ "getitem", "setitem", "len",
+ ):
+ attr_name = f"__{special_op}__"
+ namespace[attr_name] = mk_wrap(attr_name, meta_noop=False)
+
+ return super().__new__(cls, name, bases, namespace, **kwargs)
+
+
+# Tree of lazy tensors
+class LazyBase(ABC, metaclass=LazyMeta):
+ _tensor_type: type
+ _meta: Any
+ _data: Any | None
+ _args: tuple
+ _kwargs: dict[str, Any]
+ _func: Callable[[Any], Any] | None
+
+ def __init__(self, *, meta: Any, data: Any | None = None, args: tuple = (), kwargs: dict[str, Any] | None = None, func: Callable[[Any], Any] | None = None):
+ super().__init__()
+ self._meta = meta
+ self._data = data
+ self._args = args
+ self._kwargs = kwargs if kwargs is not None else {}
+ self._func = func
+ assert self._func is not None or self._data is not None
+
+ def __init_subclass__(cls) -> None:
+ if "_tensor_type" not in cls.__dict__:
+ raise TypeError(f"property '_tensor_type' must be defined for {cls!r}")
+ return super().__init_subclass__()
+
+ @staticmethod
+ def _recurse_apply(o: Any, fn: Callable[[Any], Any]) -> Any:
+ # TODO: dict and set
+ if isinstance(o, (list, tuple)):
+ L = []
+ for item in o:
+ L.append(LazyBase._recurse_apply(item, fn))
+ if isinstance(o, tuple):
+ L = tuple(L)
+ return L
+ elif isinstance(o, LazyBase):
+ return fn(o)
+ else:
+ return o
+
+ @classmethod
+ def _wrap_fn(cls, fn: Callable, *, use_self: LazyBase | None = None, meta_noop: bool | DTypeLike | tuple[DTypeLike, Callable[[tuple[int, ...]], tuple[int, ...]]] = False) -> Callable[[Any], Any]:
+ def wrapped_fn(*args, **kwargs):
+ if kwargs is None:
+ kwargs = {}
+ args = ((use_self,) if use_self is not None else ()) + args
+
+ meta_args = LazyBase._recurse_apply(args, lambda t: t._meta)
+ # TODO: maybe handle tensors in kwargs too
+
+ if isinstance(meta_noop, bool) and not meta_noop:
+ try:
+ res = fn(*meta_args, **kwargs)
+ except NotImplementedError:
+ # running some operations on PyTorch's Meta tensors can cause this exception
+ res = None
+ else:
+ # some operators don't need to actually run on the meta tensors
+ assert len(args) > 0
+ res = args[0]
+ assert isinstance(res, cls)
+ res = res._meta
+ # allow operations to override the dtype and shape
+ if meta_noop is not True:
+ if isinstance(meta_noop, tuple):
+ dtype, shape = meta_noop
+ assert callable(shape)
+ res = cls.meta_with_dtype_and_shape(dtype, shape(res.shape))
+ else:
+ res = cls.meta_with_dtype_and_shape(meta_noop, res.shape)
+
+ if isinstance(res, cls._tensor_type):
+ return cls(meta=cls.eager_to_meta(res), args=args, kwargs=kwargs, func=fn)
+ elif isinstance(res, tuple) and all(isinstance(t, cls._tensor_type) for t in res):
+ # share the evaluation between lazy tuple elements
+ shared_args: list = [args, None]
+
+ def eager_tuple_element(a: list[Any], i: int = 0, /, **kw) -> LazyBase:
+ assert len(a) == 2
+ if a[1] is None:
+ a[1] = fn(*a[0], **kw)
+ return a[1][i]
+ return tuple(cls(meta=cls.eager_to_meta(res[i]), args=(shared_args, i), kwargs=kwargs, func=eager_tuple_element) for i in range(len(res)))
+ else:
+ del res # not needed
+ # non-tensor return likely relies on the contents of the args
+ # (e.g. the result of torch.equal)
+ eager_args = cls.to_eager(args)
+ return fn(*eager_args, **kwargs)
+ return wrapped_fn
+
+ @classmethod
+ def to_eager(cls, t: Any) -> Any:
+ def simple_to_eager(_t: LazyBase) -> Any:
+ if _t._data is not None:
+ return _t._data
+
+ # NOTE: there's a recursion limit in Python (usually 1000)
+
+ assert _t._func is not None
+ _t._args = cls._recurse_apply(_t._args, simple_to_eager)
+ _t._data = _t._func(*_t._args, **_t._kwargs)
+ # sanity check
+ assert _t._data is not None
+ assert _t._data.dtype == _t._meta.dtype
+ assert _t._data.shape == _t._meta.shape
+
+ return _t._data
+
+ # recurse into lists and/or tuples, keeping their structure
+ return cls._recurse_apply(t, simple_to_eager)
+
+ @classmethod
+ def eager_to_meta(cls, t: Any) -> Any:
+ return cls.meta_with_dtype_and_shape(t.dtype, t.shape)
+
+ # must be overridden, meta tensor init is backend-specific
+ @classmethod
+ @abstractmethod
+ def meta_with_dtype_and_shape(cls, dtype: Any, shape: Any) -> Any: pass
+
+ @classmethod
+ def from_eager(cls, t: Any) -> Any:
+ if type(t) is cls:
+ # already lazy
+ return t
+ elif isinstance(t, cls._tensor_type):
+ return cls(meta=cls.eager_to_meta(t), data=t)
+ else:
+ return TypeError(f"{type(t)!r} is not compatible with {cls._tensor_type!r}")
+
+
+class LazyNumpyTensor(LazyBase):
+ _tensor_type = np.ndarray
+
+ shape: tuple[int, ...] # Makes the type checker happy in quants.py
+
+ @classmethod
+ def meta_with_dtype_and_shape(cls, dtype: DTypeLike, shape: tuple[int, ...]) -> np.ndarray[Any, Any]:
+ # The initial idea was to use np.nan as the fill value,
+ # but non-float types like np.int16 can't use that.
+ # So zero it is.
+ cheat = np.zeros(1, dtype)
+ return np.lib.stride_tricks.as_strided(cheat, shape, (0 for _ in shape))
+
+ def astype(self, dtype, *args, **kwargs):
+ meta = type(self).meta_with_dtype_and_shape(dtype, self._meta.shape)
+ full_args = (self, dtype,) + args
+ return type(self)(meta=meta, args=full_args, kwargs=kwargs, func=(lambda a, *args, **kwargs: a.astype(*args, **kwargs)))
+
+ def tofile(self, *args, **kwargs):
+ eager = LazyNumpyTensor.to_eager(self)
+ return eager.tofile(*args, **kwargs)
+
+ # TODO: __array_function__
diff --git a/venv/lib/python3.10/site-packages/gguf/metadata.py b/venv/lib/python3.10/site-packages/gguf/metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..e807f434689de669816504921f54809cac15fc71
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/metadata.py
@@ -0,0 +1,642 @@
+from __future__ import annotations
+
+import re
+import json
+import yaml
+import logging
+from pathlib import Path
+from typing import Any, Literal, Optional
+from dataclasses import dataclass
+
+from .constants import Keys
+
+import gguf
+
+logger = logging.getLogger("metadata")
+
+
+@dataclass
+class Metadata:
+ # Authorship Metadata to be written to GGUF KV Store
+ name: Optional[str] = None
+ author: Optional[str] = None
+ version: Optional[str] = None
+ organization: Optional[str] = None
+ finetune: Optional[str] = None
+ basename: Optional[str] = None
+ description: Optional[str] = None
+ quantized_by: Optional[str] = None
+ size_label: Optional[str] = None
+ url: Optional[str] = None
+ doi: Optional[str] = None
+ uuid: Optional[str] = None
+ repo_url: Optional[str] = None
+ source_url: Optional[str] = None
+ source_doi: Optional[str] = None
+ source_uuid: Optional[str] = None
+ source_repo_url: Optional[str] = None
+ license: Optional[str] = None
+ license_name: Optional[str] = None
+ license_link: Optional[str] = None
+ base_models: Optional[list[dict]] = None
+ tags: Optional[list[str]] = None
+ languages: Optional[list[str]] = None
+ datasets: Optional[list[dict]] = None
+
+ @staticmethod
+ def load(metadata_override_path: Optional[Path] = None, model_path: Optional[Path] = None, model_name: Optional[str] = None, total_params: int = 0) -> Metadata:
+ # This grabs as many contextual authorship metadata as possible from the model repository
+ # making any conversion as required to match the gguf kv store metadata format
+ # as well as giving users the ability to override any authorship metadata that may be incorrect
+
+ # Create a new Metadata instance
+ metadata = Metadata()
+
+ model_card = Metadata.load_model_card(model_path)
+ hf_params = Metadata.load_hf_parameters(model_path)
+ # TODO: load adapter_config.json when possible, it usually contains the base model of the LoRA adapter
+
+ # heuristics
+ metadata = Metadata.apply_metadata_heuristic(metadata, model_card, hf_params, model_path, total_params)
+
+ # Metadata Override File Provided
+ # This is based on LLM_KV_NAMES mapping in llama.cpp
+ metadata_override = Metadata.load_metadata_override(metadata_override_path)
+
+ metadata.name = metadata_override.get(Keys.General.NAME, metadata.name)
+ metadata.author = metadata_override.get(Keys.General.AUTHOR, metadata.author)
+ metadata.version = metadata_override.get(Keys.General.VERSION, metadata.version)
+ metadata.organization = metadata_override.get(Keys.General.ORGANIZATION, metadata.organization)
+
+ metadata.finetune = metadata_override.get(Keys.General.FINETUNE, metadata.finetune)
+ metadata.basename = metadata_override.get(Keys.General.BASENAME, metadata.basename)
+
+ metadata.description = metadata_override.get(Keys.General.DESCRIPTION, metadata.description)
+ metadata.quantized_by = metadata_override.get(Keys.General.QUANTIZED_BY, metadata.quantized_by)
+
+ metadata.size_label = metadata_override.get(Keys.General.SIZE_LABEL, metadata.size_label)
+ metadata.license_name = metadata_override.get(Keys.General.LICENSE_NAME, metadata.license_name)
+ metadata.license_link = metadata_override.get(Keys.General.LICENSE_LINK, metadata.license_link)
+
+ metadata.url = metadata_override.get(Keys.General.URL, metadata.url)
+ metadata.doi = metadata_override.get(Keys.General.DOI, metadata.doi)
+ metadata.uuid = metadata_override.get(Keys.General.UUID, metadata.uuid)
+ metadata.repo_url = metadata_override.get(Keys.General.REPO_URL, metadata.repo_url)
+
+ metadata.source_url = metadata_override.get(Keys.General.SOURCE_URL, metadata.source_url)
+ metadata.source_doi = metadata_override.get(Keys.General.SOURCE_DOI, metadata.source_doi)
+ metadata.source_uuid = metadata_override.get(Keys.General.SOURCE_UUID, metadata.source_uuid)
+ metadata.source_repo_url = metadata_override.get(Keys.General.SOURCE_REPO_URL, metadata.source_repo_url)
+
+ # Base Models is received here as an array of models
+ metadata.base_models = metadata_override.get("general.base_models", metadata.base_models)
+
+ # Datasets is received here as an array of datasets
+ metadata.datasets = metadata_override.get("general.datasets", metadata.datasets)
+
+ metadata.tags = metadata_override.get(Keys.General.TAGS, metadata.tags)
+ metadata.languages = metadata_override.get(Keys.General.LANGUAGES, metadata.languages)
+
+ # Direct Metadata Override (via direct cli argument)
+ if model_name is not None:
+ metadata.name = model_name
+
+ return metadata
+
+ @staticmethod
+ def load_metadata_override(metadata_override_path: Optional[Path] = None) -> dict[str, Any]:
+ if metadata_override_path is None or not metadata_override_path.is_file():
+ return {}
+
+ with open(metadata_override_path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+ @staticmethod
+ def load_model_card(model_path: Optional[Path] = None) -> dict[str, Any]:
+ if model_path is None or not model_path.is_dir():
+ return {}
+
+ model_card_path = model_path / "README.md"
+
+ if not model_card_path.is_file():
+ return {}
+
+ # The model card metadata is assumed to always be in YAML (frontmatter)
+ # ref: https://github.com/huggingface/transformers/blob/a5c642fe7a1f25d3bdcd76991443ba6ff7ee34b2/src/transformers/modelcard.py#L468-L473
+ yaml_content: str = ""
+ with open(model_card_path, "r", encoding="utf-8") as f:
+ content = f.read()
+ lines = content.splitlines()
+ lines_yaml = []
+ if len(lines) == 0:
+ # Empty file
+ return {}
+ if len(lines) > 0 and lines[0] != "---":
+ # No frontmatter
+ return {}
+ for line in lines[1:]:
+ if line == "---":
+ break # End of frontmatter
+ else:
+ lines_yaml.append(line)
+ yaml_content = "\n".join(lines_yaml) + "\n"
+
+ # Quick hack to fix the Norway problem
+ # https://hitchdev.com/strictyaml/why/implicit-typing-removed/
+ yaml_content = yaml_content.replace("- no\n", "- \"no\"\n")
+
+ if yaml_content:
+ data = yaml.safe_load(yaml_content)
+ if isinstance(data, dict):
+ return data
+ else:
+ logger.error(f"while reading YAML model card frontmatter, data is {type(data)} instead of dict")
+ return {}
+ else:
+ return {}
+
+ @staticmethod
+ def load_hf_parameters(model_path: Optional[Path] = None) -> dict[str, Any]:
+ if model_path is None or not model_path.is_dir():
+ return {}
+
+ config_path = model_path / "config.json"
+
+ if not config_path.is_file():
+ return {}
+
+ with open(config_path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+ @staticmethod
+ def id_to_title(string):
+ # Convert capitalization into title form unless acronym or version number
+ return ' '.join([w.title() if w.islower() and not re.match(r'^(v\d+(?:\.\d+)*|\d.*)$', w) else w for w in string.strip().replace('-', ' ').split()])
+
+ @staticmethod
+ def get_model_id_components(model_id: Optional[str] = None, total_params: int = 0) -> tuple[str | None, str | None, str | None, str | None, str | None, str | None]:
+ # Huggingface often store model id as '/'
+ # so let's parse it and apply some heuristics if possible for model name components
+
+ if model_id is None:
+ # model ID missing
+ return None, None, None, None, None, None
+
+ if ' ' in model_id:
+ # model ID is actually a normal human sentence
+ # which means its most likely a normal model name only
+ # not part of the hugging face naming standard, but whatever
+ return model_id, None, None, None, None, None
+
+ if '/' in model_id:
+ # model ID (huggingface style)
+ org_component, model_full_name_component = model_id.split('/', 1)
+ else:
+ # model ID but missing org components
+ org_component, model_full_name_component = None, model_id
+
+ # Check if we erroneously matched against './' or '../' etc...
+ if org_component is not None and len(org_component) > 0 and org_component[0] == '.':
+ org_component = None
+
+ name_parts: list[str] = model_full_name_component.split('-')
+
+ # Remove empty parts
+ for i in reversed(range(len(name_parts))):
+ if len(name_parts[i]) == 0:
+ del name_parts[i]
+
+ name_types: list[
+ set[Literal["basename", "size_label", "finetune", "version", "type"]]
+ ] = [set() for _ in name_parts]
+
+ # Annotate the name
+ for i, part in enumerate(name_parts):
+ # Version
+ if re.fullmatch(r'(v|iter)?\d+([.]\d+)*', part, re.IGNORECASE):
+ name_types[i].add("version")
+ # Quant type (should not be there for base models, but still annotated)
+ elif re.fullmatch(r'i?q\d(_\w)*|b?fp?(16|32)', part, re.IGNORECASE):
+ name_types[i].add("type")
+ name_parts[i] = part.upper()
+ # Model size
+ elif i > 0 and re.fullmatch(r'(([A]|\d+[x])?\d+([._]\d+)?[KMBT][\d]?|small|mini|medium|large|x?xl)', part, re.IGNORECASE):
+ part = part.replace("_", ".")
+ # Handle weird bloom-7b1 notation
+ if part[-1].isdecimal():
+ part = part[:-2] + "." + part[-1] + part[-2]
+ # Normalize the size suffixes
+ if len(part) > 1 and part[-2].isdecimal():
+ if part[-1] in "kmbt":
+ part = part[:-1] + part[-1].upper()
+ if total_params != 0:
+ try:
+ label_params = float(part[:-1]) * pow(1000, " KMBT".find(part[-1]))
+ # Only use it as a size label if it's close or bigger than the model size
+ # Note that LoRA adapters don't necessarily include all layers,
+ # so this is why bigger label sizes are accepted.
+ # Do not use the size label when it's smaller than 1/8 of the model size
+ if (total_params < 0 and label_params < abs(total_params) // 8) or (
+ # Check both directions when the current model isn't a LoRA adapter
+ total_params > 0 and abs(label_params - total_params) > 7 * total_params // 8
+ ):
+ # Likely a context length
+ name_types[i].add("finetune")
+ # Lowercase the size when it's a context length
+ part = part[:-1] + part[-1].lower()
+ except ValueError:
+ # Failed to convert the size label to float, use it anyway
+ pass
+ if len(name_types[i]) == 0:
+ name_types[i].add("size_label")
+ name_parts[i] = part
+ # Some easy to recognize finetune names
+ elif i > 0 and re.fullmatch(r'chat|instruct|vision|lora', part, re.IGNORECASE):
+ if total_params < 0 and part.lower() == "lora":
+ # ignore redundant "lora" in the finetune part when the output is a lora adapter
+ name_types[i].add("type")
+ else:
+ name_types[i].add("finetune")
+
+ # Ignore word-based size labels when there is at least a number-based one present
+ # TODO: should word-based size labels always be removed instead?
+ if any(c.isdecimal() for n, t in zip(name_parts, name_types) if "size_label" in t for c in n):
+ for n, t in zip(name_parts, name_types):
+ if "size_label" in t:
+ if all(c.isalpha() for c in n):
+ t.remove("size_label")
+
+ at_start = True
+ # Find the basename through the annotated name
+ for part, t in zip(name_parts, name_types):
+ if at_start and ((len(t) == 0 and part[0].isalpha()) or "version" in t):
+ t.add("basename")
+ else:
+ if at_start:
+ at_start = False
+ if len(t) == 0:
+ t.add("finetune")
+
+ # Remove the basename annotation from trailing version
+ for part, t in zip(reversed(name_parts), reversed(name_types)):
+ if "basename" in t and len(t) > 1:
+ t.remove("basename")
+ else:
+ break
+
+ basename = "-".join(n for n, t in zip(name_parts, name_types) if "basename" in t) or None
+ # Deduplicate size labels using order-preserving 'dict' ('set' seems to sort the keys)
+ size_label = "-".join(dict.fromkeys(s for s, t in zip(name_parts, name_types) if "size_label" in t).keys()) or None
+ finetune = "-".join(f for f, t in zip(name_parts, name_types) if "finetune" in t) or None
+ # TODO: should the basename version always be excluded?
+ # NOTE: multiple finetune versions are joined together
+ version = "-".join(v for v, t, in zip(name_parts, name_types) if "version" in t and "basename" not in t) or None
+
+ if size_label is None and finetune is None and version is None:
+ # Too ambiguous, output nothing
+ basename = None
+
+ return model_full_name_component, org_component, basename, finetune, version, size_label
+
+ @staticmethod
+ def apply_metadata_heuristic(metadata: Metadata, model_card: Optional[dict] = None, hf_params: Optional[dict] = None, model_path: Optional[Path] = None, total_params: int = 0) -> Metadata:
+ # Reference Model Card Metadata: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
+
+ # Model Card Heuristics
+ ########################
+ if model_card is not None:
+
+ def use_model_card_metadata(metadata_key: str, model_card_key: str):
+ if model_card_key in model_card and getattr(metadata, metadata_key, None) is None:
+ setattr(metadata, metadata_key, model_card.get(model_card_key))
+
+ def use_array_model_card_metadata(metadata_key: str, model_card_key: str):
+ # Note: Will append rather than replace if already exist
+ tags_value = model_card.get(model_card_key, None)
+ if tags_value is None:
+ return
+
+ current_value = getattr(metadata, metadata_key, None)
+ if current_value is None:
+ current_value = []
+
+ if isinstance(tags_value, str):
+ current_value.append(tags_value)
+ elif isinstance(tags_value, list):
+ current_value.extend(tags_value)
+
+ setattr(metadata, metadata_key, current_value)
+
+ # LLAMA.cpp's direct internal convention
+ # (Definitely not part of hugging face formal/informal standard)
+ #########################################
+ use_model_card_metadata("name", "name")
+ use_model_card_metadata("author", "author")
+ use_model_card_metadata("version", "version")
+ use_model_card_metadata("organization", "organization")
+ use_model_card_metadata("description", "description")
+ use_model_card_metadata("finetune", "finetune")
+ use_model_card_metadata("basename", "basename")
+ use_model_card_metadata("size_label", "size_label")
+ use_model_card_metadata("source_url", "url")
+ use_model_card_metadata("source_doi", "doi")
+ use_model_card_metadata("source_uuid", "uuid")
+ use_model_card_metadata("source_repo_url", "repo_url")
+
+ # LLAMA.cpp's huggingface style convention
+ # (Definitely not part of hugging face formal/informal standard... but with model_ appended to match their style)
+ ###########################################
+ use_model_card_metadata("name", "model_name")
+ use_model_card_metadata("author", "model_author")
+ use_model_card_metadata("version", "model_version")
+ use_model_card_metadata("organization", "model_organization")
+ use_model_card_metadata("description", "model_description")
+ use_model_card_metadata("finetune", "model_finetune")
+ use_model_card_metadata("basename", "model_basename")
+ use_model_card_metadata("size_label", "model_size_label")
+ use_model_card_metadata("source_url", "model_url")
+ use_model_card_metadata("source_doi", "model_doi")
+ use_model_card_metadata("source_uuid", "model_uuid")
+ use_model_card_metadata("source_repo_url", "model_repo_url")
+
+ # Hugging Face Direct Convention
+ #################################
+
+ # Not part of huggingface model card standard but notice some model creator using it
+ # such as TheBloke in 'TheBloke/Mistral-7B-Instruct-v0.2-GGUF'
+ use_model_card_metadata("name", "model_name")
+ use_model_card_metadata("author", "model_creator")
+ use_model_card_metadata("basename", "model_type")
+
+ if "base_model" in model_card or "base_models" in model_card or "base_model_sources" in model_card:
+ # This represents the parent models that this is based on
+ # Example: stabilityai/stable-diffusion-xl-base-1.0. Can also be a list (for merges)
+ # Example of merges: https://huggingface.co/EmbeddedLLM/Mistral-7B-Merge-14-v0.1/blob/main/README.md
+ metadata_base_models = []
+ base_model_value = model_card.get("base_model", model_card.get("base_models", model_card.get("base_model_sources", None)))
+
+ if base_model_value is not None:
+ if isinstance(base_model_value, str):
+ metadata_base_models.append(base_model_value)
+ elif isinstance(base_model_value, list):
+ metadata_base_models.extend(base_model_value)
+
+ if metadata.base_models is None:
+ metadata.base_models = []
+
+ for model_id in metadata_base_models:
+ # NOTE: model size of base model is assumed to be similar to the size of the current model
+ base_model = {}
+ if isinstance(model_id, str):
+ if model_id.startswith("http://") or model_id.startswith("https://") or model_id.startswith("ssh://"):
+ base_model["repo_url"] = model_id
+
+ # Check if Hugging Face ID is present in URL
+ if "huggingface.co" in model_id:
+ match = re.match(r"https?://huggingface.co/([^/]+/[^/]+)$", model_id)
+ if match:
+ model_id_component = match.group(1)
+ model_full_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(model_id_component, total_params)
+
+ # Populate model dictionary with extracted components
+ if model_full_name_component is not None:
+ base_model["name"] = Metadata.id_to_title(model_full_name_component)
+ if org_component is not None:
+ base_model["organization"] = Metadata.id_to_title(org_component)
+ if version is not None:
+ base_model["version"] = version
+
+ else:
+ # Likely a Hugging Face ID
+ model_full_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(model_id, total_params)
+
+ # Populate model dictionary with extracted components
+ if model_full_name_component is not None:
+ base_model["name"] = Metadata.id_to_title(model_full_name_component)
+ if org_component is not None:
+ base_model["organization"] = Metadata.id_to_title(org_component)
+ if version is not None:
+ base_model["version"] = version
+ if org_component is not None and model_full_name_component is not None:
+ base_model["repo_url"] = f"https://huggingface.co/{org_component}/{model_full_name_component}"
+
+ elif isinstance(model_id, dict):
+ base_model = model_id
+
+ else:
+ logger.error(f"base model entry '{str(model_id)}' not in a known format")
+
+ metadata.base_models.append(base_model)
+
+ if "datasets" in model_card or "dataset" in model_card or "dataset_sources" in model_card:
+ # This represents the datasets that this was trained from
+ metadata_datasets = []
+ dataset_value = model_card.get("datasets", model_card.get("dataset", model_card.get("dataset_sources", None)))
+
+ if dataset_value is not None:
+ if isinstance(dataset_value, str):
+ metadata_datasets.append(dataset_value)
+ elif isinstance(dataset_value, list):
+ metadata_datasets.extend(dataset_value)
+
+ if metadata.datasets is None:
+ metadata.datasets = []
+
+ for dataset_id in metadata_datasets:
+ # NOTE: model size of base model is assumed to be similar to the size of the current model
+ dataset = {}
+ if isinstance(dataset_id, str):
+ if dataset_id.startswith(("http://", "https://", "ssh://")):
+ dataset["repo_url"] = dataset_id
+
+ # Check if Hugging Face ID is present in URL
+ if "huggingface.co" in dataset_id:
+ match = re.match(r"https?://huggingface.co/([^/]+/[^/]+)$", dataset_id)
+ if match:
+ dataset_id_component = match.group(1)
+ dataset_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(dataset_id_component, total_params)
+
+ # Populate dataset dictionary with extracted components
+ if dataset_name_component is not None:
+ dataset["name"] = Metadata.id_to_title(dataset_name_component)
+ if org_component is not None:
+ dataset["organization"] = Metadata.id_to_title(org_component)
+ if version is not None:
+ dataset["version"] = version
+
+ else:
+ # Likely a Hugging Face ID
+ dataset_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(dataset_id, total_params)
+
+ # Populate dataset dictionary with extracted components
+ if dataset_name_component is not None:
+ dataset["name"] = Metadata.id_to_title(dataset_name_component)
+ if org_component is not None:
+ dataset["organization"] = Metadata.id_to_title(org_component)
+ if version is not None:
+ dataset["version"] = version
+ if org_component is not None and dataset_name_component is not None:
+ dataset["repo_url"] = f"https://huggingface.co/{org_component}/{dataset_name_component}"
+
+ elif isinstance(dataset_id, dict):
+ dataset = dataset_id
+
+ else:
+ logger.error(f"dataset entry '{str(dataset_id)}' not in a known format")
+
+ metadata.datasets.append(dataset)
+
+ use_model_card_metadata("license", "license")
+ use_model_card_metadata("license_name", "license_name")
+ use_model_card_metadata("license_link", "license_link")
+
+ use_array_model_card_metadata("tags", "tags")
+ use_array_model_card_metadata("tags", "pipeline_tag")
+
+ use_array_model_card_metadata("languages", "languages")
+ use_array_model_card_metadata("languages", "language")
+
+ # Hugging Face Parameter Heuristics
+ ####################################
+
+ if hf_params is not None:
+
+ hf_name_or_path = hf_params.get("_name_or_path")
+ if hf_name_or_path is not None and hf_name_or_path.count('/') <= 1:
+ # Use _name_or_path only if its actually a model name and not some computer path
+ # e.g. 'meta-llama/Llama-2-7b-hf'
+ model_id = hf_name_or_path
+ model_full_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(model_id, total_params)
+ if metadata.name is None and model_full_name_component is not None:
+ metadata.name = Metadata.id_to_title(model_full_name_component)
+ if metadata.organization is None and org_component is not None:
+ metadata.organization = Metadata.id_to_title(org_component)
+ if metadata.basename is None and basename is not None:
+ metadata.basename = basename
+ if metadata.finetune is None and finetune is not None:
+ metadata.finetune = finetune
+ if metadata.version is None and version is not None:
+ metadata.version = version
+ if metadata.size_label is None and size_label is not None:
+ metadata.size_label = size_label
+
+ # Directory Folder Name Fallback Heuristics
+ ############################################
+ if model_path is not None:
+ model_id = model_path.name
+ model_full_name_component, org_component, basename, finetune, version, size_label = Metadata.get_model_id_components(model_id, total_params)
+ if metadata.name is None and model_full_name_component is not None:
+ metadata.name = Metadata.id_to_title(model_full_name_component)
+ if metadata.organization is None and org_component is not None:
+ metadata.organization = Metadata.id_to_title(org_component)
+ if metadata.basename is None and basename is not None:
+ metadata.basename = basename
+ if metadata.finetune is None and finetune is not None:
+ metadata.finetune = finetune
+ if metadata.version is None and version is not None:
+ metadata.version = version
+ if metadata.size_label is None and size_label is not None:
+ metadata.size_label = size_label
+
+ return metadata
+
+ def set_gguf_meta_model(self, gguf_writer: gguf.GGUFWriter):
+ assert self.name is not None
+ gguf_writer.add_name(self.name)
+
+ if self.author is not None:
+ gguf_writer.add_author(self.author)
+ if self.version is not None:
+ gguf_writer.add_version(self.version)
+ if self.organization is not None:
+ gguf_writer.add_organization(self.organization)
+
+ if self.finetune is not None:
+ gguf_writer.add_finetune(self.finetune)
+ if self.basename is not None:
+ gguf_writer.add_basename(self.basename)
+
+ if self.description is not None:
+ gguf_writer.add_description(self.description)
+ if self.quantized_by is not None:
+ gguf_writer.add_quantized_by(self.quantized_by)
+
+ if self.size_label is not None:
+ gguf_writer.add_size_label(self.size_label)
+
+ if self.license is not None:
+ if isinstance(self.license, list):
+ gguf_writer.add_license(",".join(self.license))
+ else:
+ gguf_writer.add_license(self.license)
+ if self.license_name is not None:
+ gguf_writer.add_license_name(self.license_name)
+ if self.license_link is not None:
+ gguf_writer.add_license_link(self.license_link)
+
+ if self.url is not None:
+ gguf_writer.add_url(self.url)
+ if self.doi is not None:
+ gguf_writer.add_doi(self.doi)
+ if self.uuid is not None:
+ gguf_writer.add_uuid(self.uuid)
+ if self.repo_url is not None:
+ gguf_writer.add_repo_url(self.repo_url)
+
+ if self.source_url is not None:
+ gguf_writer.add_source_url(self.source_url)
+ if self.source_doi is not None:
+ gguf_writer.add_source_doi(self.source_doi)
+ if self.source_uuid is not None:
+ gguf_writer.add_source_uuid(self.source_uuid)
+ if self.source_repo_url is not None:
+ gguf_writer.add_source_repo_url(self.source_repo_url)
+
+ if self.base_models is not None:
+ gguf_writer.add_base_model_count(len(self.base_models))
+ for key, base_model_entry in enumerate(self.base_models):
+ if "name" in base_model_entry:
+ gguf_writer.add_base_model_name(key, base_model_entry["name"])
+ if "author" in base_model_entry:
+ gguf_writer.add_base_model_author(key, base_model_entry["author"])
+ if "version" in base_model_entry:
+ gguf_writer.add_base_model_version(key, base_model_entry["version"])
+ if "organization" in base_model_entry:
+ gguf_writer.add_base_model_organization(key, base_model_entry["organization"])
+ if "description" in base_model_entry:
+ gguf_writer.add_base_model_description(key, base_model_entry["description"])
+ if "url" in base_model_entry:
+ gguf_writer.add_base_model_url(key, base_model_entry["url"])
+ if "doi" in base_model_entry:
+ gguf_writer.add_base_model_doi(key, base_model_entry["doi"])
+ if "uuid" in base_model_entry:
+ gguf_writer.add_base_model_uuid(key, base_model_entry["uuid"])
+ if "repo_url" in base_model_entry:
+ gguf_writer.add_base_model_repo_url(key, base_model_entry["repo_url"])
+
+ if self.datasets is not None:
+ gguf_writer.add_dataset_count(len(self.datasets))
+ for key, dataset_entry in enumerate(self.datasets):
+ if "name" in dataset_entry:
+ gguf_writer.add_dataset_name(key, dataset_entry["name"])
+ if "author" in dataset_entry:
+ gguf_writer.add_dataset_author(key, dataset_entry["author"])
+ if "version" in dataset_entry:
+ gguf_writer.add_dataset_version(key, dataset_entry["version"])
+ if "organization" in dataset_entry:
+ gguf_writer.add_dataset_organization(key, dataset_entry["organization"])
+ if "description" in dataset_entry:
+ gguf_writer.add_dataset_description(key, dataset_entry["description"])
+ if "url" in dataset_entry:
+ gguf_writer.add_dataset_url(key, dataset_entry["url"])
+ if "doi" in dataset_entry:
+ gguf_writer.add_dataset_doi(key, dataset_entry["doi"])
+ if "uuid" in dataset_entry:
+ gguf_writer.add_dataset_uuid(key, dataset_entry["uuid"])
+ if "repo_url" in dataset_entry:
+ gguf_writer.add_dataset_repo_url(key, dataset_entry["repo_url"])
+
+ if self.tags is not None:
+ gguf_writer.add_tags(self.tags)
+ if self.languages is not None:
+ gguf_writer.add_languages(self.languages)
diff --git a/venv/lib/python3.10/site-packages/gguf/py.typed b/venv/lib/python3.10/site-packages/gguf/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/gguf/quants.py b/venv/lib/python3.10/site-packages/gguf/quants.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c8ba82e19d3d9e984ba39caf5cf865b0ee8e72a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/quants.py
@@ -0,0 +1,1269 @@
+from __future__ import annotations
+from abc import ABC, abstractmethod
+from typing import Any, Callable, Sequence
+from math import log2, ceil
+
+from numpy.typing import DTypeLike
+
+from .constants import GGML_QUANT_SIZES, GGMLQuantizationType, QK_K
+from .lazy import LazyNumpyTensor
+
+import numpy as np
+
+
+def quant_shape_to_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
+ if shape[-1] % block_size != 0:
+ raise ValueError(f"Quantized tensor row size ({shape[-1]}) is not a multiple of {quant_type.name} block size ({block_size})")
+ return (*shape[:-1], shape[-1] // block_size * type_size)
+
+
+def quant_shape_from_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
+ block_size, type_size = GGML_QUANT_SIZES[quant_type]
+ if shape[-1] % type_size != 0:
+ raise ValueError(f"Quantized tensor bytes per row ({shape[-1]}) is not a multiple of {quant_type.name} type size ({type_size})")
+ return (*shape[:-1], shape[-1] // type_size * block_size)
+
+
+# This is faster than np.vectorize and np.apply_along_axis because it works on more than one row at a time
+def _apply_over_grouped_rows(func: Callable[[np.ndarray], np.ndarray], arr: np.ndarray, otype: DTypeLike, oshape: tuple[int, ...]) -> np.ndarray:
+ rows = arr.reshape((-1, arr.shape[-1]))
+ osize = 1
+ for dim in oshape:
+ osize *= dim
+ out = np.empty(shape=osize, dtype=otype)
+ # compute over groups of 16 rows (arbitrary, but seems good for performance)
+ n_groups = (rows.shape[0] // 16) or 1
+ np.concatenate([func(group).ravel() for group in np.array_split(rows, n_groups)], axis=0, out=out)
+ return out.reshape(oshape)
+
+
+# round away from zero
+# ref: https://stackoverflow.com/a/59143326/22827863
+def np_roundf(n: np.ndarray) -> np.ndarray:
+ a = abs(n)
+ floored = np.floor(a)
+ b = floored + np.floor(2 * (a - floored))
+ return np.sign(n) * b
+
+
+class QuantError(Exception): ...
+
+
+_type_traits: dict[GGMLQuantizationType, type[__Quant]] = {}
+
+
+def quantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
+ if qtype == GGMLQuantizationType.F32:
+ return data.astype(np.float32, copy=False)
+ elif qtype == GGMLQuantizationType.F16:
+ return data.astype(np.float16, copy=False)
+ elif (q := _type_traits.get(qtype)) is not None:
+ return q.quantize(data)
+ else:
+ raise NotImplementedError(f"Quantization for {qtype.name} is not yet implemented")
+
+
+def dequantize(data: np.ndarray, qtype: GGMLQuantizationType) -> np.ndarray:
+ if qtype == GGMLQuantizationType.F32:
+ return data.view(np.float32)
+ elif qtype == GGMLQuantizationType.F16:
+ return data.view(np.float16).astype(np.float32)
+ elif (q := _type_traits.get(qtype)) is not None:
+ return q.dequantize(data)
+ else:
+ raise NotImplementedError(f"Dequantization for {qtype.name} is not yet implemented")
+
+
+class __Quant(ABC):
+ qtype: GGMLQuantizationType
+ block_size: int
+ type_size: int
+
+ grid: np.ndarray[Any, np.dtype[np.float32]] | None = None
+ grid_shape: tuple[int, int] = (0, 0)
+ grid_map: tuple[int | float, ...] = ()
+ grid_hex: bytes | None = None
+
+ def __init__(self):
+ return TypeError("Quant conversion classes can't have instances")
+
+ def __init_subclass__(cls, qtype: GGMLQuantizationType) -> None:
+ cls.qtype = qtype
+ cls.block_size, cls.type_size = GGML_QUANT_SIZES[qtype]
+ cls.__quantize_lazy = LazyNumpyTensor._wrap_fn(
+ cls.__quantize_array,
+ meta_noop=(np.uint8, cls.__shape_to_bytes)
+ )
+ cls.__dequantize_lazy = LazyNumpyTensor._wrap_fn(
+ cls.__dequantize_array,
+ meta_noop=(np.float32, cls.__shape_from_bytes)
+ )
+ assert qtype not in _type_traits
+ _type_traits[qtype] = cls
+
+ @classmethod
+ def init_grid(cls):
+ if cls.grid is not None or cls.grid_hex is None:
+ return
+
+ bits_per_elem = ceil(log2(len(cls.grid_map)))
+ assert bits_per_elem != 0, cls.qtype.name
+ elems_per_byte = 8 // bits_per_elem
+
+ grid = np.frombuffer(cls.grid_hex, dtype=np.uint8)
+ # decode hexadecimal chars from grid
+ grid = grid.reshape((-1, 2))
+ grid = (np.where(grid > 0x40, grid + 9, grid) & 0x0F) << np.array([4, 0], dtype=np.uint8).reshape((1, 2))
+ grid = grid[..., 0] | grid[..., 1]
+ # unpack the grid values
+ grid = grid.reshape((-1, 1)) >> np.array([i for i in range(0, 8, 8 // elems_per_byte)], dtype=np.uint8).reshape((1, elems_per_byte))
+ grid = (grid & ((1 << bits_per_elem) - 1)).reshape((-1, 1))
+ grid_map = np.array(cls.grid_map, dtype=np.float32).reshape((1, -1))
+ grid = np.take_along_axis(grid_map, grid, axis=-1)
+ cls.grid = grid.reshape((1, 1, *cls.grid_shape))
+
+ @classmethod
+ @abstractmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ raise NotImplementedError
+
+ @classmethod
+ @abstractmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ raise NotImplementedError
+
+ @classmethod
+ def quantize_rows(cls, rows: np.ndarray) -> np.ndarray:
+ rows = rows.astype(np.float32, copy=False)
+ shape = rows.shape
+ n_blocks = rows.size // cls.block_size
+ blocks = rows.reshape((n_blocks, cls.block_size))
+ blocks = cls.quantize_blocks(blocks)
+ assert blocks.dtype == np.uint8
+ assert blocks.shape[-1] == cls.type_size
+ return blocks.reshape(cls.__shape_to_bytes(shape))
+
+ @classmethod
+ def dequantize_rows(cls, rows: np.ndarray) -> np.ndarray:
+ rows = rows.view(np.uint8)
+ shape = rows.shape
+ n_blocks = rows.size // cls.type_size
+ blocks = rows.reshape((n_blocks, cls.type_size))
+ blocks = cls.dequantize_blocks(blocks)
+ assert blocks.dtype == np.float32
+ assert blocks.shape[-1] == cls.block_size
+ return blocks.reshape(cls.__shape_from_bytes(shape))
+
+ @classmethod
+ def __shape_to_bytes(cls, shape: Sequence[int]):
+ return quant_shape_to_byte_shape(shape, cls.qtype)
+
+ @classmethod
+ def __shape_from_bytes(cls, shape: Sequence[int]):
+ return quant_shape_from_byte_shape(shape, cls.qtype)
+
+ @classmethod
+ def __quantize_array(cls, array: np.ndarray) -> np.ndarray:
+ return _apply_over_grouped_rows(cls.quantize_rows, arr=array, otype=np.uint8, oshape=cls.__shape_to_bytes(array.shape))
+
+ @classmethod
+ def __dequantize_array(cls, array: np.ndarray) -> np.ndarray:
+ cls.init_grid()
+ return _apply_over_grouped_rows(cls.dequantize_rows, arr=array, otype=np.float32, oshape=cls.__shape_from_bytes(array.shape))
+
+ @classmethod
+ def __quantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
+ pass
+
+ @classmethod
+ def __dequantize_lazy(cls, lazy_tensor: LazyNumpyTensor, /) -> Any:
+ pass
+
+ @classmethod
+ def can_quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> bool:
+ return tensor.shape[-1] % cls.block_size == 0
+
+ @classmethod
+ def quantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
+ if not cls.can_quantize(tensor):
+ raise QuantError(f"Can't quantize tensor with shape {tensor.shape} to {cls.qtype.name}")
+ if isinstance(tensor, LazyNumpyTensor):
+ return cls.__quantize_lazy(tensor)
+ else:
+ return cls.__quantize_array(tensor)
+
+ @classmethod
+ def dequantize(cls, tensor: np.ndarray | LazyNumpyTensor) -> np.ndarray:
+ if isinstance(tensor, LazyNumpyTensor):
+ return cls.__dequantize_lazy(tensor)
+ else:
+ return cls.__dequantize_array(tensor)
+
+
+class BF16(__Quant, qtype=GGMLQuantizationType.BF16):
+ @classmethod
+ # same as ggml_compute_fp32_to_bf16 in ggml-impl.h
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n = blocks.view(np.uint32)
+ # force nan to quiet
+ n = np.where((n & 0x7fffffff) > 0x7f800000, (n & np.uint32(0xffff0000)) | np.uint32(64 << 16), n)
+ # round to nearest even
+ n = (np.uint64(n) + (0x7fff + ((n >> 16) & 1))) >> 16
+ return n.astype(np.uint16).view(np.uint8)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ return (blocks.view(np.int16).astype(np.int32) << 16).view(np.float32)
+
+
+class Q4_0(__Quant, qtype=GGMLQuantizationType.Q4_0):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ imax = abs(blocks).argmax(axis=-1, keepdims=True)
+ max = np.take_along_axis(blocks, imax, axis=-1)
+
+ d = max / -8
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ # FIXME: Q4_0's reference rounding is cursed and depends on FMA
+ qs = np.trunc((np.float64(blocks) * np.float64(id)) + np.float64(8.5), dtype=np.float32).astype(np.uint8).clip(0, 15)
+
+ qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
+ qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
+
+ d = d.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([d, qs], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, qs = np.hsplit(blocks, [2])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.int8) - np.int8(8)
+
+ return (d * qs.astype(np.float32))
+
+
+class Q4_1(__Quant, qtype=GGMLQuantizationType.Q4_1):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ max = blocks.max(axis=-1, keepdims=True)
+ min = blocks.min(axis=-1, keepdims=True)
+
+ d = (max - min) / 15
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ qs = np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32).astype(np.uint8).clip(0, 15)
+
+ qs = qs.reshape((n_blocks, 2, cls.block_size // 2))
+ qs = qs[..., 0, :] | (qs[..., 1, :] << np.uint8(4))
+
+ d = d.astype(np.float16).view(np.uint8)
+ m = min.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([d, m, qs], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ m, qs = np.hsplit(rest, [2])
+
+ d = d.view(np.float16).astype(np.float32)
+ m = m.view(np.float16).astype(np.float32)
+
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.float32)
+
+ return (d * qs) + m
+
+
+class Q5_0(__Quant, qtype=GGMLQuantizationType.Q5_0):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ imax = abs(blocks).argmax(axis=-1, keepdims=True)
+ max = np.take_along_axis(blocks, imax, axis=-1)
+
+ d = max / -16
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ # FIXME: Q5_0's reference rounding is cursed and depends on FMA
+ q = np.trunc((np.float64(blocks) * np.float64(id)) + np.float64(16.5), dtype=np.float32).astype(np.uint8).clip(0, 31)
+
+ qs = q.reshape((n_blocks, 2, cls.block_size // 2))
+ qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
+
+ qh = np.packbits(q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little").reshape(n_blocks, 4)
+
+ d = d.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([d, qh, qs], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qh, qs = np.hsplit(rest, [4])
+
+ d = d.view(np.float16).astype(np.float32)
+ qh = qh.view(np.uint32)
+
+ qh = qh.reshape((n_blocks, 1)) >> np.array([i for i in range(32)], dtype=np.uint32).reshape((1, 32))
+ ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qh = (qh & np.uint32(0x01)).astype(np.uint8)
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
+
+ qs = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(16)
+
+ return (d * qs.astype(np.float32))
+
+
+class Q5_1(__Quant, qtype=GGMLQuantizationType.Q5_1):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ max = blocks.max(axis=-1, keepdims=True)
+ min = blocks.min(axis=-1, keepdims=True)
+
+ d = (max - min) / 31
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ q = np.trunc((blocks - min) * id + np.float32(0.5), dtype=np.float32).astype(np.uint8).clip(0, 31)
+
+ qs = q.reshape((n_blocks, 2, cls.block_size // 2))
+ qs = (qs[..., 0, :] & np.uint8(0x0F)) | (qs[..., 1, :] << np.uint8(4))
+
+ qh = np.packbits(q.reshape((n_blocks, 1, 32)) >> np.uint8(4), axis=-1, bitorder="little").reshape(n_blocks, 4)
+
+ d = d.astype(np.float16).view(np.uint8)
+ m = min.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([d, m, qh, qs], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ m, rest = np.hsplit(rest, [2])
+ qh, qs = np.hsplit(rest, [4])
+
+ d = d.view(np.float16).astype(np.float32)
+ m = m.view(np.float16).astype(np.float32)
+ qh = qh.view(np.uint32)
+
+ qh = qh.reshape((n_blocks, 1)) >> np.array([i for i in range(32)], dtype=np.uint32).reshape((1, 32))
+ ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qh = (qh & np.uint32(0x01)).astype(np.uint8)
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1))
+
+ qs = (ql | (qh << np.uint8(4))).astype(np.float32)
+
+ return (d * qs) + m
+
+
+class Q8_0(__Quant, qtype=GGMLQuantizationType.Q8_0):
+ @classmethod
+ # Implementation of Q8_0 with bit-exact same results as reference implementation in ggml-quants.c
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+
+ d = abs(blocks).max(axis=1, keepdims=True) / 127
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ qs = np_roundf(blocks * id)
+
+ # (n_blocks, 2)
+ d = d.astype(np.float16).view(np.uint8)
+ # (n_blocks, block_size)
+ qs = qs.astype(np.int8).view(np.uint8)
+
+ return np.concatenate([d, qs], axis=1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ d, x = np.split(blocks, [2], axis=1)
+ d = d.view(np.float16).astype(np.float32)
+ x = x.view(np.int8).astype(np.float32)
+
+ return (x * d)
+
+
+class Q2_K(__Quant, qtype=GGMLQuantizationType.Q2_K):
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ scales, rest = np.hsplit(blocks, [QK_K // 16])
+ qs, rest = np.hsplit(rest, [QK_K // 4])
+ d, dmin = np.hsplit(rest, [2])
+
+ d = d.view(np.float16).astype(np.float32)
+ dmin = dmin.view(np.float16).astype(np.float32)
+
+ # (n_blocks, 16, 1)
+ dl = (d * (scales & 0xF).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
+ ml = (dmin * (scales >> 4).astype(np.float32)).reshape((n_blocks, QK_K // 16, 1))
+
+ shift = np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
+
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & np.uint8(3)
+
+ qs = qs.reshape((n_blocks, QK_K // 16, 16)).astype(np.float32)
+
+ qs = dl * qs - ml
+
+ return qs.reshape((n_blocks, -1))
+
+
+class Q3_K(__Quant, qtype=GGMLQuantizationType.Q3_K):
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ hmask, rest = np.hsplit(blocks, [QK_K // 8])
+ qs, rest = np.hsplit(rest, [QK_K // 4])
+ scales, d = np.hsplit(rest, [12])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ # The scales are packed at 6-bit each in this pattern:
+ # 0: IIIIAAAA
+ # 1: JJJJBBBB
+ # 2: KKKKCCCC
+ # 3: LLLLDDDD
+ # 4: MMMMEEEE
+ # 5: NNNNFFFF
+ # 6: OOOOGGGG
+ # 7: PPPPHHHH
+ # 8: MMIIEEAA
+ # 9: NNJJFFBB
+ # 10: OOKKGGCC
+ # 11: PPLLHHDD
+ lscales, hscales = np.hsplit(scales, [8])
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 2, 1))
+ lscales = lscales.reshape((n_blocks, 16))
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 4, 1))
+ hscales = hscales.reshape((n_blocks, 16))
+ scales = (lscales & np.uint8(0x0F)) | ((hscales & np.uint8(0x03)) << np.uint8(4))
+ scales = (scales.astype(np.int8) - np.int8(32)).astype(np.float32)
+
+ dl = (d * scales).reshape((n_blocks, 16, 1))
+
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1))
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(3)
+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(1))
+ qh = qh ^ np.uint8(1) # strangely, the offset is zero when the bitmask is 1
+ q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(np.float32)
+
+ return (dl * q).reshape((n_blocks, QK_K))
+
+
+class Q4_K(__Quant, qtype=GGMLQuantizationType.Q4_K):
+ K_SCALE_SIZE = 12
+
+ @staticmethod
+ def get_scale_min(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ n_blocks = scales.shape[0]
+ scales = scales.view(np.uint8)
+ ### Unpacking the following: ###
+ # 0 EEAAAAAA
+ # 1 FFBBBBBB
+ # 2 GGCCCCCC
+ # 3 HHDDDDDD
+ # 4 eeaaaaaa
+ # 5 ffbbbbbb
+ # 6 ggcccccc
+ # 7 hhdddddd
+ # 8 eeeeEEEE
+ # 9 ffffFFFF
+ # 10 ggggGGGG
+ # 11 hhhhHHHH
+ scales = scales.reshape((n_blocks, 3, 4))
+ d, m, m_d = np.split(scales, 3, axis=-2)
+
+ sc = np.concatenate([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], axis=-1)
+ min = np.concatenate([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], axis=-1)
+
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ dmin, rest = np.hsplit(rest, [2])
+ scales, qs = np.hsplit(rest, [cls.K_SCALE_SIZE])
+
+ d = d.view(np.float16).astype(np.float32)
+ dmin = dmin.view(np.float16).astype(np.float32)
+
+ sc, m = Q4_K.get_scale_min(scales)
+
+ d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
+ dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
+
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 32)).astype(np.float32)
+
+ return (d * qs - dm).reshape((n_blocks, QK_K))
+
+
+class Q5_K(__Quant, qtype=GGMLQuantizationType.Q5_K):
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ dmin, rest = np.hsplit(rest, [2])
+ scales, rest = np.hsplit(rest, [Q4_K.K_SCALE_SIZE])
+ qh, qs = np.hsplit(rest, [QK_K // 8])
+
+ d = d.view(np.float16).astype(np.float32)
+ dmin = dmin.view(np.float16).astype(np.float32)
+
+ sc, m = Q4_K.get_scale_min(scales)
+
+ d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1))
+ dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1))
+
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1))
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
+ qh = (qh & np.uint8(0x01)).reshape((n_blocks, -1, 32))
+ q = (ql | (qh << np.uint8(4))).astype(np.float32)
+
+ return (d * q - dm).reshape((n_blocks, QK_K))
+
+
+class Q6_K(__Quant, qtype=GGMLQuantizationType.Q6_K):
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ ql, rest = np.hsplit(blocks, [QK_K // 2])
+ qh, rest = np.hsplit(rest, [QK_K // 4])
+ scales, d = np.hsplit(rest, [QK_K // 16])
+
+ scales = scales.view(np.int8).astype(np.float32)
+ d = d.view(np.float16).astype(np.float32)
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
+
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32))
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qh = (qh & np.uint8(0x03)).reshape((n_blocks, -1, 32))
+ q = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(32)
+ q = q.reshape((n_blocks, QK_K // 16, -1)).astype(np.float32)
+
+ return (d * q).reshape((n_blocks, QK_K))
+
+
+class TQ1_0(__Quant, qtype=GGMLQuantizationType.TQ1_0):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d = abs(blocks).max(axis=-1, keepdims=True)
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ qs = np_roundf(blocks * id)
+ qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
+
+ qs0, qs1, qh = qs[..., :(32 * 5)], qs[..., (32 * 5):(48 * 5)], qs[..., (48 * 5):]
+ qs0 = qs0.reshape((n_blocks, -1, 5, 32)) * np.array([81, 27, 9, 3, 1], dtype=np.uint8).reshape((1, 1, 5, 1))
+ qs0 = np.sum(qs0, axis=-2).reshape((n_blocks, -1))
+ qs1 = qs1.reshape((n_blocks, -1, 5, 16)) * np.array([81, 27, 9, 3, 1], dtype=np.uint8).reshape((1, 1, 5, 1))
+ qs1 = np.sum(qs1, axis=-2).reshape((n_blocks, -1))
+ qh = qh.reshape((n_blocks, -1, 4, 4)) * np.array([81, 27, 9, 3], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qh = np.sum(qh, axis=-2).reshape((n_blocks, -1))
+ qs = np.concatenate([qs0, qs1, qh], axis=-1)
+ qs = (qs.astype(np.uint16) * 256 + (243 - 1)) // 243
+
+ qs = qs.astype(np.uint8)
+ d = d.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([qs, d], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ qs, rest = np.hsplit(blocks, [(QK_K - 4 * QK_K // 64) // 5])
+ qh, d = np.hsplit(rest, [QK_K // 64])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ qs0, qs1 = qs[..., :32], qs[..., 32:]
+ qs0 = qs0.reshape((n_blocks, -1, 1, 32)) * np.array([1, 3, 9, 27, 81], dtype=np.uint8).reshape((1, 1, 5, 1))
+ qs0 = qs0.reshape((n_blocks, -1))
+ qs1 = qs1.reshape((n_blocks, -1, 1, 16)) * np.array([1, 3, 9, 27, 81], dtype=np.uint8).reshape((1, 1, 5, 1))
+ qs1 = qs1.reshape((n_blocks, -1))
+ qh = qh.reshape((n_blocks, -1, 1, 4)) * np.array([1, 3, 9, 27], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qh = qh.reshape((n_blocks, -1))
+ qs = np.concatenate([qs0, qs1, qh], axis=-1)
+ qs = ((qs.astype(np.uint16) * 3) >> 8).astype(np.int8) - np.int8(1)
+
+ return (d * qs.astype(np.float32))
+
+
+class TQ2_0(__Quant, qtype=GGMLQuantizationType.TQ2_0):
+ @classmethod
+ def quantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d = abs(blocks).max(axis=-1, keepdims=True)
+ with np.errstate(divide="ignore"):
+ id = np.where(d == 0, 0, 1 / d)
+ qs = np_roundf(blocks * id)
+ qs = (qs.astype(np.int8) + np.int8(1)).astype(np.uint8)
+
+ qs = qs.reshape((n_blocks, -1, 4, 32)) << np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qs = qs[..., 0, :] | qs[..., 1, :] | qs[..., 2, :] | qs[..., 3, :]
+ qs = qs.reshape((n_blocks, -1))
+
+ d = d.astype(np.float16).view(np.uint8)
+
+ return np.concatenate([qs, d], axis=-1)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ qs, d = np.hsplit(blocks, [QK_K // 4])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1))
+ qs = (qs & 0x03).reshape((n_blocks, -1)).astype(np.int8) - np.int8(1)
+
+ return (d * qs.astype(np.float32))
+
+
+class IQ2_XXS(__Quant, qtype=GGMLQuantizationType.IQ2_XXS):
+ ksigns: bytes = (
+ b"\x00\x81\x82\x03\x84\x05\x06\x87\x88\x09\x0a\x8b\x0c\x8d\x8e\x0f"
+ b"\x90\x11\x12\x93\x14\x95\x96\x17\x18\x99\x9a\x1b\x9c\x1d\x1e\x9f"
+ b"\xa0\x21\x22\xa3\x24\xa5\xa6\x27\x28\xa9\xaa\x2b\xac\x2d\x2e\xaf"
+ b"\x30\xb1\xb2\x33\xb4\x35\x36\xb7\xb8\x39\x3a\xbb\x3c\xbd\xbe\x3f"
+ b"\xc0\x41\x42\xc3\x44\xc5\xc6\x47\x48\xc9\xca\x4b\xcc\x4d\x4e\xcf"
+ b"\x50\xd1\xd2\x53\xd4\x55\x56\xd7\xd8\x59\x5a\xdb\x5c\xdd\xde\x5f"
+ b"\x60\xe1\xe2\x63\xe4\x65\x66\xe7\xe8\x69\x6a\xeb\x6c\xed\xee\x6f"
+ b"\xf0\x71\x72\xf3\x74\xf5\xf6\x77\x78\xf9\xfa\x7b\xfc\x7d\x7e\xff"
+ )
+
+ # iq2xxs_grid, but with each byte of the original packed in 2 bits,
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
+ grid_shape = (256, 8)
+ grid_map = (0x08, 0x19, 0x2b)
+ grid_hex = (
+ b"00000200050008000a00110014002000220028002a0041004400500058006100"
+ b"6400800082008a00a20001010401100115014001840198010002020222028202"
+ b"010404041004210424044004420448046004810484049004a404000502050805"
+ b"200546056905800591050906100640068406a406000805080808140828084108"
+ b"440850085208880804094009020a140a01100410101021104010601084109010"
+ b"951000110811201150115a118011241245120014081420142514491480141815"
+ b"6215001616160118041810184018811800190519a019511a002002200a204420"
+ b"6120802082202921482100220222012404241024402456240025412564259026"
+ b"082820289428442a014004401040184021402440404048405640604081408440"
+ b"9040004120416141804185410142104248425642684200440844204480449944"
+ b"124524450046014804481048404845480049584961498249454a904a00500850"
+ b"1150195020508050885004514251a4519152905492540a550156545600581158"
+ b"195864584059085a046010604060686000615561186260620064056410651265"
+ b"84654268008002800a8041808280048118814081118201840484108415844084"
+ b"608400854685948509864086608602880489118a0490109024904090a1901691"
+ b"8091459200942294449451958198209902a050a085a009a100a218a450a804a9"
+ )
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, qs = np.hsplit(blocks, [2])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ qs = qs.view(np.uint32).reshape(n_blocks, -1, 2)
+
+ db = d * (np.float32(0.5) + (qs[..., 1] >> 28).astype(np.float32)) * np.float32(0.25)
+ db = db.reshape((n_blocks, -1, 1, 1))
+
+ # get the sign indices and unpack the bits
+ signs = qs[..., 1].reshape((n_blocks, -1, 1)) >> np.array([0, 7, 14, 21], dtype=np.uint32).reshape((1, 1, 4))
+ ksigns = np.frombuffer(cls.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
+ signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
+ signs = np.take_along_axis(ksigns, signs, axis=-1)
+ signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 1, 8))
+ signs = signs & np.uint8(0x01)
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
+ signs = signs.reshape((n_blocks, -1, 4, 8))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs[..., 0].copy().view(np.uint8).reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 4, 8))
+
+ return (db * grid * signs).reshape((n_blocks, -1))
+
+
+class IQ2_XS(__Quant, qtype=GGMLQuantizationType.IQ2_XS):
+ # iq2xs_grid, but with each byte of the original packed in 2 bits,
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
+ grid_shape = (512, 8)
+ grid_map = (0x08, 0x19, 0x2b)
+ grid_hex = (
+ b"00000200050008000a0011001400160019002000220025002800410044004600"
+ b"49005000520055005800610064008000820085008800910094009900a0000101"
+ b"04010601090110011201150118011a0121012401400142014501480151015401"
+ b"6001680181018401900100020202050208021102140220024102440250025502"
+ b"80028a0201040404060409041004120415041804210424044004420445044804"
+ b"5104540456046004810484049004000502050505080511051405200541054405"
+ b"500561058005010604061006260640064206840600080208050808080a081108"
+ b"14082008250841084408500858088008a008aa08010904091009400981098909"
+ b"000a200a280a960aa00a01100410061009101010121015101810211024104010"
+ b"4210451048105110541060106a10811084109010001102110511081111111411"
+ b"2011411144115011801194119611011204120612101240126012001402140514"
+ b"0814111414142014411444144914501464148014011504151015401500161416"
+ b"49160118041810181218401854188618001905196619511aa91a002002200520"
+ b"08200a201120142020204120442050208020a020012104211021402148216521"
+ b"002222228022a82201240424102429244024002541255225992501261a26a626"
+ b"002808280a28202855288828a22868299029082a202a822a882a8a2a01400440"
+ b"0640094010401240154018402140244040404240454048404a40514054406040"
+ b"6540814084409040004102410541084111411441204141414441504180418541"
+ b"a241014204421042124229424042004402440544084411441444194420444144"
+ b"4444504480449444014504451045244540459a4500460a464446504601480448"
+ b"1048404845485448624800491149444950496949044a00500250055008501150"
+ b"145020502850415044505050805001510451105115514051425100524452aa52"
+ b"0154045410542154405460548154a154005508558055885521566856a1560058"
+ b"14584158505899581a5940594259855a0160046010604060546062608660a960"
+ b"006124624a62926200641664106540654565a46501686a682569066a546a626a"
+ b"00800280058008801180148020802a8041804480508080808280a880aa800181"
+ b"0481068110814081518159810082208280828282a082a8820184048410841284"
+ b"158440846084898400854485a58518866a860088088825885a8880888288a888"
+ b"0689228a808a888a968aa88a0190049010904090569084900091229164915692"
+ b"89920094059444945094589429959095929541965198a6984999159a609a00a0"
+ b"02a008a00aa020a02aa0a0a051a159a1a6a100a202a208a22aa280a2a0a240a4"
+ b"95a465a698a60aa820a822a828a8a0a8a8a804a984a986a928aa2aaa91aaaaaa"
+ )
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qs, scales = np.hsplit(rest, [2 * QK_K // 8])
+
+ d = d.view(np.float16).astype(np.float32)
+ qs = qs.view(np.uint16)
+
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
+ db = d * (np.float32(0.5) + scales) * np.float32(0.25)
+ db = db.reshape((n_blocks, -1, 1, 1))
+
+ # get the sign indices and unpack the bits
+ signs = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape(1, 1, 128)
+ signs = np.take_along_axis(signs, (qs >> 9).reshape((n_blocks, -1, 1)), axis=-1)
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
+ signs = signs & np.uint8(0x01)
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
+ signs = signs.reshape((n_blocks, -1, 2, 8))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, (qs & np.uint16(511)).reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 2, 8))
+
+ return (db * grid * signs).reshape((n_blocks, -1))
+
+
+class IQ2_S(__Quant, qtype=GGMLQuantizationType.IQ2_S):
+ # iq2s_grid, but with each byte of the original packed in 2 bits,
+ # by mapping 0x08 to 0, 0x19 to 1, and 0x2b to 2.
+ grid_shape = (1024, 8)
+ grid_map = (0x08, 0x19, 0x2b)
+ grid_hex = (
+ b"00000200050008000a0011001400160019002000220025002800410044004600"
+ b"490050005200550058006100640066006900800082008500880091009400a000"
+ b"a500aa0001010401060109011001120115011801210124014001420145014801"
+ b"510154015601590160016501680181018401900192019501a101a40100020202"
+ b"050208021102140220022a02410244024602490250025502800285028a029402"
+ b"a202010404040604090410041204150418042104240426042904400442044504"
+ b"48044a0451045404560459046004620465048104840486048904900495049804"
+ b"a104a40400050205050508050a05110514051605190520052505280541054405"
+ b"46054905500552055505580561056405800582058505880591059405a0050106"
+ b"0406060609061006150640064506480651065406600681068406900600080208"
+ b"050808081108140816081908200825082a084108440846084908500852085508"
+ b"580861086408800885089408aa08010904091009120915091809210940094509"
+ b"480951095409600981099009000a110a140a220a280a2a0a500a990a01100410"
+ b"0610091010101210151018102110241026104010421045104810511054105610"
+ b"59106010621065106810811084108610901095109810a110a410001102110511"
+ b"08110a1111111411161119112011221125112811411144114611491150115211"
+ b"5511581161116411801182118511881191119411011204120912101215122112"
+ b"2412401245125112541281128412901200140214051408141114141416141914"
+ b"2014251428144114441446144914501452145514581461146414801482148514"
+ b"881491149414a014011504150615091510151215151518152115241540154215"
+ b"4515481551155415601581158415901500160516081611161416201641164416"
+ b"50168016aa160118041806180918101815181818211840184218451848185118"
+ b"541860188118841800190219051908191119141920194119441950196919a219"
+ b"041a101a401a561a00200220052008201120142016201920202025202a204120"
+ b"4420502052205520642080208a209420aa200121042110211221152121214021"
+ b"4221452151215421602181218421902100220a22222228222a22442250228822"
+ b"8a22a82201240424062409241024152418242124242440244224452448245124"
+ b"5424602481248424902400250525082511251425202541254425502566258025"
+ b"0126042610264026592600280528112814284128442850288a28aa2801290429"
+ b"102995290a2a222a642a882a8a2a014004400640094010401240154018401a40"
+ b"21402440264040404240454048404a4051405440564059406040624065408140"
+ b"8440904095409840a140a4400041024105410841114114411641194120412241"
+ b"2541414144414641494150415241554158416141644180418241854188419141"
+ b"9441a04101420442104212421542184224424042454248425142544260428142"
+ b"844200440244054408440a441144144416441944204422442544284441444444"
+ b"46444944504452445544584461446444804482448544884491449444a0440145"
+ b"0445064509451045124515451845214524454045424545454845514554456045"
+ b"6a4581458445904500460246054608461146144620464146444650468046a546"
+ b"0148044809481048124815481848214824484048424845484848514854486048"
+ b"84489048004902490549084911491449204941494449504980499649014a044a"
+ b"104a404a00500250055008501150145016501950205022502550285041504450"
+ b"4650495050505250555058506150645080508250855088509150945001510451"
+ b"0651095110511251155118512151245140514251455148515151545160518151"
+ b"8451905100520552085211521452205241524452505269528052015404540654"
+ b"0954105412541554185421542454405442544554485451545454605481548454"
+ b"9054005502550555085511551455205541554455505580550156045610562656"
+ b"405600580258055808581158145820584158445850585a588058015904591059"
+ b"4059005a195a855aa85a01600460066010601260156018602160246040604560"
+ b"4860516054606060846090600061026105610861116114612061416144615061"
+ b"806199610462106240625662a162006405640864116414642064416444645064"
+ b"806401650465106540654a656865926500669466016804681068656898680069"
+ b"2a69426aa16a0080028005800880118014801980208025804180448050805280"
+ b"5580588061808080858091809480018104810981108112811581188121812481"
+ b"408142814581488151815481818184819081a981008205820a82118214824182"
+ b"4482508201840484068409841084128415841884218440844284458448845184"
+ b"5484608481848484908400850285058508851185148520854185448550858085"
+ b"8a85018604861086298640860088058811881488418844885088a28801890489"
+ b"40896589228a588a5a8a828aa28a019004900990109012901590189024904090"
+ b"4290459048905190549060908190849090900091059111911491419144915091"
+ b"5a910192049210924092a6920094029405940894119414942094419444945094"
+ b"8094969401950495109540959895a19500964696649601980498109826984098"
+ b"a998009949995299909a00a005a00aa014a022a02aa041a044a050a0a2a0aaa0"
+ b"40a165a102a20aa222a228a22aa282a288a28aa2a8a201a404a410a440a489a4"
+ b"a4a400a519a551a60aa828a8a2a854a986a908aa0aaa20aa22aa28aa88aaaaaa"
+ )
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qs, rest = np.hsplit(rest, [QK_K // 8])
+ signs, rest = np.hsplit(rest, [QK_K // 8])
+ qh, scales = np.hsplit(rest, [QK_K // 32])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
+ db = d * (np.float32(0.5) + scales) * np.float32(0.25)
+ db = db.reshape((n_blocks, -1, 1, 1))
+
+ # unpack the sign bits
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
+ signs = signs & np.uint8(0x01)
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
+ signs = signs.reshape((n_blocks, -1, 2, 8))
+
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4))
+ qs = qs.astype(np.uint16) | ((qh & 0x03).astype(np.uint16) << 8).reshape((n_blocks, -1))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 2, 8))
+
+ return (db * grid * signs).reshape((n_blocks, -1))
+
+
+class IQ3_XXS(__Quant, qtype=GGMLQuantizationType.IQ3_XXS):
+ grid_shape = (256, 4)
+ grid_map = (0x04, 0x0c, 0x14, 0x1c, 0x24, 0x2c, 0x34, 0x3e)
+ grid_hex = (
+ b"0000020004001100130017002000220031004200730075000101030110011201"
+ b"2101250130013201410154017001000202020402110220022202310233023702"
+ b"5102570275020103070310031203250370031304370444045704730475040105"
+ b"0705320552053506640610071407160743076107011003101010121021102310"
+ b"3010321034104710501000110211111120112211011203121012121221123012"
+ b"7212001302132013311346136613011405145014201524154615711505162217"
+ b"4017002002201120132020202220262031204220012103210521102112212121"
+ b"3021632167217021002202221122172220222222372240225522012310231423"
+ b"7023742335245324032527254125742501270327162745270130103012302130"
+ b"2330503065307230003102312031313144314631013203321032253252327232"
+ b"1133333330344734723400350635223555351436363663363337603704401740"
+ b"3540374053405740744120423742404260426642074345430444514464442545"
+ b"4345704505471047124730471250415070500051065126515551145232527252"
+ b"0253535310542354275472540255315550562457425724604460466064602161"
+ b"6161176264623063366344640565526533660367216703700570077010703270"
+ b"5270267140711272457252720073157333736073217441740075027524753076"
+ )
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qs, scales = np.hsplit(rest, [QK_K // 4])
+
+ d = d.view(np.float16).astype(np.float32)
+ scales = scales.view(np.uint32)
+
+ db = d * (np.float32(0.5) + (scales >> 28).astype(np.float32)) * np.float32(0.5)
+ db = db.reshape((n_blocks, -1, 1, 1))
+
+ # get the sign indices and unpack the bits
+ signs = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 7, 14, 21], dtype=np.uint32).reshape((1, 1, 4))
+ ksigns = np.frombuffer(IQ2_XXS.ksigns, dtype=np.uint8).reshape((1, 1, 1, 128))
+ signs = (signs & np.uint32(0x7F)).reshape((n_blocks, -1, 4, 1))
+ signs = np.take_along_axis(ksigns, signs, axis=-1)
+ signs = signs.reshape((n_blocks, -1, 4, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 1, 8))
+ signs = signs & np.uint8(0x01)
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
+ signs = signs.reshape((n_blocks, -1, 4, 8))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 4, 8))
+
+ return (db * grid * signs).reshape((n_blocks, -1))
+
+
+class IQ3_S(__Quant, qtype=GGMLQuantizationType.IQ3_S):
+ grid_shape = (512, 4)
+ grid_map = (0x01, 0x03, 0x05, 0x07, 0x09, 0x0b, 0x0d, 0x0f)
+ grid_hex = (
+ b"0000010002000500070010001100120014001600200021002500330040004200"
+ b"4500470051005300600062007100740077000001010102010401100111011501"
+ b"2001230127013101350144016101650172010002010205020702100213021602"
+ b"2102250230023402420245024702510253027002730203031103150320032203"
+ b"3103330336034403500352036703710375030004130417042104240432044004"
+ b"4304510470040205040520052205260533054105450547056605730506061106"
+ b"1306310652067106000702070407200722072607330750075407001001100210"
+ b"0410101011101310151017102010221031103410361054105610611072100011"
+ b"0111031106111011141121113011331141115011521170117611001212121512"
+ b"1712201224123212401243125512601272120113041307131013131321132713"
+ b"3013341341136213701303140514121414143114331442144614501454140115"
+ b"1015131521153015321551152016241627164416461601170317101712172117"
+ b"3517411762177017002001200320052007201020122014201620212023202720"
+ b"3020322041204320452050205220672070207320752000210221102113211721"
+ b"2221252131213421422151210122042207222122232230223722412253225722"
+ b"7122742200230223052311232223242331233323422350236623012407242024"
+ b"2324322435244124722475240425112522253725402553257025002602260726"
+ b"2126552661260527112726273027432750270230113013301530173022303130"
+ b"3330353042304430473051306330713001310331053114312131233140316031"
+ b"7231763100321232203232323432503201331033143321332333273330334133"
+ b"4333473355337333033411341634223431345234603464340135103512352535"
+ b"3235443556357335163641360137033720372237353700400440124020402440"
+ b"2740324041405040704002410741114113412241304135414341514155410142"
+ b"0342104215422142334240425742624270420443114313432043224331433543"
+ b"0044024424443744404471440545074521456245134634466046104715473047"
+ b"4347514702501050145022504050445047505250665074500151035105511251"
+ b"2151325172510052115223523052365253520253075310532753445351536553"
+ b"7353015404542054325446541255265551555355425602570457225711601360"
+ b"1560316033606060006120612761646112623462426255626262706200631463"
+ b"2163406325644364626400650365346560650566406611671367007004700770"
+ b"2070227036704070547062700271117124714371457101720472107216722172"
+ b"3072517202733273357353730174057413742074507422754275027631760077"
+ )
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qs, rest = np.hsplit(rest, [QK_K // 4])
+ qh, rest = np.hsplit(rest, [QK_K // 32])
+ signs, scales = np.hsplit(rest, [QK_K // 8])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ scales = scales.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
+ scales = (scales & 0x0F).reshape((n_blocks, -1))
+ db = d * (1 + 2 * scales)
+ db = db.reshape((n_blocks, -1, 1, 1))
+
+ # unpack the sign bits
+ signs = signs.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8))
+ signs = signs & np.uint8(0x01)
+ signs = np.where(signs == 0, np.float32(1), np.float32(-1))
+ signs = signs.reshape((n_blocks, -1, 4, 8))
+
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array([i for i in range(8)], dtype=np.uint8)
+ qh = (qh & 0x01).astype(np.uint16).reshape((n_blocks, -1))
+ qs = qs.astype(np.uint16) | (qh << 8)
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 4, 8))
+
+ return (db * grid * signs).reshape((n_blocks, -1))
+
+
+class IQ1_S(__Quant, qtype=GGMLQuantizationType.IQ1_S):
+ # iq1s_grid, with each byte packed into 2 bits
+ # -1, 0, 1 <=> 0, 1, 2
+ grid_shape = (2048, 8)
+ grid_map = (-1, 0, 1)
+ grid_hex = (
+ b"00000200050008000a00110015002000220028002a0045005100540056006500"
+ b"8000820088008a009500a000a200a800aa000401050111011401160119011a01"
+ b"2501410146014901520155015a0161016401660168018501910194019601a501"
+ b"0002020208020a0215022002220228022a024502510259026402690280028202"
+ b"88028a02910295029902a002a202a802aa021104140416042504410449045504"
+ b"5a046404650491049904a5040105040505050605150518051a05290540054505"
+ b"4a0550055105540555055605590560056205650568056a058105910595059805"
+ b"9a05a105a405a505a605a9051406190641064406500652065506580660066106"
+ b"6606690685069106940699060008020808080a0815082008220828082a084508"
+ b"5108560865088008820888088a089508a008a208a808aa080509110914091909"
+ b"2409250941095009510955096109640969099109940996099909a509000a020a"
+ b"080a0a0a150a200a220a280a2a0a450a510a590a610a650a800a820a850a880a"
+ b"8a0a950aa00aa20aa80aaa0a1010111014101910241025104110441050105510"
+ b"58106110641065106910911094109610a110a510011104110611091110111211"
+ b"1511181121112411291145114a11501151115211541155115611591160116511"
+ b"841192119511a111a41111121412161225124012461249125212551258125a12"
+ b"641266128512911294129612a512011406140914141415141814191421142614"
+ b"41144514461448144a1451145414551456145914621465146814841489149014"
+ b"94149514981499149a14a114a414a514a914021505150a151115141515151615"
+ b"191520152215251528152a154115441545154615511552155415551556155915"
+ b"5a1561156415651566156915801582158415851588158a159015911594159515"
+ b"961599159a15a015a215a51501160416051606161516161618161a1621162616"
+ b"401642164416451648164a165116551656165816591661166416651668166916"
+ b"6a1686168a1692169516a416a916111816182518411844184618491850185518"
+ b"58185a1860186118641866186918851891189418a5181019121915191a192119"
+ b"25194219441945194819511954195519561959195a19601965196a1989199119"
+ b"921995199819a119a619a919091a161a241a261a441a461a491a501a521a551a"
+ b"581a611a661a691a851a911a961a9a1a0020022008200a201520202022202520"
+ b"28202a20452051205920612065208020822088208a209520a020a220a520a820"
+ b"aa2005211121142119212521422144214921552158215a216121642165216621"
+ b"8521902196219921a521012208220a22112215222022222228222a2245225122"
+ b"562259226522812288228a2291229522a022a222a822aa220524142416241924"
+ b"252444244524462449245224552458245a2466248524912494249924a124a524"
+ b"0925152521252925402545254825512554255525592562256525682589259025"
+ b"9425952598259a25a125a425a625a92505261026122619262526412649265526"
+ b"6026612669268426862690269a260028022808280a2815282028222828282a28"
+ b"45285128542865288028822888288a28a028a228a828aa280929112914291929"
+ b"2529462949295229552961296429662969298529902996299929a429a529002a"
+ b"022a082a0a2a202a222a282a2a2a452a512a562a592a652a802a822a882a8a2a"
+ b"952aa02aa22aa82aaa2a054011401640254049405240554058405a4061406440"
+ b"664094409940a140a6400041014104410641094112411541164118411a412141"
+ b"26412941454148414a41514154415541564159415a41654168416a4181418441"
+ b"8641904192419541a041a141a241054211421442164225424142524255425a42"
+ b"6442694289429442a5420144154419442944454448444a445144544455445644"
+ b"61446244654468446a44814486448944904492449544a044a144a94401450245"
+ b"05450a4511451445154516451945204525452a45414544454545464549455045"
+ b"5145544555455645584559456145644565456645694582458445854588459145"
+ b"94459545964599459a45a545a845aa450146054609461446154618461a462146"
+ b"2446294640464246454648465046514652465546564659466246654668468146"
+ b"85468a4694469546a146a446a6460548114815481a4825484248494850485548"
+ b"5848614864486648694885489148944896489948a5480149054906490a491049"
+ b"144915491849214924492649404945494a495149524954495549564959496049"
+ b"6249654966496a49864989499249954996499849a149a449a649a949164a444a"
+ b"464a494a554a584a5a4a644a694a944aa54a0150045005500650095012501550"
+ b"1a50215024502950405045504850515054505550565059506550685086508950"
+ b"95509850a050a150a650a9500551085109510a51115114511551165118511951"
+ b"20512551265128512a5141514451455146514951505151515251545155515651"
+ b"585159515a51615164516551665169518251855191519451955196519951a051"
+ b"a551aa5101520652125215521a5221522452425245524a525152545255525652"
+ b"595262526552855290529252955299529a52a452045405541154145415541654"
+ b"185419542154255428542a54415444544554465449544a545054515454545554"
+ b"5654585459545a54615462546454655466546954805488548a54915494549554"
+ b"96549954a154a454a554aa540155025504550555065509551055115512551455"
+ b"1555165519551a55215524552555265529554055415542554455455546554855"
+ b"4955505551555255545555555655585559555a55605561556455655566556855"
+ b"69556a5581558455855589558a559055915594559555965598559955a155a455"
+ b"a555a655a9550056015602560456065608560956115614561556185619562056"
+ b"2156225624562556265628562956415645564656485649564a56505651565256"
+ b"545655565656585659565a566156645665566956825685568656885689568a56"
+ b"915695569a56a256a556a656a856a95604580558065809581058155818582158"
+ b"2a58455848584a58515854585558565858585958605862586458655882588958"
+ b"9058925895589858a158a9580159025905590a59115914591559165919592559"
+ b"41594459455946594959505951595259545955595659585959595a5961596459"
+ b"655966596959815985598959915994599559965998599959a559045a085a155a"
+ b"1a5a205a255a265a295a455a485a495a515a555a565a585a595a625a655a685a"
+ b"6a5a815a8a5a925a955a965a985a9a5aa15a0560146016601960256044605060"
+ b"5560566058605a60616064606660696081609660a56001610461066109611261"
+ b"15612161226126612961456149615161556156615961656166616a6184618a61"
+ b"92619561a161a661a96111621662196240624162466255625662586260628562"
+ b"91629662a56211641264156416641a6421642664296440644264456448644a64"
+ b"516454645564566459645a646064626465648464856489649064926494649564"
+ b"966498649a64a164a464a964056508650a651165156516651965446545654665"
+ b"496550655165546555655665596561656465656566656965866589658a659165"
+ b"9565966599659a65a265a565a665a86502660966156620662666286629664066"
+ b"456648664a66516654665566566658665a666066656668668066826685668a66"
+ b"9466966698669966a066a466a666aa661668196825684168526855685a686168"
+ b"6968856891689868a66801690469106915692169246926692969406941694569"
+ b"4669486951695469556956695969606965696a69826984698a699569a169a469"
+ b"a569a969116a166a186a416a446a496a506a556a586a5a6a646a656a696a866a"
+ b"946a986a9a6aa66a0080028008800a802080228028802a804580508051805480"
+ b"5680598065808080828088808a809580a080a280a880aa800581118114811681"
+ b"1981258141814481498150815281558156815881598164816681698185818981"
+ b"948196819981a5810082028208820a8215822082228228822a82518254825982"
+ b"65828082828288828a829582a082a282a882aa82148419844184448451845584"
+ b"5a846184648469849484998401850985128515851a8526852985408541854585"
+ b"4885518554855585568559855a856585668568856a8581858485868589859085"
+ b"928595859885a68511861686198625864186448649864a865086558659865a86"
+ b"618666866a86858691869a86a4860088028808880a8815882088228828882a88"
+ b"41884588518854885988658869888088828888888a889588a088a288a888aa88"
+ b"05890689118914891689258941894489468949895089528955895a8961896489"
+ b"858996899989a589008a028a088a0a8a158a208a228a288a2a8a458a518a548a"
+ b"568a808a828a888a8a8a958aa08aa28aa88aaa8a059011901690189019902590"
+ b"419046904990559058905a9069906a9085909190949096909990a59001910491"
+ b"069109911091159118911a912191249126912991409145915091519154915591"
+ b"569159916291659184918691929195919891a191a491a691a991059211921492"
+ b"19922592449246924992509252925592589266926992859294929692a9920194"
+ b"04940694109415941894269440944a9451945494559456945894599460946194"
+ b"62946594849486949294949495949894a194a9940095059508950a9510951195"
+ b"14951595169519952195259529952a9541954495459546954995509551955295"
+ b"549555955695589559955a956195649565956695699581958595889591959295"
+ b"94959595969599959a95a095a295a595a895aa95019604961096159619962096"
+ b"2696299645964896499651965296559656965996659668968296849689968a96"
+ b"929694969596a496a696a9960598169819982598419846985098529855985698"
+ b"5a98649865988598919896989998a59804990699099910991299159918991a99"
+ b"209921992499269940994299459948994a995199549955995699599962996599"
+ b"66996a99819984999099929995999a99a199a699059a159a259a449a469a499a"
+ b"509a559a589a619a859a919a949a959a969a00a002a008a00aa015a020a022a0"
+ b"28a02aa045a051a054a056a059a080a082a088a08aa095a0a0a0a2a0a8a0aaa0"
+ b"05a109a111a114a116a119a11aa146a149a151a155a158a15aa161a164a185a1"
+ b"90a192a196a199a102a208a20aa210a219a222a228a22aa245a251a256a259a2"
+ b"65a280a282a288a28aa295a2a0a2a2a2a8a2aaa219a425a441a444a450a454a4"
+ b"55a458a45aa461a465a466a468a469a485a406a509a510a512a515a518a526a5"
+ b"29a542a545a551a554a555a556a559a565a56aa581a584a585a586a589a592a5"
+ b"95a598a505a611a616a61aa621a625a644a646a64aa652a655a656a658a660a6"
+ b"62a686a690a695a696a699a6a1a6a4a6a6a600a802a808a80aa820a822a828a8"
+ b"2aa851a854a856a859a880a882a888a88aa895a8a0a8a2a8a8a8aaa805a914a9"
+ b"19a921a925a941a950a955a95aa961a966a969a990a996a900aa02aa08aa0aaa"
+ b"20aa22aa28aa2aaa51aa54aa56aa80aa82aa88aa8aaa95aaa0aaa2aaa8aaaaaa"
+ )
+
+ delta = np.float32(0.125)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ qs, qh = np.hsplit(rest, [QK_K // 8])
+
+ d = d.view(np.float16).astype(np.float32)
+ qh = qh.view(np.uint16)
+
+ dl = d * (2 * ((qh >> 12) & 7) + 1)
+ dl = dl.reshape((n_blocks, -1, 1, 1))
+ delta = np.where((qh & np.uint16(0x8000)) == 0, cls.delta, -cls.delta)
+ delta = delta.reshape((n_blocks, -1, 1, 1))
+
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 3, 6, 9], dtype=np.uint16).reshape((1, 1, 4))
+ qs = qs.astype(np.uint16) | ((qh & 7) << 8).reshape((n_blocks, -1))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 4, 8))
+
+ return (dl * (grid + delta)).reshape((n_blocks, -1))
+
+
+class IQ1_M(__Quant, qtype=GGMLQuantizationType.IQ1_M):
+ grid_shape = IQ1_S.grid_shape
+ grid_map = IQ1_S.grid_map
+ grid_hex = IQ1_S.grid_hex
+
+ delta = IQ1_S.delta
+
+ # Okay *this* type is weird. It's the only one which stores the f16 scales in multiple parts.
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ qs, rest = np.hsplit(blocks, [QK_K // 8])
+ qh, scales = np.hsplit(rest, [QK_K // 16])
+
+ # The f16 scale is packed across multiple bytes
+ scales = scales.view(np.uint16)
+ d = (scales.reshape((n_blocks, 4)) & np.uint16(0xF000)) >> np.array([12, 8, 4, 0], dtype=np.uint16).reshape((1, 4))
+ d = d[..., 0] | d[..., 1] | d[..., 2] | d[..., 3]
+ d = d.view(np.float16).astype(np.float32).reshape((n_blocks, 1))
+
+ scales = scales.reshape(n_blocks, -1, 1) >> np.array([0, 3, 6, 9], dtype=np.uint16).reshape((1, 1, 4))
+ scales = (scales & 0x07).reshape((n_blocks, -1))
+ dl = d * (2 * scales + 1)
+ dl = dl.reshape((n_blocks, -1, 2, 1, 1))
+
+ qh = qh.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
+ qs = qs.astype(np.uint16) | ((qh & 0x07).astype(np.uint16) << 8).reshape((n_blocks, -1))
+
+ delta = np.where(qh & 0x08 == 0, cls.delta, -cls.delta)
+ delta = delta.reshape((n_blocks, -1, 2, 2, 1))
+
+ assert cls.grid is not None
+ grid = np.take_along_axis(cls.grid, qs.reshape((n_blocks, -1, 1, 1)), axis=-2)
+ grid = grid.reshape((n_blocks, -1, 2, 2, 8))
+
+ return (dl * (grid + delta)).reshape((n_blocks, -1))
+
+
+class IQ4_NL(__Quant, qtype=GGMLQuantizationType.IQ4_NL):
+ kvalues = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
+
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, qs = np.hsplit(blocks, [2])
+
+ d = d.view(np.float16).astype(np.float32)
+
+ qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+
+ qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 1))
+
+ kvalues = np.array(cls.kvalues, dtype=np.int8).reshape(1, 1, 16)
+ qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1))
+
+ return (d * qs)
+
+
+class IQ4_XS(__Quant, qtype=GGMLQuantizationType.IQ4_XS):
+ @classmethod
+ def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray:
+ n_blocks = blocks.shape[0]
+
+ d, rest = np.hsplit(blocks, [2])
+ scales_h, rest = np.hsplit(rest, [2])
+ scales_l, qs = np.hsplit(rest, [QK_K // 64])
+
+ d = d.view(np.float16).astype(np.float32)
+ scales_h = scales_h.view(np.uint16)
+
+ scales_l = scales_l.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2))
+ scales_h = scales_h.reshape((n_blocks, 1, -1)) >> np.array([2 * i for i in range(QK_K // 32)], dtype=np.uint16).reshape((1, -1, 1))
+ scales_l = scales_l.reshape((n_blocks, -1)) & np.uint8(0x0F)
+ scales_h = scales_h.reshape((n_blocks, -1)).astype(np.uint8) & np.uint8(0x03)
+
+ scales = (scales_l | (scales_h << np.uint8(4))).astype(np.int8) - np.int8(32)
+ dl = (d * scales.astype(np.float32)).reshape((n_blocks, -1, 1))
+
+ qs = qs.reshape((n_blocks, -1, 1, 16)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1))
+ qs = qs.reshape((n_blocks, -1, 32, 1)) & np.uint8(0x0F)
+
+ kvalues = np.array(IQ4_NL.kvalues, dtype=np.int8).reshape((1, 1, 1, -1))
+ qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1, 32))
+
+ return (dl * qs).reshape((n_blocks, -1))
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_convert_endian.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_convert_endian.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2aeac5876968b705f037d745d3dcc6c99f88c4a6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_convert_endian.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_dump.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_dump.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3971fcae09a76f0f22503ca0f5a3eaab5dd7faae
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_dump.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_editor_gui.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_editor_gui.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dda6f994f5349d412c69b4c5e26cbdaa568f5930
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_editor_gui.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_hash.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_hash.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6b130182bca2b7d18700734f693e7c80ebc25021
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_hash.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_new_metadata.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_new_metadata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d959a3ecfd16f068a2698b88ac830e101a5acff
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_new_metadata.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_set_metadata.cpython-310.pyc b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_set_metadata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72c229da9ce7fe29d5c3c2a3aae61e2e25060f27
Binary files /dev/null and b/venv/lib/python3.10/site-packages/gguf/scripts/__pycache__/gguf_set_metadata.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_convert_endian.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_convert_endian.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e0febaa791786fb9d5c713478377e5d54642df8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_convert_endian.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import logging
+import argparse
+import os
+import sys
+from tqdm import tqdm
+from pathlib import Path
+
+import numpy as np
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+import gguf
+
+logger = logging.getLogger("gguf-convert-endian")
+
+
+def convert_byteorder(reader: gguf.GGUFReader, args: argparse.Namespace) -> None:
+ file_endian = reader.endianess.name
+ if reader.byte_order == 'S':
+ host_endian = 'BIG' if file_endian == 'LITTLE' else 'LITTLE'
+ else:
+ host_endian = file_endian
+ order = host_endian if args.order == "native" else args.order.upper()
+ logger.info(f"* Host is {host_endian} endian, GGUF file seems to be {file_endian} endian")
+ if file_endian == order:
+ logger.info(f"* File is already {order} endian. Nothing to do.")
+ sys.exit(0)
+ logger.info("* Checking tensors for conversion compatibility")
+ for tensor in reader.tensors:
+ if tensor.tensor_type not in (
+ gguf.GGMLQuantizationType.F32,
+ gguf.GGMLQuantizationType.F16,
+ gguf.GGMLQuantizationType.Q8_0,
+ gguf.GGMLQuantizationType.Q4_K,
+ gguf.GGMLQuantizationType.Q6_K,
+ ):
+ raise ValueError(f"Cannot handle type {tensor.tensor_type.name} for tensor {repr(tensor.name)}")
+ logger.info(f"* Preparing to convert from {file_endian} to {order}")
+ if args.dry_run:
+ return
+ logger.warning("*** Warning *** Warning *** Warning **")
+ logger.warning("* This conversion process may damage the file. Ensure you have a backup.")
+ if order != host_endian:
+ logger.warning("* Requested endian differs from host, you will not be able to load the model on this machine.")
+ logger.warning("* The file will be modified immediately, so if conversion fails or is interrupted")
+ logger.warning("* the file will be corrupted. Enter exactly YES if you are positive you want to proceed:")
+ response = input("YES, I am sure> ")
+ if response != "YES":
+ logger.warning("You didn't enter YES. Okay then, see ya!")
+ sys.exit(0)
+ logger.info(f"* Converting fields ({len(reader.fields)})")
+ for idx, field in enumerate(reader.fields.values()):
+ logger.info(f"- {idx:4}: Converting field {repr(field.name)}, part count: {len(field.parts)}")
+ for part in field.parts:
+ part.byteswap(inplace=True)
+ logger.info(f"* Converting tensors ({len(reader.tensors)})")
+
+ for idx, tensor in enumerate(pbar := tqdm(reader.tensors, desc="Converting tensor")):
+ log_message = (
+ f"Converting tensor {repr(tensor.name)}, "
+ f"type={tensor.tensor_type.name}, "
+ f"elements={tensor.n_elements} "
+ )
+
+ # Byte-swap each part of the tensor's field
+ for part in tensor.field.parts:
+ part.byteswap(inplace=True)
+
+ # Byte-swap tensor data if necessary
+ if tensor.tensor_type == gguf.GGMLQuantizationType.Q8_0:
+ # Handle Q8_0 tensor blocks (block_q8_0)
+ # Specific handling of block_q8_0 is required.
+ # Each block_q8_0 consists of an f16 delta (scaling factor) followed by 32 int8 quantizations.
+
+ block_size = 34 # 34 bytes = + 32 *
+
+ n_blocks = len(tensor.data) // block_size
+ for block_num in (inner_pbar := tqdm(range(n_blocks), desc="Byte-swapping Blocks", leave=False)):
+ block_offs = block_num * block_size
+
+ # Byte-Swap f16 sized delta field
+ delta = tensor.data[block_offs:block_offs + 2].view(dtype=np.uint16)
+ delta.byteswap(inplace=True)
+
+ # Byte-Swap Q8 weights
+ if block_num % 100000 == 0:
+ inner_pbar.set_description(f"Byte-swapping Blocks [{(n_blocks - block_num) // n_blocks}]")
+
+ elif tensor.tensor_type == gguf.GGMLQuantizationType.Q4_K:
+ # Handle Q4_K tensor blocks (block_q4_k)
+ # Specific handling of block_q4_k is required.
+ # Each block_q4_k consists of 2 f16 values followed by 140 int8 values.
+
+ # first flatten structure
+ newshape = 1
+ for i in tensor.data.shape:
+ newshape *= i
+
+ tensor.data.resize(newshape)
+
+ block_size = 144
+ n_blocks = len(tensor.data) // block_size
+ for block_num in (inner_pbar := tqdm(range(n_blocks), desc="Byte-swapping Blocks", leave=False)):
+ block_offs = block_num * block_size
+
+ # Byte-Swap f16 sized fields
+ delta = tensor.data[block_offs:block_offs + 2].view(dtype=np.uint16)
+ delta.byteswap(inplace=True)
+
+ delta = tensor.data[block_offs + 2:block_offs + 4].view(dtype=np.uint16)
+ delta.byteswap(inplace=True)
+
+ # Byte-Swap
+ if block_num % 100000 == 0:
+ inner_pbar.set_description(f"Byte-swapping Blocks [{(n_blocks - block_num) // n_blocks}]")
+
+ elif tensor.tensor_type == gguf.GGMLQuantizationType.Q6_K:
+ # Handle Q6_K tensor blocks (block_q6_k)
+ # Specific handling of block_q6_k is required.
+ # Each block_q6_k consists of 208 int8 values followed by 1 f16 value.
+
+ # first flatten structure
+ newshape = 1
+ for i in tensor.data.shape:
+ newshape *= i
+
+ tensor.data.resize(newshape)
+
+ block_size = 210
+ n_blocks = len(tensor.data) // block_size
+ for block_num in (inner_pbar := tqdm(range(n_blocks), desc="Byte-swapping Blocks", leave=False)):
+ block_offs = block_num * block_size
+
+ # Byte-Swap f16 sized field
+ delta = tensor.data[block_offs + 208:block_offs + 210].view(dtype=np.uint16)
+ delta.byteswap(inplace=True)
+
+ # Byte-Swap
+ if block_num % 100000 == 0:
+ inner_pbar.set_description(f"Byte-swapping Blocks [{(n_blocks - block_num) // n_blocks}]")
+
+ else:
+ # Handle other tensor types
+ tensor.data.byteswap(inplace=True)
+
+ pbar.set_description(log_message)
+
+ logger.info("* Completion")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Convert GGUF file byte order")
+ parser.add_argument(
+ "model", type=str,
+ help="GGUF format model filename",
+ )
+ parser.add_argument(
+ "order", type=str, choices=['big', 'little', 'native'],
+ help="Requested byte order",
+ )
+ parser.add_argument(
+ "--dry-run", action="store_true",
+ help="Don't actually change anything",
+ )
+ parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+
+ args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+
+ logger.info(f'* Loading: {args.model}')
+ reader = gguf.GGUFReader(args.model, 'r' if args.dry_run else 'r+')
+ convert_byteorder(reader, args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_dump.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_dump.py
new file mode 100644
index 0000000000000000000000000000000000000000..e282892d645c7c31a1d5e00f383dcaaa5890a127
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_dump.py
@@ -0,0 +1,454 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import logging
+import argparse
+import os
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from gguf import GGUFReader, GGUFValueType, ReaderTensor # noqa: E402
+
+logger = logging.getLogger("gguf-dump")
+
+
+def get_file_host_endian(reader: GGUFReader) -> tuple[str, str]:
+ file_endian = reader.endianess.name
+ if reader.byte_order == 'S':
+ host_endian = 'BIG' if file_endian == 'LITTLE' else 'LITTLE'
+ else:
+ host_endian = file_endian
+ return (host_endian, file_endian)
+
+
+# For more information about what field.parts and field.data represent,
+# please see the comments in the modify_gguf.py example.
+def dump_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
+ host_endian, file_endian = get_file_host_endian(reader)
+ print(f'* File is {file_endian} endian, script is running on a {host_endian} endian host.') # noqa: NP100
+ print(f'* Dumping {len(reader.fields)} key/value pair(s)') # noqa: NP100
+ for n, field in enumerate(reader.fields.values(), 1):
+ if not field.types:
+ pretty_type = 'N/A'
+ elif field.types[0] == GGUFValueType.ARRAY:
+ nest_count = len(field.types) - 1
+ pretty_type = '[' * nest_count + str(field.types[-1].name) + ']' * nest_count
+ else:
+ pretty_type = str(field.types[-1].name)
+
+ log_message = f' {n:5}: {pretty_type:10} | {len(field.data):8} | {field.name}'
+ if field.types:
+ curr_type = field.types[0]
+ if curr_type == GGUFValueType.STRING:
+ content = field.contents()
+ if len(content) > 60:
+ content = content[:57] + '...'
+ log_message += ' = {0}'.format(repr(content))
+ elif curr_type in reader.gguf_scalar_to_np:
+ log_message += ' = {0}'.format(field.contents())
+ else:
+ content = repr(field.contents(slice(6)))
+ if len(field.data) > 6:
+ content = content[:-1] + ', ...]'
+ log_message += ' = {0}'.format(content)
+ print(log_message) # noqa: NP100
+ if args.no_tensors:
+ return
+ print(f'* Dumping {len(reader.tensors)} tensor(s)') # noqa: NP100
+ for n, tensor in enumerate(reader.tensors, 1):
+ prettydims = ', '.join('{0:5}'.format(d) for d in list(tensor.shape) + [1] * (4 - len(tensor.shape)))
+ print(f' {n:5}: {tensor.n_elements:10} | {prettydims} | {tensor.tensor_type.name:7} | {tensor.name}') # noqa: NP100
+
+
+def dump_metadata_json(reader: GGUFReader, args: argparse.Namespace) -> None:
+ import json
+ host_endian, file_endian = get_file_host_endian(reader)
+ metadata: dict[str, Any] = {}
+ tensors: dict[str, Any] = {}
+ result = {
+ "filename": args.model,
+ "endian": file_endian,
+ "metadata": metadata,
+ "tensors": tensors,
+ }
+ for idx, field in enumerate(reader.fields.values()):
+ curr: dict[str, Any] = {
+ "index": idx,
+ "type": field.types[0].name if field.types else 'UNKNOWN',
+ "offset": field.offset,
+ }
+ metadata[field.name] = curr
+ if field.types[:1] == [GGUFValueType.ARRAY]:
+ curr["array_types"] = [t.name for t in field.types][1:]
+ if not args.json_array:
+ continue
+ curr["value"] = field.contents()
+ else:
+ curr["value"] = field.contents()
+ if not args.no_tensors:
+ for idx, tensor in enumerate(reader.tensors):
+ tensors[tensor.name] = {
+ "index": idx,
+ "shape": tensor.shape.tolist(),
+ "type": tensor.tensor_type.name,
+ "offset": tensor.field.offset,
+ }
+ json.dump(result, sys.stdout)
+
+
+def markdown_table_with_alignment_support(header_map: list[dict[str, str]], data: list[dict[str, Any]]):
+ # JSON to Markdown table formatting: https://stackoverflow.com/a/72983854/2850957
+
+ # Alignment Utility Function
+ def strAlign(padding: int, alignMode: str | None, strVal: str):
+ if alignMode == 'center':
+ return strVal.center(padding)
+ elif alignMode == 'right':
+ return strVal.rjust(padding - 1) + ' '
+ elif alignMode == 'left':
+ return ' ' + strVal.ljust(padding - 1)
+ else: # default left
+ return ' ' + strVal.ljust(padding - 1)
+
+ def dashAlign(padding: int, alignMode: str | None):
+ if alignMode == 'center':
+ return ':' + '-' * (padding - 2) + ':'
+ elif alignMode == 'right':
+ return '-' * (padding - 1) + ':'
+ elif alignMode == 'left':
+ return ':' + '-' * (padding - 1)
+ else: # default left
+ return '-' * (padding)
+
+ # Calculate Padding For Each Column Based On Header and Data Length
+ rowsPadding = {}
+ for index, columnEntry in enumerate(header_map):
+ padCount = max([len(str(v)) for d in data for k, v in d.items() if k == columnEntry['key_name']], default=0) + 2
+ headerPadCount = len(columnEntry['header_name']) + 2
+ rowsPadding[index] = headerPadCount if padCount <= headerPadCount else padCount
+
+ # Render Markdown Header
+ rows = []
+ rows.append('|'.join(strAlign(rowsPadding[index], columnEntry.get('align'), str(columnEntry['header_name'])) for index, columnEntry in enumerate(header_map)))
+ rows.append('|'.join(dashAlign(rowsPadding[index], columnEntry.get('align')) for index, columnEntry in enumerate(header_map)))
+
+ # Render Tabular Data
+ for item in data:
+ rows.append('|'.join(strAlign(rowsPadding[index], columnEntry.get('align'), str(item[columnEntry['key_name']])) for index, columnEntry in enumerate(header_map)))
+
+ # Convert Tabular String Rows Into String
+ tableString = ""
+ for row in rows:
+ tableString += f'|{row}|\n'
+
+ return tableString
+
+
+def element_count_rounded_notation(count: int) -> str:
+ if count > 1e15 :
+ # Quadrillion
+ scaled_amount = count * 1e-15
+ scale_suffix = "Q"
+ elif count > 1e12 :
+ # Trillions
+ scaled_amount = count * 1e-12
+ scale_suffix = "T"
+ elif count > 1e9 :
+ # Billions
+ scaled_amount = count * 1e-9
+ scale_suffix = "B"
+ elif count > 1e6 :
+ # Millions
+ scaled_amount = count * 1e-6
+ scale_suffix = "M"
+ elif count > 1e3 :
+ # Thousands
+ scaled_amount = count * 1e-3
+ scale_suffix = "K"
+ else:
+ # Under Thousands
+ scaled_amount = count
+ scale_suffix = ""
+ return f"{'~' if count > 1e3 else ''}{round(scaled_amount)}{scale_suffix}"
+
+
+def translate_tensor_name(name):
+ words = name.split(".")
+
+ # Source: https://github.com/ggml-org/ggml/blob/master/docs/gguf.md#standardized-tensor-names
+ abbreviation_dictionary = {
+ 'token_embd': 'Token embedding',
+ 'pos_embd': 'Position embedding',
+ 'output_norm': 'Output normalization',
+ 'output': 'Output',
+ 'attn_norm': 'Attention normalization',
+ 'attn_norm_2': 'Attention normalization',
+ 'attn_qkv': 'Attention query-key-value',
+ 'attn_q': 'Attention query',
+ 'attn_k': 'Attention key',
+ 'attn_v': 'Attention value',
+ 'attn_output': 'Attention output',
+ 'ffn_norm': 'Feed-forward network normalization',
+ 'ffn_up': 'Feed-forward network "up"',
+ 'ffn_gate': 'Feed-forward network "gate"',
+ 'ffn_down': 'Feed-forward network "down"',
+ 'ffn_gate_inp': 'Expert-routing layer for the Feed-forward network in Mixture of Expert models',
+ 'ffn_gate_exp': 'Feed-forward network "gate" layer per expert in Mixture of Expert models',
+ 'ffn_down_exp': 'Feed-forward network "down" layer per expert in Mixture of Expert models',
+ 'ffn_up_exp': 'Feed-forward network "up" layer per expert in Mixture of Expert models',
+ 'ssm_in': 'State space model input projections',
+ 'ssm_conv1d': 'State space model rolling/shift',
+ 'ssm_x': 'State space model selective parametrization',
+ 'ssm_a': 'State space model state compression',
+ 'ssm_d': 'State space model skip connection',
+ 'ssm_dt': 'State space model time step',
+ 'ssm_out': 'State space model output projection',
+ 'blk': 'Block',
+ 'enc': 'Encoder',
+ 'dec': 'Decoder',
+ }
+
+ expanded_words = []
+ for word in words:
+ word_norm = word.strip().lower()
+ if word_norm in abbreviation_dictionary:
+ expanded_words.append(abbreviation_dictionary[word_norm].title())
+ else:
+ expanded_words.append(word.title())
+
+ return ' '.join(expanded_words)
+
+
+def dump_markdown_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
+ host_endian, file_endian = get_file_host_endian(reader)
+ markdown_content = ""
+ markdown_content += f'# {args.model} - GGUF Internal File Dump\n\n'
+ markdown_content += f'- Endian: {file_endian} endian\n'
+ markdown_content += '\n'
+ markdown_content += '## Key Value Metadata Store\n\n'
+ markdown_content += f'There are {len(reader.fields)} key-value pairs in this file\n'
+ markdown_content += '\n'
+
+ kv_dump_table: list[dict[str, str | int]] = []
+ for n, field in enumerate(reader.fields.values(), 1):
+ if not field.types:
+ pretty_type = 'N/A'
+ elif field.types[0] == GGUFValueType.ARRAY:
+ nest_count = len(field.types) - 1
+ pretty_type = '[' * nest_count + str(field.types[-1].name) + ']' * nest_count
+ else:
+ pretty_type = str(field.types[-1].name)
+
+ def escape_markdown_inline_code(value_string):
+ # Find the longest contiguous sequence of backticks in the string then
+ # wrap string with appropriate number of backticks required to escape it
+ max_backticks = max((len(match.group(0)) for match in re.finditer(r'`+', value_string)), default=0)
+ inline_code_marker = '`' * (max_backticks + 1)
+
+ # If the string starts or ends with a backtick, add a space at the beginning and end
+ if value_string.startswith('`') or value_string.endswith('`'):
+ value_string = f" {value_string} "
+
+ return f"{inline_code_marker}{value_string}{inline_code_marker}"
+
+ total_elements = len(field.data)
+ value = ""
+ if len(field.types) == 1:
+ curr_type = field.types[0]
+ if curr_type == GGUFValueType.STRING:
+ truncate_length = 60
+ value_string = str(bytes(field.parts[-1]), encoding='utf-8')
+ if len(value_string) > truncate_length:
+ head = escape_markdown_inline_code(value_string[:truncate_length // 2])
+ tail = escape_markdown_inline_code(value_string[-truncate_length // 2:])
+ value = "{head}...{tail}".format(head=head, tail=tail)
+ else:
+ value = escape_markdown_inline_code(value_string)
+ elif curr_type in reader.gguf_scalar_to_np:
+ value = str(field.parts[-1][0])
+ else:
+ if field.types[0] == GGUFValueType.ARRAY:
+ curr_type = field.types[1]
+ array_elements = []
+
+ if curr_type == GGUFValueType.STRING:
+ render_element = min(5, total_elements)
+ for element_pos in range(render_element):
+ truncate_length = 30
+ value_string = str(bytes(field.parts[-1 - (total_elements - element_pos - 1) * 2]), encoding='utf-8')
+ if len(value_string) > truncate_length:
+ head = escape_markdown_inline_code(value_string[:truncate_length // 2])
+ tail = escape_markdown_inline_code(value_string[-truncate_length // 2:])
+ value = "{head}...{tail}".format(head=head, tail=tail)
+ else:
+ value = escape_markdown_inline_code(value_string)
+ array_elements.append(value)
+
+ elif curr_type in reader.gguf_scalar_to_np:
+ render_element = min(7, total_elements)
+ for element_pos in range(render_element):
+ array_elements.append(str(field.parts[-1 - (total_elements - element_pos - 1)][0]))
+
+ value = f'[ {", ".join(array_elements).strip()}{", ..." if total_elements > len(array_elements) else ""} ]'
+
+ kv_dump_table.append({"n":n, "pretty_type":pretty_type, "total_elements":total_elements, "field_name":field.name, "value":value})
+
+ kv_dump_table_header_map = [
+ {'key_name':'n', 'header_name':'POS', 'align':'right'},
+ {'key_name':'pretty_type', 'header_name':'TYPE', 'align':'left'},
+ {'key_name':'total_elements', 'header_name':'Count', 'align':'right'},
+ {'key_name':'field_name', 'header_name':'Key', 'align':'left'},
+ {'key_name':'value', 'header_name':'Value', 'align':'left'},
+ ]
+
+ markdown_content += markdown_table_with_alignment_support(kv_dump_table_header_map, kv_dump_table)
+
+ markdown_content += "\n"
+
+ if not args.no_tensors:
+ # Group tensors by their prefix and maintain order
+ tensor_prefix_order: list[str] = []
+ tensor_name_to_key: dict[str, int] = {}
+ tensor_groups: dict[str, list[ReaderTensor]] = {}
+ total_elements = sum(tensor.n_elements for tensor in reader.tensors)
+
+ # Parsing Tensors Record
+ for key, tensor in enumerate(reader.tensors):
+ tensor_components = tensor.name.split('.')
+
+ # Classify Tensor Group
+ tensor_group_name = "base"
+ if tensor_components[0] == 'blk':
+ tensor_group_name = f"{tensor_components[0]}.{tensor_components[1]}"
+ elif tensor_components[0] in ['enc', 'dec'] and tensor_components[1] == 'blk':
+ tensor_group_name = f"{tensor_components[0]}.{tensor_components[1]}.{tensor_components[2]}"
+ elif tensor_components[0] in ['enc', 'dec']:
+ tensor_group_name = f"{tensor_components[0]}"
+
+ # Check if new Tensor Group
+ if tensor_group_name not in tensor_groups:
+ tensor_groups[tensor_group_name] = []
+ tensor_prefix_order.append(tensor_group_name)
+
+ # Record Tensor and Tensor Position
+ tensor_groups[tensor_group_name].append(tensor)
+ tensor_name_to_key[tensor.name] = key
+
+ # Tensors Mapping Dump
+ markdown_content += f'## Tensors Overview {element_count_rounded_notation(total_elements)} Elements\n\n'
+ markdown_content += f'Total number of elements in all tensors: {total_elements} Elements\n'
+ markdown_content += '\n'
+
+ for group in tensor_prefix_order:
+ tensors = tensor_groups[group]
+ group_elements = sum(tensor.n_elements for tensor in tensors)
+ markdown_content += f"- [{translate_tensor_name(group)} Tensor Group - {element_count_rounded_notation(group_elements)} Elements](#{group.replace('.', '_')})\n"
+
+ markdown_content += "\n"
+
+ markdown_content += "### Tensor Data Offset\n"
+ markdown_content += '\n'
+ markdown_content += 'This table contains the offset and data segment relative to start of file\n'
+ markdown_content += '\n'
+
+ tensor_mapping_table: list[dict[str, str | int]] = []
+ for key, tensor in enumerate(reader.tensors):
+ data_offset_pretty = '{0:#16x}'.format(tensor.data_offset)
+ data_size_pretty = '{0:#16x}'.format(tensor.n_bytes)
+ tensor_mapping_table.append({"t_id":key, "layer_name":tensor.name, "data_offset":data_offset_pretty, "data_size":data_size_pretty})
+
+ tensors_mapping_table_header_map = [
+ {'key_name':'t_id', 'header_name':'T_ID', 'align':'right'},
+ {'key_name':'layer_name', 'header_name':'Tensor Layer Name', 'align':'left'},
+ {'key_name':'data_offset', 'header_name':'Data Offset (B)', 'align':'right'},
+ {'key_name':'data_size', 'header_name':'Data Size (B)', 'align':'right'},
+ ]
+
+ markdown_content += markdown_table_with_alignment_support(tensors_mapping_table_header_map, tensor_mapping_table)
+ markdown_content += "\n"
+
+ for group in tensor_prefix_order:
+ tensors = tensor_groups[group]
+ group_elements = sum(tensor.n_elements for tensor in tensors)
+ group_percentage = group_elements / total_elements * 100
+ markdown_content += f"### {translate_tensor_name(group)} Tensor Group : {element_count_rounded_notation(group_elements)} Elements \n\n"
+
+ # Precalculate column sizing for visual consistency
+ prettify_element_est_count_size: int = 1
+ prettify_element_count_size: int = 1
+ prettify_dimension_max_widths: dict[int, int] = {}
+ for tensor in tensors:
+ prettify_element_est_count_size = max(prettify_element_est_count_size, len(str(element_count_rounded_notation(tensor.n_elements))))
+ prettify_element_count_size = max(prettify_element_count_size, len(str(tensor.n_elements)))
+ for i, dimension_size in enumerate(list(tensor.shape) + [1] * (4 - len(tensor.shape))):
+ prettify_dimension_max_widths[i] = max(prettify_dimension_max_widths.get(i,1), len(str(dimension_size)))
+
+ # Generate Tensor Layer Table Content
+ tensor_dump_table: list[dict[str, str | int]] = []
+ for tensor in tensors:
+ human_friendly_name = translate_tensor_name(tensor.name.replace(".weight", ".(W)").replace(".bias", ".(B)"))
+ pretty_dimension = ' x '.join(f'{str(d):>{prettify_dimension_max_widths[i]}}' for i, d in enumerate(list(tensor.shape) + [1] * (4 - len(tensor.shape))))
+ element_count_est = f"({element_count_rounded_notation(tensor.n_elements):>{prettify_element_est_count_size}})"
+ element_count_string = f"{element_count_est} {tensor.n_elements:>{prettify_element_count_size}}"
+ type_name_string = f"{tensor.tensor_type.name}"
+ tensor_dump_table.append({"t_id":tensor_name_to_key[tensor.name], "layer_name":tensor.name, "human_layer_name":human_friendly_name, "element_count":element_count_string, "pretty_dimension":pretty_dimension, "tensor_type":type_name_string})
+
+ tensor_dump_table_header_map = [
+ {'key_name':'t_id', 'header_name':'T_ID', 'align':'right'},
+ {'key_name':'layer_name', 'header_name':'Tensor Layer Name', 'align':'left'},
+ {'key_name':'human_layer_name', 'header_name':'Human Friendly Tensor Layer Name', 'align':'left'},
+ {'key_name':'element_count', 'header_name':'Elements', 'align':'left'},
+ {'key_name':'pretty_dimension', 'header_name':'Shape', 'align':'left'},
+ {'key_name':'tensor_type', 'header_name':'Type', 'align':'left'},
+ ]
+
+ markdown_content += markdown_table_with_alignment_support(tensor_dump_table_header_map, tensor_dump_table)
+
+ markdown_content += "\n"
+ markdown_content += f"- Total elements in {group}: ({element_count_rounded_notation(group_elements):>4}) {group_elements}\n"
+ markdown_content += f"- Percentage of total elements: {group_percentage:.2f}%\n"
+ markdown_content += "\n\n"
+
+ print(markdown_content) # noqa: NP100
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Dump GGUF file metadata")
+ parser.add_argument("model", type=str, help="GGUF format model filename")
+ parser.add_argument("--no-tensors", action="store_true", help="Don't dump tensor metadata")
+ parser.add_argument("--json", action="store_true", help="Produce JSON output")
+ parser.add_argument("--json-array", action="store_true", help="Include full array values in JSON output (long)")
+ parser.add_argument("--data-offset", action="store_true", help="Start of data offset")
+ parser.add_argument("--data-alignment", action="store_true", help="Data alignment applied globally to data field")
+ parser.add_argument("--markdown", action="store_true", help="Produce markdown output")
+ parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+
+ args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+
+ if not args.json and not args.markdown and not args.data_offset and not args.data_alignment:
+ logger.info(f'* Loading: {args.model}')
+
+ reader = GGUFReader(args.model, 'r')
+
+ if args.json:
+ dump_metadata_json(reader, args)
+ elif args.markdown:
+ dump_markdown_metadata(reader, args)
+ elif args.data_offset:
+ print(reader.data_offset) # noqa: NP100
+ elif args.data_alignment:
+ print(reader.alignment) # noqa: NP100
+ else:
+ dump_metadata(reader, args)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_editor_gui.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_editor_gui.py
new file mode 100644
index 0000000000000000000000000000000000000000..05f4db0f8cdc89049a7e8719fcaa1fe741391413
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_editor_gui.py
@@ -0,0 +1,1621 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import logging
+import argparse
+import os
+import sys
+import numpy
+import enum
+from pathlib import Path
+from typing import Any, Optional, Tuple, Type
+import warnings
+
+import numpy as np
+from PySide6.QtWidgets import (
+ QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
+ QPushButton, QLabel, QLineEdit, QFileDialog, QTableWidget,
+ QTableWidgetItem, QComboBox, QMessageBox, QTabWidget,
+ QTextEdit, QFormLayout,
+ QHeaderView, QDialog, QDialogButtonBox
+)
+from PySide6.QtCore import Qt
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+import gguf
+from gguf import GGUFReader, GGUFWriter, GGUFValueType, ReaderField
+from gguf.constants import TokenType, RopeScalingType, PoolingType, GGMLQuantizationType
+
+logger = logging.getLogger("gguf-editor-gui")
+
+# Map of key names to enum types for automatic enum interpretation
+KEY_TO_ENUM_TYPE = {
+ gguf.Keys.Tokenizer.TOKEN_TYPE: TokenType,
+ gguf.Keys.Rope.SCALING_TYPE: RopeScalingType,
+ gguf.Keys.LLM.POOLING_TYPE: PoolingType,
+ gguf.Keys.General.FILE_TYPE: GGMLQuantizationType,
+}
+
+# Define the tokenizer keys that should be edited together
+TOKENIZER_LINKED_KEYS = [
+ gguf.Keys.Tokenizer.LIST,
+ gguf.Keys.Tokenizer.TOKEN_TYPE,
+ gguf.Keys.Tokenizer.SCORES
+]
+
+
+class TokenizerEditorDialog(QDialog):
+ def __init__(self, tokens, token_types, scores, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle("Edit Tokenizer Data")
+ self.resize(900, 600)
+
+ self.tokens = tokens.copy() if tokens else []
+ self.token_types = token_types.copy() if token_types else []
+ self.scores = scores.copy() if scores else []
+
+ # Ensure all arrays have the same length
+ max_len = max(len(self.tokens), len(self.token_types), len(self.scores))
+ if len(self.tokens) < max_len:
+ self.tokens.extend([""] * (max_len - len(self.tokens)))
+ if len(self.token_types) < max_len:
+ self.token_types.extend([0] * (max_len - len(self.token_types)))
+ if len(self.scores) < max_len:
+ self.scores.extend([0.0] * (max_len - len(self.scores)))
+
+ layout = QVBoxLayout(self)
+
+ # Add filter controls
+ filter_layout = QHBoxLayout()
+ filter_layout.addWidget(QLabel("Filter:"))
+ self.filter_edit = QLineEdit()
+ self.filter_edit.setPlaceholderText("Type to filter tokens...")
+ self.filter_edit.textChanged.connect(self.apply_filter)
+ filter_layout.addWidget(self.filter_edit)
+
+ # Add page controls
+ self.page_size = 100 # Show 100 items per page
+ self.current_page = 0
+ self.total_pages = max(1, (len(self.tokens) + self.page_size - 1) // self.page_size)
+
+ self.page_label = QLabel(f"Page 1 of {self.total_pages}")
+ filter_layout.addWidget(self.page_label)
+
+ prev_page = QPushButton("Previous")
+ prev_page.clicked.connect(self.previous_page)
+ filter_layout.addWidget(prev_page)
+
+ next_page = QPushButton("Next")
+ next_page.clicked.connect(self.next_page)
+ filter_layout.addWidget(next_page)
+
+ layout.addLayout(filter_layout)
+
+ # Tokenizer data table
+ self.tokens_table = QTableWidget()
+ self.tokens_table.setColumnCount(4)
+ self.tokens_table.setHorizontalHeaderLabels(["Index", "Token", "Type", "Score"])
+ self.tokens_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
+ self.tokens_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
+ self.tokens_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
+ self.tokens_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
+
+ layout.addWidget(self.tokens_table)
+
+ # Controls
+ controls_layout = QHBoxLayout()
+
+ add_button = QPushButton("Add Token")
+ add_button.clicked.connect(self.add_token)
+ controls_layout.addWidget(add_button)
+
+ remove_button = QPushButton("Remove Selected")
+ remove_button.clicked.connect(self.remove_selected)
+ controls_layout.addWidget(remove_button)
+
+ controls_layout.addStretch()
+
+ layout.addLayout(controls_layout)
+
+ # Buttons
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+ layout.addWidget(buttons)
+
+ # Initialize the filtered values
+ self.filtered_indices = list(range(len(self.tokens)))
+
+ # Load data for the first page
+ self.load_page()
+
+ def apply_filter(self):
+ """Filter the tokens based on the search text."""
+ filter_text = self.filter_edit.text().lower()
+
+ if not filter_text:
+ # No filter, show all values
+ self.filtered_indices = list(range(len(self.tokens)))
+ else:
+ # Apply filter
+ self.filtered_indices = []
+ for i, token in enumerate(self.tokens):
+ if filter_text in str(token).lower():
+ self.filtered_indices.append(i)
+
+ # Reset to first page and reload
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+ self.current_page = 0
+ self.page_label.setText(f"Page 1 of {self.total_pages}")
+ self.load_page()
+
+ def previous_page(self):
+ """Go to the previous page of results."""
+ if self.current_page > 0:
+ self.current_page -= 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+ self.load_page()
+
+ def next_page(self):
+ """Go to the next page of results."""
+ if self.current_page < self.total_pages - 1:
+ self.current_page += 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+ self.load_page()
+
+ def load_page(self):
+ """Load the current page of tokenizer data."""
+ self.tokens_table.setRowCount(0) # Clear the table
+
+ # Calculate start and end indices for the current page
+ start_idx = self.current_page * self.page_size
+ end_idx = min(start_idx + self.page_size, len(self.filtered_indices))
+
+ # Pre-allocate rows for better performance
+ self.tokens_table.setRowCount(end_idx - start_idx)
+
+ for row, i in enumerate(range(start_idx, end_idx)):
+ orig_idx = self.filtered_indices[i]
+
+ # Index
+ index_item = QTableWidgetItem(str(orig_idx))
+ index_item.setData(Qt.ItemDataRole.UserRole, orig_idx) # Store original index
+ index_item.setFlags(index_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tokens_table.setItem(row, 0, index_item)
+
+ # Token
+ token_item = QTableWidgetItem(str(self.tokens[orig_idx]))
+ self.tokens_table.setItem(row, 1, token_item)
+
+ # Token Type
+ token_type = self.token_types[orig_idx] if orig_idx < len(self.token_types) else 0
+ try:
+ enum_val = TokenType(token_type)
+ display_text = f"{enum_val.name} ({token_type})"
+ except (ValueError, KeyError):
+ display_text = f"Unknown ({token_type})"
+
+ type_item = QTableWidgetItem(display_text)
+ type_item.setData(Qt.ItemDataRole.UserRole, token_type)
+
+ # Make type cell editable with a double-click handler
+ type_item.setFlags(type_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tokens_table.setItem(row, 2, type_item)
+
+ # Score
+ score = self.scores[orig_idx] if orig_idx < len(self.scores) else 0.0
+ score_item = QTableWidgetItem(str(score))
+ self.tokens_table.setItem(row, 3, score_item)
+
+ # Connect double-click handler for token type cells
+ self.tokens_table.cellDoubleClicked.connect(self.handle_cell_double_click)
+
+ def handle_cell_double_click(self, row, column):
+ """Handle double-click on a cell, specifically for token type editing."""
+ if column == 2: # Token Type column
+ orig_item = self.tokens_table.item(row, 0)
+ if orig_item:
+ orig_idx = orig_item.data(Qt.ItemDataRole.UserRole)
+ self.edit_token_type(row, orig_idx)
+
+ def edit_token_type(self, row, orig_idx):
+ """Edit a token type using a dialog with a dropdown of all enum options."""
+ current_value = self.token_types[orig_idx] if orig_idx < len(self.token_types) else 0
+
+ # Create a dialog with enum options
+ dialog = QDialog(self)
+ dialog.setWindowTitle("Select Token Type")
+ layout = QVBoxLayout(dialog)
+
+ combo = QComboBox()
+ for enum_val in TokenType:
+ combo.addItem(f"{enum_val.name} ({enum_val.value})", enum_val.value)
+
+ # Set current value
+ try:
+ if isinstance(current_value, int):
+ enum_val = TokenType(current_value)
+ combo.setCurrentText(f"{enum_val.name} ({current_value})")
+ except (ValueError, KeyError):
+ pass
+
+ layout.addWidget(combo)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(dialog.accept)
+ buttons.rejected.connect(dialog.reject)
+ layout.addWidget(buttons)
+
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ # Get the selected value
+ new_value = combo.currentData()
+ enum_val = TokenType(new_value)
+ display_text = f"{enum_val.name} ({new_value})"
+
+ # Update the display
+ type_item = self.tokens_table.item(row, 2)
+ if type_item:
+ type_item.setText(display_text)
+ type_item.setData(Qt.ItemDataRole.UserRole, new_value)
+
+ # Update the actual value
+ self.token_types[orig_idx] = new_value
+
+ def add_token(self):
+ """Add a new token to the end of the list."""
+ # Add to the end of the arrays
+ self.tokens.append("")
+ self.token_types.append(0) # Default to normal token
+ self.scores.append(0.0)
+
+ orig_idx = len(self.tokens) - 1
+
+ # Add to filtered indices if it matches the current filter
+ filter_text = self.filter_edit.text().lower()
+ if not filter_text or filter_text in "":
+ self.filtered_indices.append(orig_idx)
+
+ # Update pagination
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+
+ # Go to the last page to show the new item
+ self.current_page = self.total_pages - 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+
+ # Reload the page
+ self.load_page()
+
+ def remove_selected(self):
+ """Remove selected tokens from all arrays."""
+ selected_rows = []
+ for item in self.tokens_table.selectedItems():
+ row = item.row()
+ if row not in selected_rows:
+ selected_rows.append(row)
+
+ if not selected_rows:
+ return
+
+ # Get original indices in descending order to avoid index shifting
+ orig_indices = []
+ for row in selected_rows:
+ orig_item = self.tokens_table.item(row, 0)
+ if orig_item:
+ orig_indices.append(orig_item.data(Qt.ItemDataRole.UserRole))
+ orig_indices.sort(reverse=True)
+
+ # Remove from all arrays
+ for idx in orig_indices:
+ if idx < len(self.tokens):
+ del self.tokens[idx]
+ if idx < len(self.token_types):
+ del self.token_types[idx]
+ if idx < len(self.scores):
+ del self.scores[idx]
+
+ # Rebuild filtered_indices
+ self.filtered_indices = []
+ filter_text = self.filter_edit.text().lower()
+
+ for i, token in enumerate(self.tokens):
+ if not filter_text or filter_text in str(token).lower():
+ self.filtered_indices.append(i)
+
+ # Update pagination
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+ self.current_page = min(self.current_page, self.total_pages - 1)
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+
+ # Reload the page
+ self.load_page()
+
+ def get_data(self):
+ """Return the edited tokenizer data."""
+ return self.tokens, self.token_types, self.scores
+
+
+class ArrayEditorDialog(QDialog):
+ def __init__(self, array_values, element_type, key=None, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle("Edit Array Values")
+ self.resize(700, 500)
+
+ self.array_values = array_values
+ self.element_type = element_type
+ self.key = key
+
+ # Get enum type for this array if applicable
+ self.enum_type = None
+ if key in KEY_TO_ENUM_TYPE and element_type == GGUFValueType.INT32:
+ self.enum_type = KEY_TO_ENUM_TYPE[key]
+
+ layout = QVBoxLayout(self)
+
+ # Add enum type information if applicable
+ if self.enum_type is not None:
+ enum_info_layout = QHBoxLayout()
+ enum_label = QLabel(f"Editing {self.enum_type.__name__} values:")
+ enum_info_layout.addWidget(enum_label)
+
+ # Add a legend for the enum values
+ enum_values = ", ".join([f"{e.name}={e.value}" for e in self.enum_type])
+ enum_values_label = QLabel(f"Available values: {enum_values}")
+ enum_values_label.setWordWrap(True)
+ enum_info_layout.addWidget(enum_values_label, 1)
+
+ layout.addLayout(enum_info_layout)
+
+ # Add search/filter controls
+ filter_layout = QHBoxLayout()
+ filter_layout.addWidget(QLabel("Filter:"))
+ self.filter_edit = QLineEdit()
+ self.filter_edit.setPlaceholderText("Type to filter values...")
+ self.filter_edit.textChanged.connect(self.apply_filter)
+ filter_layout.addWidget(self.filter_edit)
+
+ # Add page controls for large arrays
+ self.page_size = 100 # Show 100 items per page
+ self.current_page = 0
+ self.total_pages = max(1, (len(array_values) + self.page_size - 1) // self.page_size)
+
+ self.page_label = QLabel(f"Page 1 of {self.total_pages}")
+ filter_layout.addWidget(self.page_label)
+
+ prev_page = QPushButton("Previous")
+ prev_page.clicked.connect(self.previous_page)
+ filter_layout.addWidget(prev_page)
+
+ next_page = QPushButton("Next")
+ next_page.clicked.connect(self.next_page)
+ filter_layout.addWidget(next_page)
+
+ layout.addLayout(filter_layout)
+
+ # Array items table
+ self.items_table = QTableWidget()
+
+ # Set up columns based on whether we have an enum type
+ if self.enum_type is not None:
+ self.items_table.setColumnCount(3)
+ self.items_table.setHorizontalHeaderLabels(["Index", "Value", "Actions"])
+ self.items_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
+ self.items_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
+ self.items_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
+ else:
+ self.items_table.setColumnCount(2)
+ self.items_table.setHorizontalHeaderLabels(["Index", "Value"])
+ self.items_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
+ self.items_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
+
+ layout.addWidget(self.items_table)
+
+ # Controls
+ controls_layout = QHBoxLayout()
+
+ add_button = QPushButton("Add Item")
+ add_button.clicked.connect(self.add_item)
+ controls_layout.addWidget(add_button)
+
+ remove_button = QPushButton("Remove Selected")
+ remove_button.clicked.connect(self.remove_selected)
+ controls_layout.addWidget(remove_button)
+
+ # Add bulk edit button for enum arrays
+ if self.enum_type is not None:
+ bulk_edit_button = QPushButton("Bulk Edit Selected")
+ bulk_edit_button.clicked.connect(self.bulk_edit_selected)
+ controls_layout.addWidget(bulk_edit_button)
+
+ controls_layout.addStretch()
+
+ layout.addLayout(controls_layout)
+
+ # Buttons
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+ layout.addWidget(buttons)
+
+ # Initialize the filtered values
+ self.filtered_indices = list(range(len(self.array_values)))
+
+ # Load array values for the first page
+ self.load_page()
+
+ def apply_filter(self):
+ """Filter the array values based on the search text."""
+ filter_text = self.filter_edit.text().lower()
+
+ if not filter_text:
+ # No filter, show all values
+ self.filtered_indices = list(range(len(self.array_values)))
+ else:
+ # Apply filter
+ self.filtered_indices = []
+ for i, value in enumerate(self.array_values):
+ # For enum values, search in both name and value
+ if self.enum_type is not None and isinstance(value, int):
+ try:
+ enum_val = self.enum_type(value)
+ display_text = f"{enum_val.name} ({value})".lower()
+ if filter_text in display_text:
+ self.filtered_indices.append(i)
+ except (ValueError, KeyError):
+ # If not a valid enum value, just check the raw value
+ if filter_text in str(value).lower():
+ self.filtered_indices.append(i)
+ else:
+ # For non-enum values, just check the string representation
+ if filter_text in str(value).lower():
+ self.filtered_indices.append(i)
+
+ # Reset to first page and reload
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+ self.current_page = 0
+ self.page_label.setText(f"Page 1 of {self.total_pages}")
+ self.load_page()
+
+ def previous_page(self):
+ """Go to the previous page of results."""
+ if self.current_page > 0:
+ self.current_page -= 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+ self.load_page()
+
+ def next_page(self):
+ """Go to the next page of results."""
+ if self.current_page < self.total_pages - 1:
+ self.current_page += 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+ self.load_page()
+
+ def load_page(self):
+ """Load the current page of array values."""
+ self.items_table.setRowCount(0) # Clear the table
+
+ # Calculate start and end indices for the current page
+ start_idx = self.current_page * self.page_size
+ end_idx = min(start_idx + self.page_size, len(self.filtered_indices))
+
+ # Pre-allocate rows for better performance
+ self.items_table.setRowCount(end_idx - start_idx)
+
+ for row, i in enumerate(range(start_idx, end_idx)):
+ orig_idx = self.filtered_indices[i]
+ value = self.array_values[orig_idx]
+
+ # Index
+ index_item = QTableWidgetItem(str(orig_idx))
+ index_item.setData(Qt.ItemDataRole.UserRole, orig_idx) # Store original index
+ index_item.setFlags(index_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.items_table.setItem(row, 0, index_item)
+
+ # Value
+ if self.enum_type is not None:
+ # Display enum value and name
+ try:
+ if isinstance(value, (int, numpy.signedinteger)):
+ enum_val = self.enum_type(value)
+ display_text = f"{enum_val.name} ({value})"
+ else:
+ display_text = str(value)
+ except (ValueError, KeyError):
+ display_text = f"Unknown ({value})"
+
+ # Store the enum value in the item
+ value_item = QTableWidgetItem(display_text)
+ value_item.setData(Qt.ItemDataRole.UserRole, value)
+ value_item.setFlags(value_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.items_table.setItem(row, 1, value_item)
+
+ # Add an edit button in a separate column
+ edit_button = QPushButton("Edit")
+ edit_button.setProperty("row", row)
+ edit_button.clicked.connect(self.edit_array_enum_value)
+
+ # Create a widget to hold the button
+ button_widget = QWidget()
+ button_layout = QHBoxLayout(button_widget)
+ button_layout.setContentsMargins(2, 2, 2, 2)
+ button_layout.addWidget(edit_button)
+ button_layout.addStretch()
+
+ self.items_table.setCellWidget(row, 2, button_widget)
+ else:
+ value_item = QTableWidgetItem(str(value))
+ self.items_table.setItem(row, 1, value_item)
+
+ def edit_array_enum_value(self):
+ """Handle editing an enum value in the array editor."""
+ button = self.sender()
+ row = button.property("row")
+
+ # Get the original index from the table item
+ orig_item = self.items_table.item(row, 0)
+ new_item = self.items_table.item(row, 1)
+ if orig_item and new_item and self.enum_type and self.edit_enum_value(row, self.enum_type):
+ orig_idx = orig_item.data(Qt.ItemDataRole.UserRole)
+ new_value = new_item.data(Qt.ItemDataRole.UserRole)
+ # Update the stored value in the array
+ if isinstance(new_value, (int, float, str, bool)):
+ self.array_values[orig_idx] = new_value
+
+ def bulk_edit_selected(self):
+ """Edit multiple enum values at once."""
+ if not self.enum_type:
+ return
+
+ selected_rows = set()
+ for item in self.items_table.selectedItems():
+ selected_rows.add(item.row())
+
+ if not selected_rows:
+ QMessageBox.information(self, "No Selection", "Please select at least one row to edit.")
+ return
+
+ # Create a dialog with enum options
+ dialog = QDialog(self)
+ dialog.setWindowTitle(f"Bulk Edit {self.enum_type.__name__} Values")
+ layout = QVBoxLayout(dialog)
+
+ layout.addWidget(QLabel(f"Set {len(selected_rows)} selected items to:"))
+
+ combo = QComboBox()
+ for enum_val in self.enum_type:
+ combo.addItem(f"{enum_val.name} ({enum_val.value})", enum_val.value)
+
+ layout.addWidget(combo)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(dialog.accept)
+ buttons.rejected.connect(dialog.reject)
+ layout.addWidget(buttons)
+
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ # Get the selected value
+ new_value = combo.currentData()
+ enum_val = self.enum_type(new_value)
+ display_text = f"{enum_val.name} ({new_value})"
+
+ # Update all selected rows
+ for row in selected_rows:
+ orig_item = self.items_table.item(row, 0)
+ new_item = self.items_table.item(row, 1)
+ if orig_item and new_item:
+ orig_idx = orig_item.data(Qt.ItemDataRole.UserRole)
+ self.array_values[orig_idx] = new_value
+
+ # Update the display
+ new_item.setText(display_text)
+ new_item.setData(Qt.ItemDataRole.UserRole, new_value)
+
+ def add_item(self):
+ # Add to the end of the array
+ orig_idx = len(self.array_values)
+
+ # Add default value based on type
+ if self.enum_type is not None:
+ # Default to first enum value
+ default_value = list(self.enum_type)[0].value
+ self.array_values.append(default_value)
+ else:
+ if self.element_type == GGUFValueType.STRING:
+ self.array_values.append("")
+ else:
+ self.array_values.append(0)
+
+ # Add to filtered indices if it matches the current filter
+ self.filtered_indices.append(orig_idx)
+
+ # Update pagination
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+
+ # Go to the last page to show the new item
+ self.current_page = self.total_pages - 1
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+
+ # Reload the page
+ self.load_page()
+
+ def remove_selected(self):
+ selected_rows = []
+ for item in self.items_table.selectedItems():
+ row = item.row()
+ if row not in selected_rows:
+ selected_rows.append(row)
+
+ if not selected_rows:
+ return
+
+ # Get original indices in descending order to avoid index shifting
+ orig_indices = list()
+ for row in selected_rows:
+ orig_item = self.items_table.item(row, 0)
+ if orig_item:
+ orig_indices.append(orig_item.data(Qt.ItemDataRole.UserRole))
+ orig_indices.sort(reverse=True)
+
+ # Remove from array_values
+ for idx in orig_indices:
+ del self.array_values[idx]
+
+ # Rebuild filtered_indices
+ self.filtered_indices = []
+ filter_text = self.filter_edit.text().lower()
+
+ for i, value in enumerate(self.array_values):
+ if not filter_text:
+ self.filtered_indices.append(i)
+ else:
+ # Apply filter
+ if self.enum_type is not None and isinstance(value, int):
+ try:
+ enum_val = self.enum_type(value)
+ display_text = f"{enum_val.name} ({value})".lower()
+ if filter_text in display_text:
+ self.filtered_indices.append(i)
+ except (ValueError, KeyError):
+ if filter_text in str(value).lower():
+ self.filtered_indices.append(i)
+ else:
+ if filter_text in str(value).lower():
+ self.filtered_indices.append(i)
+
+ # Update pagination
+ self.total_pages = max(1, (len(self.filtered_indices) + self.page_size - 1) // self.page_size)
+ self.current_page = min(self.current_page, self.total_pages - 1)
+ self.page_label.setText(f"Page {self.current_page + 1} of {self.total_pages}")
+
+ # Reload the page
+ self.load_page()
+
+ def edit_enum_value(self, row: int, enum_type: Type[enum.Enum]):
+ """Edit an enum value using a dialog with a dropdown of all enum options."""
+ # Get the original index from the table item
+ orig_item = self.items_table.item(row, 0)
+ if orig_item:
+ orig_idx = orig_item.data(Qt.ItemDataRole.UserRole)
+ else:
+ return
+ current_value = self.array_values[orig_idx]
+
+ # Create a dialog with enum options
+ dialog = QDialog(self)
+ dialog.setWindowTitle(f"Select {enum_type.__name__} Value")
+ layout = QVBoxLayout(dialog)
+
+ # Add description
+ description = QLabel(f"Select a {enum_type.__name__} value:")
+ layout.addWidget(description)
+
+ # Use a combo box for quick selection
+ combo = QComboBox()
+ for enum_val in enum_type:
+ combo.addItem(f"{enum_val.name} ({enum_val.value})", enum_val.value)
+
+ # Set current value
+ try:
+ if isinstance(current_value, int):
+ enum_val = enum_type(current_value)
+ combo.setCurrentText(f"{enum_val.name} ({current_value})")
+ except (ValueError, KeyError):
+ pass
+
+ layout.addWidget(combo)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(dialog.accept)
+ buttons.rejected.connect(dialog.reject)
+ layout.addWidget(buttons)
+
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ # Update the value display and stored data
+ new_value = combo.currentData()
+ enum_val = enum_type(new_value)
+ display_text = f"{enum_val.name} ({new_value})"
+
+ new_item = self.items_table.item(row, 1)
+ if new_item:
+ new_item.setText(display_text)
+ new_item.setData(Qt.ItemDataRole.UserRole, new_value)
+
+ # Update the actual array value
+ self.array_values[orig_idx] = new_value
+ return True
+ return False
+
+ def get_array_values(self):
+ # The array_values list is kept up-to-date as edits are made
+ return self.array_values
+
+
+class AddMetadataDialog(QDialog):
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self.setWindowTitle("Add Metadata")
+ self.resize(400, 200)
+
+ layout = QVBoxLayout(self)
+
+ form_layout = QFormLayout()
+
+ self.key_edit = QLineEdit()
+ form_layout.addRow("Key:", self.key_edit)
+
+ self.type_combo = QComboBox()
+ for value_type in GGUFValueType:
+ if value_type != GGUFValueType.ARRAY: # Skip array type for simplicity
+ self.type_combo.addItem(value_type.name, value_type)
+ form_layout.addRow("Type:", self.type_combo)
+
+ self.value_edit = QTextEdit()
+ form_layout.addRow("Value:", self.value_edit)
+
+ layout.addLayout(form_layout)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(self.accept)
+ buttons.rejected.connect(self.reject)
+ layout.addWidget(buttons)
+
+ def get_data(self) -> Tuple[str, GGUFValueType, Any]:
+ key = self.key_edit.text()
+ value_type = self.type_combo.currentData()
+ value_text = self.value_edit.toPlainText()
+
+ # Convert value based on type
+ if value_type == GGUFValueType.UINT8:
+ value = np.uint8(int(value_text))
+ elif value_type == GGUFValueType.INT8:
+ value = np.int8(int(value_text))
+ elif value_type == GGUFValueType.UINT16:
+ value = np.uint16(int(value_text))
+ elif value_type == GGUFValueType.INT16:
+ value = np.int16(int(value_text))
+ elif value_type == GGUFValueType.UINT32:
+ value = np.uint32(int(value_text))
+ elif value_type == GGUFValueType.INT32:
+ value = np.int32(int(value_text))
+ elif value_type == GGUFValueType.FLOAT32:
+ value = np.float32(float(value_text))
+ elif value_type == GGUFValueType.BOOL:
+ value = value_text.lower() in ('true', 'yes', '1')
+ elif value_type == GGUFValueType.STRING:
+ value = value_text
+ else:
+ value = value_text
+
+ return key, value_type, value
+
+
+class GGUFEditorWindow(QMainWindow):
+ def __init__(self):
+ super().__init__()
+
+ self.setWindowTitle("GGUF Editor")
+ self.resize(1000, 800)
+
+ self.current_file = None
+ self.reader = None
+ self.modified = False
+ self.metadata_changes = {} # Store changes to apply when saving
+ self.metadata_to_remove = set() # Store keys to remove when saving
+ self.on_metadata_changed_is_connected = False
+
+ self.setup_ui()
+
+ def setup_ui(self):
+ central_widget = QWidget()
+ self.setCentralWidget(central_widget)
+
+ main_layout = QVBoxLayout(central_widget)
+
+ # File controls
+ file_layout = QHBoxLayout()
+
+ self.file_path_edit = QLineEdit()
+ self.file_path_edit.setReadOnly(True)
+ file_layout.addWidget(self.file_path_edit)
+
+ open_button = QPushButton("Open GGUF")
+ open_button.clicked.connect(self.open_file)
+ file_layout.addWidget(open_button)
+
+ save_button = QPushButton("Save As...")
+ save_button.clicked.connect(self.save_file)
+ file_layout.addWidget(save_button)
+
+ main_layout.addLayout(file_layout)
+
+ # Tabs for different views
+ self.tabs = QTabWidget()
+
+ # Metadata tab
+ self.metadata_tab = QWidget()
+ metadata_layout = QVBoxLayout(self.metadata_tab)
+
+ # Metadata table
+ self.metadata_table = QTableWidget()
+ self.metadata_table.setColumnCount(4)
+ self.metadata_table.setHorizontalHeaderLabels(["Key", "Type", "Value", "Actions"])
+ self.metadata_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
+ self.metadata_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
+ self.metadata_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
+ self.metadata_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
+ metadata_layout.addWidget(self.metadata_table)
+
+ # Metadata controls
+ metadata_controls = QHBoxLayout()
+
+ add_metadata_button = QPushButton("Add Metadata")
+ add_metadata_button.clicked.connect(self.add_metadata)
+ metadata_controls.addWidget(add_metadata_button)
+
+ metadata_controls.addStretch()
+
+ metadata_layout.addLayout(metadata_controls)
+
+ # Tensors tab
+ self.tensors_tab = QWidget()
+ tensors_layout = QVBoxLayout(self.tensors_tab)
+
+ self.tensors_table = QTableWidget()
+ self.tensors_table.setColumnCount(5)
+ self.tensors_table.setHorizontalHeaderLabels(["Name", "Type", "Shape", "Elements", "Size (bytes)"])
+ self.tensors_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
+ self.tensors_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
+ self.tensors_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
+ self.tensors_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
+ self.tensors_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
+ tensors_layout.addWidget(self.tensors_table)
+
+ # Add tabs to tab widget
+ self.tabs.addTab(self.metadata_tab, "Metadata")
+ self.tabs.addTab(self.tensors_tab, "Tensors")
+
+ main_layout.addWidget(self.tabs)
+
+ # Status bar
+ self.statusBar().showMessage("Ready")
+
+ def load_file(self, file_path):
+ """Load a GGUF file by path"""
+ try:
+ self.statusBar().showMessage(f"Loading {file_path}...")
+ QApplication.processEvents()
+
+ self.reader = GGUFReader(file_path, 'r')
+ self.current_file = file_path
+ self.file_path_edit.setText(file_path)
+
+ self.load_metadata()
+ self.load_tensors()
+
+ self.metadata_changes = {}
+ self.metadata_to_remove = set()
+ self.modified = False
+
+ self.statusBar().showMessage(f"Loaded {file_path}")
+ return True
+ except Exception as e:
+ QMessageBox.critical(self, "Error", f"Failed to open file: {str(e)}")
+ self.statusBar().showMessage("Error loading file")
+ return False
+
+ def open_file(self):
+ file_path, _ = QFileDialog.getOpenFileName(
+ self, "Open GGUF File", "", "GGUF Files (*.gguf);;All Files (*)"
+ )
+
+ if not file_path:
+ return
+
+ self.load_file(file_path)
+
+ def load_metadata(self):
+ self.metadata_table.setRowCount(0)
+
+ if not self.reader:
+ return
+
+ # Disconnect to prevent triggering during loading
+ if self.on_metadata_changed_is_connected:
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore')
+ self.metadata_table.itemChanged.disconnect(self.on_metadata_changed)
+ self.on_metadata_changed_is_connected = False
+
+ for i, (key, field) in enumerate(self.reader.fields.items()):
+ self.metadata_table.insertRow(i)
+
+ # Key
+ key_item = QTableWidgetItem(key)
+ key_item.setFlags(key_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.metadata_table.setItem(i, 0, key_item)
+
+ # Type
+ if not field.types:
+ type_str = "N/A"
+ elif field.types[0] == GGUFValueType.ARRAY:
+ nest_count = len(field.types) - 1
+ element_type = field.types[-1].name
+ # Check if this is an enum array
+ enum_type = self.get_enum_for_key(key)
+ if enum_type is not None and field.types[-1] == GGUFValueType.INT32:
+ element_type = enum_type.__name__
+ type_str = '[' * nest_count + element_type + ']' * nest_count
+ else:
+ type_str = str(field.types[0].name)
+ # Check if this is an enum field
+ enum_type = self.get_enum_for_key(key)
+ if enum_type is not None and field.types[0] == GGUFValueType.INT32:
+ type_str = enum_type.__name__
+
+ type_item = QTableWidgetItem(type_str)
+ type_item.setFlags(type_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.metadata_table.setItem(i, 1, type_item)
+
+ # Value
+ value_str = self.format_field_value(field)
+ value_item = QTableWidgetItem(value_str)
+
+ # Make only simple values editable
+ if len(field.types) == 1 and field.types[0] != GGUFValueType.ARRAY:
+ value_item.setFlags(value_item.flags() | Qt.ItemFlag.ItemIsEditable)
+ else:
+ value_item.setFlags(value_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+
+ self.metadata_table.setItem(i, 2, value_item)
+
+ # Actions
+ actions_widget = QWidget()
+ actions_layout = QHBoxLayout(actions_widget)
+ actions_layout.setContentsMargins(2, 2, 2, 2)
+
+ # Add Edit button for arrays and enum fields
+ if field.types and field.types[0] == GGUFValueType.ARRAY:
+ edit_button = QPushButton("Edit")
+ edit_button.setProperty("row", i)
+ edit_button.setProperty("key", key)
+ edit_button.clicked.connect(self.edit_array_metadata)
+ actions_layout.addWidget(edit_button)
+
+ # Add special label for tokenizer linked fields
+ if key in TOKENIZER_LINKED_KEYS:
+ edit_button.setText("Edit Tokenizer")
+ edit_button.setToolTip("Edit all tokenizer data together")
+ elif len(field.types) == 1 and self.get_enum_for_key(key) is not None:
+ edit_button = QPushButton("Edit")
+ edit_button.setProperty("row", i)
+ edit_button.setProperty("key", key)
+ edit_button.clicked.connect(self.edit_metadata_enum)
+ actions_layout.addWidget(edit_button)
+
+ remove_button = QPushButton("Remove")
+ remove_button.setProperty("row", i)
+ remove_button.setProperty("key", key)
+ remove_button.clicked.connect(self.remove_metadata)
+ actions_layout.addWidget(remove_button)
+
+ self.metadata_table.setCellWidget(i, 3, actions_widget)
+
+ # Reconnect after loading
+ self.metadata_table.itemChanged.connect(self.on_metadata_changed)
+ self.on_metadata_changed_is_connected = True
+
+ def extract_array_values(self, field: ReaderField) -> list:
+ """Extract all values from an array field."""
+ if not field.types or field.types[0] != GGUFValueType.ARRAY:
+ return []
+
+ curr_type = field.types[1]
+ array_values = []
+ total_elements = len(field.data)
+
+ if curr_type == GGUFValueType.STRING:
+ for element_pos in range(total_elements):
+ value_string = str(bytes(field.parts[-1 - (total_elements - element_pos - 1) * 2]), encoding='utf-8')
+ array_values.append(value_string)
+ elif self.reader and curr_type in self.reader.gguf_scalar_to_np:
+ for element_pos in range(total_elements):
+ array_values.append(field.parts[-1 - (total_elements - element_pos - 1)][0])
+
+ return array_values
+
+ def get_enum_for_key(self, key: str) -> Optional[Type[enum.Enum]]:
+ """Get the enum type for a given key if it exists."""
+ return KEY_TO_ENUM_TYPE.get(key)
+
+ def format_enum_value(self, value: Any, enum_type: Type[enum.Enum]) -> str:
+ """Format a value as an enum if possible."""
+ try:
+ if isinstance(value, (int, str)):
+ enum_value = enum_type(value)
+ return f"{enum_value.name} ({value})"
+ except (ValueError, KeyError):
+ pass
+ return str(value)
+
+ def format_field_value(self, field: ReaderField) -> str:
+ if not field.types:
+ return "N/A"
+
+ if len(field.types) == 1:
+ curr_type = field.types[0]
+ if curr_type == GGUFValueType.STRING:
+ return str(bytes(field.parts[-1]), encoding='utf-8')
+ elif self.reader and curr_type in self.reader.gguf_scalar_to_np:
+ value = field.parts[-1][0]
+ # Check if this field has an enum type
+ enum_type = self.get_enum_for_key(field.name)
+ if enum_type is not None:
+ return self.format_enum_value(value, enum_type)
+ return str(value)
+
+ if field.types[0] == GGUFValueType.ARRAY:
+ array_values = self.extract_array_values(field)
+ render_element = min(5, len(array_values))
+
+ # Get enum type for this array if applicable
+ enum_type = self.get_enum_for_key(field.name)
+
+ if enum_type is not None:
+ array_elements = []
+ for i in range(render_element):
+ array_elements.append(self.format_enum_value(array_values[i], enum_type))
+ else:
+ array_elements = [str(array_values[i]) for i in range(render_element)]
+
+ return f"[ {', '.join(array_elements).strip()}{', ...' if len(array_values) > len(array_elements) else ''} ]"
+
+ return "Complex value"
+
+ def load_tensors(self):
+ self.tensors_table.setRowCount(0)
+
+ if not self.reader:
+ return
+
+ for i, tensor in enumerate(self.reader.tensors):
+ self.tensors_table.insertRow(i)
+
+ # Name
+ name_item = QTableWidgetItem(tensor.name)
+ name_item.setFlags(name_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tensors_table.setItem(i, 0, name_item)
+
+ # Type
+ type_item = QTableWidgetItem(tensor.tensor_type.name)
+ type_item.setFlags(type_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tensors_table.setItem(i, 1, type_item)
+
+ # Shape
+ shape_str = " × ".join(str(d) for d in tensor.shape)
+ shape_item = QTableWidgetItem(shape_str)
+ shape_item.setFlags(shape_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tensors_table.setItem(i, 2, shape_item)
+
+ # Elements
+ elements_item = QTableWidgetItem(str(tensor.n_elements))
+ elements_item.setFlags(elements_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tensors_table.setItem(i, 3, elements_item)
+
+ # Size
+ size_item = QTableWidgetItem(f"{tensor.n_bytes:,}")
+ size_item.setFlags(size_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.tensors_table.setItem(i, 4, size_item)
+
+ def on_metadata_changed(self, item):
+ if item.column() != 2: # Only handle value column changes
+ return
+
+ row = item.row()
+ orig_item = self.metadata_table.item(row, 0)
+ key = None
+ if orig_item:
+ key = orig_item.text()
+ new_value = item.text()
+
+ field = None
+ if self.reader and key:
+ field = self.reader.get_field(key)
+ if not field or not field.types or not key:
+ return
+
+ value_type = field.types[0]
+
+ # Check if this is an enum field
+ enum_type = self.get_enum_for_key(key)
+ if enum_type is not None and value_type == GGUFValueType.INT32:
+ # Try to parse the enum value from the text
+ try:
+ # Check if it's a name
+ try:
+ enum_val = enum_type[new_value]
+ converted_value = enum_val.value
+ except (KeyError, AttributeError):
+ # Check if it's a number or "NAME (value)" format
+ if '(' in new_value and ')' in new_value:
+ # Extract the value from "NAME (value)" format
+ value_part = new_value.split('(')[1].split(')')[0].strip()
+ converted_value = int(value_part)
+ else:
+ # Try to convert directly to int
+ converted_value = int(new_value)
+
+ # Validate that it's a valid enum value
+ enum_type(converted_value)
+
+ # Store the change
+ self.metadata_changes[key] = (value_type, converted_value)
+ self.modified = True
+
+ # Update display with formatted enum value
+ formatted_value = self.format_enum_value(converted_value, enum_type)
+ item.setText(formatted_value)
+
+ self.statusBar().showMessage(f"Changed {key} to {formatted_value}")
+ return
+ except (ValueError, KeyError) as e:
+ QMessageBox.warning(
+ self,
+ f"Invalid Enum Value ({e})",
+ f"'{new_value}' is not a valid {enum_type.__name__} value.\n"
+ f"Valid values are: {', '.join(v.name for v in enum_type)}")
+
+ # Revert to original value
+ original_value = self.format_field_value(field)
+ item.setText(original_value)
+ return
+
+ try:
+ # Convert the string value to the appropriate type
+ if value_type == GGUFValueType.UINT8:
+ converted_value = np.uint8(int(new_value))
+ elif value_type == GGUFValueType.INT8:
+ converted_value = np.int8(int(new_value))
+ elif value_type == GGUFValueType.UINT16:
+ converted_value = np.uint16(int(new_value))
+ elif value_type == GGUFValueType.INT16:
+ converted_value = np.int16(int(new_value))
+ elif value_type == GGUFValueType.UINT32:
+ converted_value = np.uint32(int(new_value))
+ elif value_type == GGUFValueType.INT32:
+ converted_value = np.int32(int(new_value))
+ elif value_type == GGUFValueType.FLOAT32:
+ converted_value = np.float32(float(new_value))
+ elif value_type == GGUFValueType.BOOL:
+ converted_value = new_value.lower() in ('true', 'yes', '1')
+ elif value_type == GGUFValueType.STRING:
+ converted_value = new_value
+ else:
+ # Unsupported type for editing
+ return
+
+ # Store the change
+ self.metadata_changes[key] = (value_type, converted_value)
+ self.modified = True
+
+ self.statusBar().showMessage(f"Changed {key} to {new_value}")
+ except ValueError:
+ QMessageBox.warning(self, "Invalid Value", f"The value '{new_value}' is not valid for type {value_type.name}")
+
+ # Revert to original value
+ original_value = self.format_field_value(field)
+ item.setText(original_value)
+
+ def remove_metadata(self):
+ button = self.sender()
+ key = button.property("key")
+ row = button.property("row")
+
+ reply = QMessageBox.question(
+ self, "Confirm Removal",
+ f"Are you sure you want to remove the metadata key '{key}'?",
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No
+ )
+
+ if reply == QMessageBox.StandardButton.Yes:
+ self.metadata_table.removeRow(row)
+ self.metadata_to_remove.add(key)
+
+ # If we previously had changes for this key, remove them
+ if key in self.metadata_changes:
+ del self.metadata_changes[key]
+
+ self.modified = True
+ self.statusBar().showMessage(f"Marked {key} for removal")
+
+ def edit_metadata_enum(self):
+ """Edit an enum metadata field."""
+ button = self.sender()
+ key = button.property("key")
+ row = button.property("row")
+
+ field = None
+ if self.reader:
+ field = self.reader.get_field(key)
+ if not field or not field.types:
+ return
+
+ enum_type = self.get_enum_for_key(key)
+ if enum_type is None:
+ return
+
+ # Get current value
+ current_value = field.contents()
+
+ # Create a dialog with enum options
+ dialog = QDialog(self)
+ dialog.setWindowTitle(f"Select {enum_type.__name__} Value")
+ layout = QVBoxLayout(dialog)
+
+ combo = QComboBox()
+ for enum_val in enum_type:
+ combo.addItem(f"{enum_val.name} ({enum_val.value})", enum_val.value)
+
+ # Set current value
+ try:
+ if isinstance(current_value, (int, str)):
+ enum_val = enum_type(current_value)
+ combo.setCurrentText(f"{enum_val.name} ({current_value})")
+ except (ValueError, KeyError):
+ pass
+
+ layout.addWidget(combo)
+
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
+ buttons.accepted.connect(dialog.accept)
+ buttons.rejected.connect(dialog.reject)
+ layout.addWidget(buttons)
+
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ # Get the selected value
+ new_value = combo.currentData()
+ enum_val = enum_type(new_value)
+
+ # Store the change
+ self.metadata_changes[key] = (field.types[0], new_value)
+ self.modified = True
+
+ # Update display
+ display_text = f"{enum_val.name} ({new_value})"
+ target_item = self.metadata_table.item(row, 2)
+ if target_item:
+ target_item.setText(display_text)
+
+ self.statusBar().showMessage(f"Changed {key} to {display_text}")
+
+ def edit_array_metadata(self):
+ button = self.sender()
+ key = button.property("key")
+ row = button.property("row")
+
+ # Check if this is one of the linked tokenizer keys
+ if key in TOKENIZER_LINKED_KEYS:
+ self.edit_tokenizer_metadata(key)
+ return
+
+ field = None
+ if self.reader:
+ field = self.reader.get_field(key)
+ if not field or not field.types or field.types[0] != GGUFValueType.ARRAY:
+ return
+
+ # Get array element type
+ element_type = field.types[1]
+
+ # Extract array values
+ array_values = self.extract_array_values(field)
+
+ # Open array editor dialog
+ dialog = ArrayEditorDialog(array_values, element_type, key, self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ new_values = dialog.get_array_values()
+
+ # Store the change
+ self.metadata_changes[key] = (GGUFValueType.ARRAY, (element_type, new_values))
+ self.modified = True
+
+ # Update display
+ enum_type = self.get_enum_for_key(key)
+ if enum_type is not None and element_type == GGUFValueType.INT32:
+ value_str = f"[ {', '.join(self.format_enum_value(v, enum_type) for v in new_values[:5])}{', ...' if len(new_values) > 5 else ''} ]"
+ else:
+ value_str = f"[ {', '.join(str(v) for v in new_values[:5])}{', ...' if len(new_values) > 5 else ''} ]"
+ target_item = self.metadata_table.item(row, 2)
+ if target_item:
+ target_item.setText(value_str)
+
+ self.statusBar().showMessage(f"Updated array values for {key}")
+
+ def edit_tokenizer_metadata(self, trigger_key):
+ """Edit the linked tokenizer metadata arrays together."""
+ if not self.reader:
+ return
+
+ # Get all three fields
+ tokens_field = self.reader.get_field(gguf.Keys.Tokenizer.LIST)
+ token_types_field = self.reader.get_field(gguf.Keys.Tokenizer.TOKEN_TYPE)
+ scores_field = self.reader.get_field(gguf.Keys.Tokenizer.SCORES)
+
+ # Extract values from each field
+ tokens = self.extract_array_values(tokens_field) if tokens_field else []
+ token_types = self.extract_array_values(token_types_field) if token_types_field else []
+ scores = self.extract_array_values(scores_field) if scores_field else []
+
+ # Apply any pending changes
+ if gguf.Keys.Tokenizer.LIST in self.metadata_changes:
+ _, (_, tokens) = self.metadata_changes[gguf.Keys.Tokenizer.LIST]
+ if gguf.Keys.Tokenizer.TOKEN_TYPE in self.metadata_changes:
+ _, (_, token_types) = self.metadata_changes[gguf.Keys.Tokenizer.TOKEN_TYPE]
+ if gguf.Keys.Tokenizer.SCORES in self.metadata_changes:
+ _, (_, scores) = self.metadata_changes[gguf.Keys.Tokenizer.SCORES]
+
+ # Open the tokenizer editor dialog
+ dialog = TokenizerEditorDialog(tokens, token_types, scores, self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ new_tokens, new_token_types, new_scores = dialog.get_data()
+
+ # Store changes for all three arrays
+ if tokens_field:
+ self.metadata_changes[gguf.Keys.Tokenizer.LIST] = (
+ GGUFValueType.ARRAY,
+ (tokens_field.types[1], new_tokens)
+ )
+
+ if token_types_field:
+ self.metadata_changes[gguf.Keys.Tokenizer.TOKEN_TYPE] = (
+ GGUFValueType.ARRAY,
+ (token_types_field.types[1], new_token_types)
+ )
+
+ if scores_field:
+ self.metadata_changes[gguf.Keys.Tokenizer.SCORES] = (
+ GGUFValueType.ARRAY,
+ (scores_field.types[1], new_scores)
+ )
+
+ self.modified = True
+
+ # Update display for all three fields
+ self.update_tokenizer_display(gguf.Keys.Tokenizer.LIST, new_tokens)
+ self.update_tokenizer_display(gguf.Keys.Tokenizer.TOKEN_TYPE, new_token_types)
+ self.update_tokenizer_display(gguf.Keys.Tokenizer.SCORES, new_scores)
+
+ self.statusBar().showMessage("Updated tokenizer data")
+
+ def update_tokenizer_display(self, key, values):
+ """Update the display of a tokenizer field in the metadata table."""
+ for row in range(self.metadata_table.rowCount()):
+ key_item = self.metadata_table.item(row, 0)
+ if key_item and key_item.text() == key:
+ value_str = f"[ {', '.join(str(v) for v in values[:5])}{', ...' if len(values) > 5 else ''} ]"
+ value_item = self.metadata_table.item(row, 2)
+ if value_item:
+ value_item.setText(value_str)
+ break
+
+ def add_metadata(self):
+ dialog = AddMetadataDialog(self)
+ if dialog.exec() == QDialog.DialogCode.Accepted:
+ key, value_type, value = dialog.get_data()
+
+ if not key:
+ QMessageBox.warning(self, "Invalid Key", "Key cannot be empty")
+ return
+
+ # Check if key already exists
+ for row in range(self.metadata_table.rowCount()):
+ orig_item = self.metadata_table.item(row, 0)
+ if orig_item and orig_item.text() == key:
+ QMessageBox.warning(self, "Duplicate Key", f"Key '{key}' already exists")
+ return
+
+ # Add to table
+ row = self.metadata_table.rowCount()
+ self.metadata_table.insertRow(row)
+
+ # Key
+ key_item = QTableWidgetItem(key)
+ key_item.setFlags(key_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.metadata_table.setItem(row, 0, key_item)
+
+ # Type
+ type_item = QTableWidgetItem(value_type.name)
+ type_item.setFlags(type_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
+ self.metadata_table.setItem(row, 1, type_item)
+
+ # Value
+ value_item = QTableWidgetItem(str(value))
+ value_item.setFlags(value_item.flags() | Qt.ItemFlag.ItemIsEditable)
+ self.metadata_table.setItem(row, 2, value_item)
+
+ # Actions
+ actions_widget = QWidget()
+ actions_layout = QHBoxLayout(actions_widget)
+ actions_layout.setContentsMargins(2, 2, 2, 2)
+
+ remove_button = QPushButton("Remove")
+ remove_button.setProperty("row", row)
+ remove_button.setProperty("key", key)
+ remove_button.clicked.connect(self.remove_metadata)
+ actions_layout.addWidget(remove_button)
+
+ self.metadata_table.setCellWidget(row, 3, actions_widget)
+
+ # Store the change
+ self.metadata_changes[key] = (value_type, value)
+ self.modified = True
+
+ self.statusBar().showMessage(f"Added new metadata key {key}")
+
+ def save_file(self):
+ if not self.reader:
+ QMessageBox.warning(self, "No File Open", "Please open a GGUF file first")
+ return
+
+ if not self.modified and not self.metadata_changes and not self.metadata_to_remove:
+ QMessageBox.information(self, "No Changes", "No changes to save")
+ return
+
+ file_path, _ = QFileDialog.getSaveFileName(
+ self, "Save GGUF File As", "", "GGUF Files (*.gguf);;All Files (*)"
+ )
+
+ if not file_path:
+ return
+
+ try:
+ self.statusBar().showMessage(f"Saving to {file_path}...")
+ QApplication.processEvents()
+
+ # Get architecture and endianness from the original file
+ arch = 'unknown'
+ field = self.reader.get_field(gguf.Keys.General.ARCHITECTURE)
+ if field:
+ arch = field.contents()
+
+ # Create writer
+ writer = GGUFWriter(file_path, arch=arch, endianess=self.reader.endianess)
+
+ # Get alignment if present
+ alignment = None
+ field = self.reader.get_field(gguf.Keys.General.ALIGNMENT)
+ if field:
+ alignment = field.contents()
+ if alignment is not None:
+ writer.data_alignment = alignment
+
+ # Copy metadata with changes
+ for field in self.reader.fields.values():
+ # Skip virtual fields and fields written by GGUFWriter
+ if field.name == gguf.Keys.General.ARCHITECTURE or field.name.startswith('GGUF.'):
+ continue
+
+ # Skip fields marked for removal
+ if field.name in self.metadata_to_remove:
+ continue
+
+ # Apply changes if any
+ sub_type = None
+ if field.name in self.metadata_changes:
+ value_type, value = self.metadata_changes[field.name]
+ if value_type == GGUFValueType.ARRAY:
+ # Handle array values
+ sub_type, value = value
+ else:
+ # Copy original value
+ value = field.contents()
+ value_type = field.types[0]
+ if value_type == GGUFValueType.ARRAY:
+ sub_type = field.types[-1]
+
+ if value is not None:
+ writer.add_key_value(field.name, value, value_type, sub_type=sub_type)
+
+ # Add new metadata
+ for key, (value_type, value) in self.metadata_changes.items():
+ # Skip if the key already existed (we handled it above)
+ if self.reader.get_field(key) is not None:
+ continue
+
+ sub_type = None
+ if value_type == GGUFValueType.ARRAY:
+ # Handle array values
+ sub_type, value = value
+
+ writer.add_key_value(key, value, value_type, sub_type=sub_type)
+
+ # Add tensors (including data)
+ for tensor in self.reader.tensors:
+ writer.add_tensor(tensor.name, tensor.data, raw_shape=tensor.data.shape, raw_dtype=tensor.tensor_type)
+
+ # Write header and metadata
+ writer.open_output_file(Path(file_path))
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+
+ # Write tensor data using the optimized method
+ writer.write_tensors_to_file(progress=False)
+
+ writer.close()
+
+ self.statusBar().showMessage(f"Saved to {file_path}")
+
+ # Ask if user wants to open the new file
+ reply = QMessageBox.question(
+ self, "Open Saved File",
+ "Would you like to open the newly saved file?",
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.Yes
+ )
+
+ if reply == QMessageBox.StandardButton.Yes:
+ self.reader = GGUFReader(file_path, 'r')
+ self.current_file = file_path
+ self.file_path_edit.setText(file_path)
+
+ self.load_metadata()
+ self.load_tensors()
+
+ self.metadata_changes = {}
+ self.metadata_to_remove = set()
+ self.modified = False
+
+ except Exception as e:
+ QMessageBox.critical(self, "Error", f"Failed to save file: {str(e)}")
+ self.statusBar().showMessage("Error saving file")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="GUI GGUF Editor")
+ parser.add_argument("model_path", nargs="?", help="path to GGUF model file to load at startup")
+ parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+
+ args = parser.parse_args()
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+
+ app = QApplication(sys.argv)
+ window = GGUFEditorWindow()
+ window.show()
+
+ # Load model if specified
+ if args.model_path:
+ if os.path.isfile(args.model_path) and args.model_path.endswith('.gguf'):
+ window.load_file(args.model_path)
+ else:
+ logger.error(f"Invalid model path: {args.model_path}")
+ QMessageBox.warning(
+ window,
+ "Invalid Model Path",
+ f"The specified file does not exist or is not a GGUF file: {args.model_path}")
+
+ sys.exit(app.exec())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_hash.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_hash.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ef98992197e987d8aefc8fb5f5bf9c787e9d06a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_hash.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import uuid
+import hashlib
+
+import logging
+import argparse
+import os
+import sys
+from pathlib import Path
+
+from tqdm import tqdm
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from gguf import GGUFReader # noqa: E402
+
+
+logger = logging.getLogger("gguf-hash")
+
+# UUID_NAMESPACE_LLAMA_CPP = uuid.uuid5(uuid.NAMESPACE_URL, 'en.wikipedia.org/wiki/Llama.cpp')
+UUID_NAMESPACE_LLAMA_CPP = uuid.UUID('ef001206-dadc-5f6d-a15f-3359e577d4e5')
+
+
+# For more information about what field.parts and field.data represent,
+# please see the comments in the modify_gguf.py example.
+def gguf_hash(reader: GGUFReader, filename: str, disable_progress_bar: bool, no_layer: bool) -> None:
+ sha1 = hashlib.sha1()
+ sha256 = hashlib.sha256()
+ uuidv5_sha1 = hashlib.sha1()
+ uuidv5_sha1.update(UUID_NAMESPACE_LLAMA_CPP.bytes)
+
+ # Total Weight Calculation For Progress Bar
+ total_weights = 0
+ for n, tensor in enumerate(reader.tensors, 1):
+
+ # We don't need these
+ if tensor.name.endswith((".attention.masked_bias", ".attention.bias", ".rotary_emb.inv_freq")):
+ continue
+
+ # Calculate Tensor Volume
+ sum_weights_in_tensor = 1
+ for dim in tensor.shape:
+ sum_weights_in_tensor *= dim
+ total_weights += sum_weights_in_tensor
+
+ # Hash Progress Bar
+ bar = tqdm(desc="Hashing", total=total_weights, unit="weights", unit_scale=True, disable=disable_progress_bar)
+
+ # Hashing Process
+ for tensor in reader.tensors:
+
+ # We don't need these
+ if tensor.name.endswith((".attention.masked_bias", ".attention.bias", ".rotary_emb.inv_freq")):
+ continue
+
+ # Progressbar
+ sum_weights_in_tensor = 1
+ for dim in tensor.shape:
+ sum_weights_in_tensor *= dim
+ bar.update(sum_weights_in_tensor)
+
+ if not no_layer:
+
+ sha1_layer = hashlib.sha1()
+ sha1_layer.update(tensor.data.data)
+ print("sha1 {0} {1}:{2}".format(sha1_layer.hexdigest(), filename, tensor.name)) # noqa: NP100
+
+ sha256_layer = hashlib.sha256()
+ sha256_layer.update(tensor.data.data)
+ print("sha256 {0} {1}:{2}".format(sha256_layer.hexdigest(), filename, tensor.name)) # noqa: NP100
+
+ sha1.update(tensor.data.data)
+ sha256.update(tensor.data.data)
+ uuidv5_sha1.update(tensor.data.data)
+
+ # Flush Hash Progress Bar
+ bar.close()
+
+ # Display Hash Output
+ print("sha1 {0} {1}".format(sha1.hexdigest(), filename)) # noqa: NP100
+ print("sha256 {0} {1}".format(sha256.hexdigest(), filename)) # noqa: NP100
+ print("uuid {0} {1}".format(uuid.UUID(bytes=uuidv5_sha1.digest()[:16], version=5), filename)) # noqa: NP100
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Dump GGUF file metadata")
+ parser.add_argument("model", type=str, help="GGUF format model filename")
+ parser.add_argument("--no-layer", action="store_true", help="exclude per layer hash")
+ parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+ parser.add_argument("--progressbar", action="store_true", help="enable progressbar")
+ args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+ reader = GGUFReader(args.model, 'r')
+ gguf_hash(reader, args.model, not args.progressbar, args.no_layer)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_new_metadata.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_new_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..63f2300348ed0ffad3bb9a4be6aa7aae6b827350
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_new_metadata.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import logging
+import argparse
+import os
+import sys
+import json
+from pathlib import Path
+
+from tqdm import tqdm
+from typing import Any, Sequence, NamedTuple
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+import gguf
+
+logger = logging.getLogger("gguf-new-metadata")
+
+
+class MetadataDetails(NamedTuple):
+ type: gguf.GGUFValueType
+ value: Any
+ description: str = ''
+ sub_type: gguf.GGUFValueType | None = None
+
+
+def get_field_data(reader: gguf.GGUFReader, key: str) -> Any:
+ field = reader.get_field(key)
+
+ return field.contents() if field else None
+
+
+def find_token(token_list: Sequence[int], token: str) -> Sequence[int]:
+ token_ids = [index for index, value in enumerate(token_list) if value == token]
+
+ if len(token_ids) == 0:
+ raise LookupError(f'Unable to find "{token}" in token list!')
+
+ return token_ids
+
+
+def copy_with_new_metadata(reader: gguf.GGUFReader, writer: gguf.GGUFWriter, new_metadata: dict[str, MetadataDetails], remove_metadata: Sequence[str]) -> None:
+ for field in reader.fields.values():
+ # Suppress virtual fields and fields written by GGUFWriter
+ if field.name == gguf.Keys.General.ARCHITECTURE or field.name.startswith('GGUF.'):
+ logger.debug(f'Suppressing {field.name}')
+ continue
+
+ # Skip old chat templates if we have new ones
+ if field.name.startswith(gguf.Keys.Tokenizer.CHAT_TEMPLATE) and gguf.Keys.Tokenizer.CHAT_TEMPLATE in new_metadata:
+ logger.debug(f'Skipping {field.name}')
+ continue
+
+ if field.name in remove_metadata:
+ logger.debug(f'Removing {field.name}')
+ continue
+
+ val_type = field.types[0]
+ sub_type = field.types[-1] if val_type == gguf.GGUFValueType.ARRAY else None
+ old_val = MetadataDetails(val_type, field.contents(), sub_type=sub_type)
+ val = new_metadata.get(field.name, old_val)
+
+ if field.name in new_metadata:
+ logger.debug(f'Modifying {field.name}: "{old_val.value}" -> "{val.value}" {val.description}')
+ del new_metadata[field.name]
+ elif val.value is not None:
+ logger.debug(f'Copying {field.name}')
+
+ if val.value is not None:
+ writer.add_key_value(field.name, val.value, val.type, sub_type=sub_type if val.sub_type is None else val.sub_type)
+
+ if gguf.Keys.Tokenizer.CHAT_TEMPLATE in new_metadata:
+ logger.debug('Adding chat template(s)')
+ writer.add_chat_template(new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE].value)
+ del new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE]
+
+ for key, val in new_metadata.items():
+ logger.debug(f'Adding {key}: "{val.value}" {val.description}')
+ writer.add_key_value(key, val.value, val.type)
+
+ total_bytes = 0
+
+ for tensor in reader.tensors:
+ total_bytes += tensor.n_bytes
+ writer.add_tensor_info(tensor.name, tensor.data.shape, tensor.data.dtype, tensor.data.nbytes, tensor.tensor_type)
+
+ bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
+
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_ti_data_to_file()
+
+ for tensor in reader.tensors:
+ writer.write_tensor_data(tensor.data)
+ bar.update(tensor.n_bytes)
+
+ writer.close()
+
+
+def main() -> None:
+ tokenizer_metadata = (getattr(gguf.Keys.Tokenizer, n) for n in gguf.Keys.Tokenizer.__dict__.keys() if not n.startswith('_'))
+ token_names = dict((n.split('.')[-1][:-len('_token_id')], n) for n in tokenizer_metadata if n.endswith('_token_id'))
+
+ parser = argparse.ArgumentParser(description="Make a copy of a GGUF file with new metadata")
+ parser.add_argument("input", type=Path, help="GGUF format model input filename")
+ parser.add_argument("output", type=Path, help="GGUF format model output filename")
+ parser.add_argument("--general-name", type=str, help="The models general.name", metavar='"name"')
+ parser.add_argument("--general-description", type=str, help="The models general.description", metavar='"Description ..."')
+ parser.add_argument("--chat-template", type=str, help="Chat template string (or JSON string containing templates)", metavar='"{% ... %} ..."')
+ parser.add_argument("--chat-template-config", type=Path, help="Config file containing chat template(s)", metavar='tokenizer_config.json')
+ parser.add_argument("--pre-tokenizer", type=str, help="The models tokenizer.ggml.pre", metavar='"pre tokenizer"')
+ parser.add_argument("--remove-metadata", action="append", type=str, help="Remove metadata (by key name) from output model", metavar='general.url')
+ parser.add_argument("--special-token", action="append", type=str, help="Special token by value", nargs=2, metavar=(' | '.join(token_names.keys()), '""'))
+ parser.add_argument("--special-token-by-id", action="append", type=str, help="Special token by id", nargs=2, metavar=(' | '.join(token_names.keys()), '0'))
+ parser.add_argument("--force", action="store_true", help="Bypass warnings without confirmation")
+ parser.add_argument("--verbose", action="store_true", help="Increase output verbosity")
+ args = parser.parse_args(None if len(sys.argv) > 2 else ["--help"])
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+
+ new_metadata = {}
+ remove_metadata = args.remove_metadata or []
+
+ if args.general_name:
+ new_metadata[gguf.Keys.General.NAME] = MetadataDetails(gguf.GGUFValueType.STRING, args.general_name)
+
+ if args.general_description:
+ new_metadata[gguf.Keys.General.DESCRIPTION] = MetadataDetails(gguf.GGUFValueType.STRING, args.general_description)
+
+ if args.chat_template:
+ new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE] = MetadataDetails(gguf.GGUFValueType.STRING, json.loads(args.chat_template) if args.chat_template.startswith('[') else args.chat_template)
+
+ if args.chat_template_config:
+ with open(args.chat_template_config, 'r') as fp:
+ config = json.load(fp)
+ template = config.get('chat_template')
+ if template:
+ new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE] = MetadataDetails(gguf.GGUFValueType.STRING, template)
+
+ if args.pre_tokenizer:
+ new_metadata[gguf.Keys.Tokenizer.PRE] = MetadataDetails(gguf.GGUFValueType.STRING, args.pre_tokenizer)
+
+ if remove_metadata:
+ logger.warning('*** Warning *** Warning *** Warning **')
+ logger.warning('* Most metadata is required for a fully functional GGUF file,')
+ logger.warning('* removing crucial metadata may result in a corrupt output file!')
+
+ if not args.force:
+ logger.warning('* Enter exactly YES if you are positive you want to proceed:')
+ response = input('YES, I am sure> ')
+ if response != 'YES':
+ logger.info("You didn't enter YES. Okay then, see ya!")
+ sys.exit(0)
+
+ logger.info(f'* Loading: {args.input}')
+ reader = gguf.GGUFReader(args.input, 'r')
+
+ arch = get_field_data(reader, gguf.Keys.General.ARCHITECTURE)
+
+ token_list = get_field_data(reader, gguf.Keys.Tokenizer.LIST) or []
+
+ for name, token in args.special_token or []:
+ if name not in token_names:
+ logger.warning(f'Unknown special token "{name}", ignoring...')
+ else:
+ ids = find_token(token_list, token)
+ new_metadata[token_names[name]] = MetadataDetails(gguf.GGUFValueType.UINT32, ids[0], f'= {token}')
+
+ if len(ids) > 1:
+ logger.warning(f'Multiple "{token}" tokens found, choosing ID {ids[0]}, use --special-token-by-id if you want another:')
+ logger.warning(', '.join(str(i) for i in ids))
+
+ for name, id_string in args.special_token_by_id or []:
+ if name not in token_names:
+ logger.warning(f'Unknown special token "{name}", ignoring...')
+ elif not id_string.isdecimal():
+ raise LookupError(f'Token ID "{id_string}" is not a valid ID!')
+ else:
+ id_int = int(id_string)
+
+ if id_int >= 0 and id_int < len(token_list):
+ new_metadata[token_names[name]] = MetadataDetails(gguf.GGUFValueType.UINT32, id_int, f'= {token_list[id_int]}')
+ else:
+ raise LookupError(f'Token ID {id_int} is not within token list!')
+
+ if os.path.isfile(args.output) and not args.force:
+ logger.warning('*** Warning *** Warning *** Warning **')
+ logger.warning(f'* The "{args.output}" GGUF file already exists, it will be overwritten!')
+ logger.warning('* Enter exactly YES if you are positive you want to proceed:')
+ response = input('YES, I am sure> ')
+ if response != 'YES':
+ logger.info("You didn't enter YES. Okay then, see ya!")
+ sys.exit(0)
+
+ logger.info(f'* Writing: {args.output}')
+ writer = gguf.GGUFWriter(args.output, arch=arch, endianess=reader.endianess)
+
+ alignment = get_field_data(reader, gguf.Keys.General.ALIGNMENT)
+ if alignment is not None:
+ logger.debug(f'Setting custom alignment: {alignment}')
+ writer.data_alignment = alignment
+
+ copy_with_new_metadata(reader, writer, new_metadata, remove_metadata)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/scripts/gguf_set_metadata.py b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_set_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5809c35c887086f8055e828719041f8ae3ea749
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/scripts/gguf_set_metadata.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+import logging
+import argparse
+import os
+import sys
+from pathlib import Path
+
+# Necessary to load the local gguf package
+if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent.parent / 'gguf-py').exists():
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from gguf import GGUFReader # noqa: E402
+
+logger = logging.getLogger("gguf-set-metadata")
+
+
+def minimal_example(filename: str) -> None:
+ reader = GGUFReader(filename, 'r+')
+ field = reader.fields['tokenizer.ggml.bos_token_id']
+ if field is None:
+ return
+ part_index = field.data[0]
+ field.parts[part_index][0] = 2 # Set tokenizer.ggml.bos_token_id to 2
+ #
+ # So what's this field.data thing? It's helpful because field.parts contains
+ # _every_ part of the GGUF field. For example, tokenizer.ggml.bos_token_id consists
+ # of:
+ #
+ # Part index 0: Key length (27)
+ # Part index 1: Key data ("tokenizer.ggml.bos_token_id")
+ # Part index 2: Field type (4, the id for GGUFValueType.UINT32)
+ # Part index 3: Field value
+ #
+ # Note also that each part is an NDArray slice, so even a part that
+ # is only a single value like the key length will be a NDArray of
+ # the key length type (numpy.uint32).
+ #
+ # The .data attribute in the Field is a list of relevant part indexes
+ # and doesn't contain internal GGUF details like the key length part.
+ # In this case, .data will be [3] - just the part index of the
+ # field value itself.
+
+
+def set_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
+ field = reader.get_field(args.key)
+ if field is None:
+ logger.error(f'! Field {repr(args.key)} not found')
+ sys.exit(1)
+ # Note that field.types is a list of types. This is because the GGUF
+ # format supports arrays. For example, an array of UINT32 would
+ # look like [GGUFValueType.ARRAY, GGUFValueType.UINT32]
+ handler = reader.gguf_scalar_to_np.get(field.types[0]) if field.types else None
+ if handler is None:
+ logger.error(f'! This tool only supports changing simple values, {repr(args.key)} has unsupported type {field.types}')
+ sys.exit(1)
+ current_value = field.parts[field.data[0]][0]
+ new_value = handler(args.value)
+ logger.info(f'* Preparing to change field {repr(args.key)} from {current_value} to {new_value}')
+ if current_value == new_value:
+ logger.info(f'- Key {repr(args.key)} already set to requested value {current_value}')
+ sys.exit(0)
+ if args.dry_run:
+ sys.exit(0)
+ if not args.force:
+ logger.warning('*** Warning *** Warning *** Warning **')
+ logger.warning('* Changing fields in a GGUF file can make it unusable. Proceed at your own risk.')
+ logger.warning('* Enter exactly YES if you are positive you want to proceed:')
+ response = input('YES, I am sure> ')
+ if response != 'YES':
+ logger.info("You didn't enter YES. Okay then, see ya!")
+ sys.exit(0)
+ field.parts[field.data[0]][0] = new_value
+ logger.info('* Field changed. Successful completion.')
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Set a simple value in GGUF file metadata")
+ parser.add_argument("model", type=str, help="GGUF format model filename")
+ parser.add_argument("key", type=str, help="Metadata key to set")
+ parser.add_argument("value", type=str, help="Metadata value to set")
+ parser.add_argument("--dry-run", action="store_true", help="Don't actually change anything")
+ parser.add_argument("--force", action="store_true", help="Change the field without confirmation")
+ parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
+
+ args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
+
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
+
+ logger.info(f'* Loading: {args.model}')
+ reader = GGUFReader(args.model, 'r' if args.dry_run else 'r+')
+ set_metadata(reader, args)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/venv/lib/python3.10/site-packages/gguf/tensor_mapping.py b/venv/lib/python3.10/site-packages/gguf/tensor_mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..79f044d2a5945236b613ac3733ccc2b60ebd9ba4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/tensor_mapping.py
@@ -0,0 +1,1280 @@
+from __future__ import annotations
+
+from typing import Sequence
+
+from .constants import MODEL_ARCH, MODEL_TENSOR, MODEL_TENSORS, TENSOR_NAMES
+
+
+class TensorNameMap:
+ mappings_cfg: dict[MODEL_TENSOR, tuple[str, ...]] = {
+ # Token embeddings
+ MODEL_TENSOR.TOKEN_EMBD: (
+ "gpt_neox.embed_in", # gptneox
+ "transformer.wte", # gpt2 gpt-j mpt refact qwen dbrx jais exaone
+ "transformer.word_embeddings", # falcon
+ "word_embeddings", # bloom
+ "model.embed_tokens", # llama-hf nemotron olmoe olmo2 rwkv6qwen2 glm4-0414
+ "tok_embeddings", # llama-pth
+ "embeddings.word_embeddings", # bert nomic-bert
+ "language_model.embedding.word_embeddings", # persimmon
+ "wte", # gpt2
+ "transformer.embd.wte", # phi2
+ "model.tok_embeddings", # internlm2
+ "model.embedding", # mamba-qbert
+ "backbone.embedding", # mamba
+ "backbone.embeddings", # mamba-hf
+ "transformer.in_out_embed", # Grok
+ "embedding.word_embeddings", # chatglm
+ "transformer.token_embeddings", # openelm
+ "shared", # t5
+ "rwkv.embeddings", # rwkv6
+ "model.embeddings", # rwkv7
+ "model.word_embeddings", # bailingmoe
+ "language_model.model.embed_tokens", # llama4
+ "encoder", # neobert
+ ),
+
+ # Token type embeddings
+ MODEL_TENSOR.TOKEN_TYPES: (
+ "embeddings.token_type_embeddings", # bert nomic-bert
+ ),
+
+ # Normalization of token embeddings
+ MODEL_TENSOR.TOKEN_EMBD_NORM: (
+ "word_embeddings_layernorm", # bloom
+ "embeddings.LayerNorm", # bert
+ "emb_ln", # nomic-bert
+ "transformer.norm", # openelm
+ "rwkv.blocks.0.pre_ln", # rwkv
+ "rwkv.blocks.0.pre_ln", # rwkv6
+ "model.pre_ln", # rwkv7
+ "model.layers.0.pre_norm", # rwkv7
+ "backbone.norm", # wavtokenizer
+ ),
+
+ # Position embeddings
+ MODEL_TENSOR.POS_EMBD: (
+ "transformer.wpe", # gpt2
+ "embeddings.position_embeddings", # bert
+ "wpe", # gpt2
+ ),
+
+ # Output
+ MODEL_TENSOR.OUTPUT: (
+ "embed_out", # gptneox
+ "lm_head", # gpt2 mpt falcon llama-hf baichuan qwen mamba dbrx jais nemotron exaone olmoe olmo2 phimoe
+ "output", # llama-pth bloom internlm2
+ "word_embeddings_for_head", # persimmon
+ "lm_head.linear", # phi2
+ "output_layer", # chatglm
+ "head", # rwkv
+ "head.out", # wavtokenizer
+ "lm_head", # llama4
+ ),
+
+ # Output norm
+ MODEL_TENSOR.OUTPUT_NORM: (
+ "gpt_neox.final_layer_norm", # gptneox
+ "transformer.ln_f", # gpt2 gpt-j falcon jais exaone
+ "model.norm", # llama-hf baichuan internlm2 olmoe olmo2 phimoe
+ "norm", # llama-pth
+ "transformer.norm_f", # mpt dbrx
+ "ln_f", # refact bloom qwen gpt2
+ "language_model.encoder.final_layernorm", # persimmon
+ "model.final_layernorm", # persimmon
+ "lm_head.ln", # phi2
+ "model.norm_f", # mamba-qbert
+ "backbone.norm_f", # mamba
+ "transformer.rms_norm", # Grok
+ "encoder.final_layernorm", # chatglm
+ "transformer.norm", # openelm
+ "model.norm", # nemotron
+ "rwkv.ln_out", # rwkv6
+ "model.ln_out", # rwkv7
+ "backbone.final_layer_norm", # wavtokenizer
+ "model.norm", # llama4
+ ),
+
+ # Rope frequencies
+ MODEL_TENSOR.ROPE_FREQS: (
+ "rope.freqs", # llama-pth
+ "rotary_pos_emb.inv_freq", # chatglm
+ ),
+
+ MODEL_TENSOR.ROPE_FACTORS_LONG: (),
+ MODEL_TENSOR.ROPE_FACTORS_SHORT: (),
+
+ MODEL_TENSOR.CONV1D: (
+ "backbone.embed", # roberta
+ ),
+ }
+
+ block_mappings_cfg: dict[MODEL_TENSOR, tuple[str, ...]] = {
+ # Attention norm
+ MODEL_TENSOR.ATTN_NORM: (
+ "gpt_neox.layers.{bid}.input_layernorm", # gptneox
+ "transformer.h.{bid}.ln_1", # gpt2 gpt-j refact qwen jais exaone
+ "transformer.blocks.{bid}.norm_1", # mpt
+ "transformer.h.{bid}.input_layernorm", # falcon7b
+ "h.{bid}.input_layernorm", # bloom
+ "transformer.h.{bid}.ln_mlp", # falcon40b
+ "model.layers.{bid}.input_layernorm", # llama-hf nemotron olmoe phimoe
+ "layers.{bid}.attention_norm", # llama-pth
+ "language_model.encoder.layers.{bid}.input_layernorm", # persimmon
+ "model.layers.{bid}.ln1", # yi
+ "h.{bid}.ln_1", # gpt2
+ "transformer.h.{bid}.ln", # phi2
+ "model.layers.layers.{bid}.norm", # plamo
+ "model.layers.{bid}.attention_norm", # internlm2
+ "model.layers.{bid}.norm", # mamba-qbert
+ "backbone.layers.{bid}.norm", # mamba
+ "transformer.decoder_layer.{bid}.rms_norm", # Grok
+ "transformer.blocks.{bid}.norm_attn_norm.norm_1", # dbrx
+ "encoder.layers.{bid}.input_layernorm", # chatglm
+ "transformer.layers.{bid}.attn_norm", # openelm
+ "rwkv.blocks.{bid}.ln1", # rwkv6
+ "model.layers.{bid}.ln1", # rwkv7
+ "model.layers.{bid}.input_layernorm", # llama4
+ "transformer_encoder.{bid}.attention_norm", # neobert
+ ),
+
+ # Attention norm 2
+ MODEL_TENSOR.ATTN_NORM_2: (
+ "transformer.h.{bid}.ln_attn", # falcon40b
+ "encoder.layer.{bid}.layer_norm_1", # jina-v2-code
+ "rwkv.blocks.{bid}.ln2", # rwkv6
+ "model.layers.{bid}.ln2", # rwkv7
+ ),
+
+ # Attention query-key-value
+ MODEL_TENSOR.ATTN_QKV: (
+ "gpt_neox.layers.{bid}.attention.query_key_value", # gptneox
+ "transformer.h.{bid}.attn.c_attn", # gpt2 qwen jais
+ "transformer.blocks.{bid}.attn.Wqkv", # mpt
+ "transformer.blocks.{bid}.norm_attn_norm.attn.Wqkv", # dbrx
+ "transformer.h.{bid}.self_attention.query_key_value", # falcon
+ "h.{bid}.self_attention.query_key_value", # bloom
+ "language_model.encoder.layers.{bid}.self_attention.query_key_value", # persimmon
+ "model.layers.{bid}.self_attn.query_key_value", # persimmon
+ "h.{bid}.attn.c_attn", # gpt2
+ "transformer.h.{bid}.mixer.Wqkv", # phi2
+ "encoder.layers.{bid}.attn.Wqkv", # nomic-bert
+ "encoder.layers.{bid}.mixer.Wqkv", # jina
+ "model.layers.{bid}.self_attn.qkv_proj", # phi3
+ "encoder.layers.{bid}.self_attention.query_key_value", # chatglm
+ "transformer.layers.{bid}.attn.qkv_proj", # openelm
+ "transformer_encoder.{bid}.qkv", # neobert
+ ),
+
+ # Attention query
+ MODEL_TENSOR.ATTN_Q: (
+ "model.layers.{bid}.self_attn.q_proj", # llama-hf nemotron olmoe olmo2 phimoe
+ "model.layers.{bid}.self_attn.q_proj_no_perm", # llama-custom
+ "layers.{bid}.attention.wq", # llama-pth
+ "encoder.layer.{bid}.attention.self.query", # bert
+ "transformer.layer.{bid}.attention.q_lin", # distillbert
+ "transformer.h.{bid}.attn.q_proj", # gpt-j
+ "model.layers.layers.{bid}.self_attn.q_proj", # plamo
+ "model.layers.{bid}.attention.wq", # internlm2
+ "transformer.decoder_layer.{bid}.multi_head_attention.query",# Grok
+ "transformer.h.{bid}.attn.attention.q_proj", # exaone
+ "model.layers.{bid}.self_attn.q_proj", # llama4
+ ),
+
+ # Attention key
+ MODEL_TENSOR.ATTN_K: (
+ "model.layers.{bid}.self_attn.k_proj", # llama-hf nemotron olmoe olmo2 phimoe
+ "model.layers.{bid}.self_attn.k_proj_no_perm", # llama-custom
+ "layers.{bid}.attention.wk", # llama-pth
+ "encoder.layer.{bid}.attention.self.key", # bert
+ "transformer.layer.{bid}.attention.k_lin", # distillbert
+ "transformer.h.{bid}.attn.k_proj", # gpt-j
+ "transformer.h.{bid}.attn.k", # refact
+ "model.layers.layers.{bid}.self_attn.k_proj", # plamo
+ "model.layers.{bid}.attention.wk", # internlm2
+ "transformer.decoder_layer.{bid}.multi_head_attention.key",# Grok
+ "transformer.h.{bid}.attn.attention.k_proj", # exaone
+ "model.layers.{bid}.self_attn.k_proj", # llama4
+ ),
+
+ # Attention value
+ MODEL_TENSOR.ATTN_V: (
+ "model.layers.{bid}.self_attn.v_proj", # llama-hf nemotron olmoe olmo2 phimoe
+ "layers.{bid}.attention.wv", # llama-pth
+ "encoder.layer.{bid}.attention.self.value", # bert
+ "transformer.layer.{bid}.attention.v_lin", # distillbert
+ "transformer.h.{bid}.attn.v_proj", # gpt-j
+ "transformer.h.{bid}.attn.v", # refact
+ "model.layers.layers.{bid}.self_attn.v_proj", # plamo
+ "model.layers.{bid}.attention.wv", # internlm2
+ "transformer.decoder_layer.{bid}.multi_head_attention.value",# Grok
+ "transformer.h.{bid}.attn.attention.v_proj", # exaone
+ "model.layers.{bid}.self_attn.v_proj", # llama4
+ ),
+
+ # Attention output
+ MODEL_TENSOR.ATTN_OUT: (
+ "gpt_neox.layers.{bid}.attention.dense", # gptneox
+ "transformer.h.{bid}.attn.c_proj", # gpt2 refact qwen jais
+ "transformer.blocks.{bid}.attn.out_proj", # mpt
+ "transformer.h.{bid}.self_attention.dense", # falcon
+ "h.{bid}.self_attention.dense", # bloom
+ "model.layers.{bid}.self_attn.o_proj", # llama-hf nemotron olmoe olmo2 phimoe
+ "model.layers.{bid}.self_attn.linear_attn", # deci
+ "layers.{bid}.attention.wo", # llama-pth
+ "encoder.layer.{bid}.attention.output.dense", # bert
+ "transformer.layer.{bid}.attention.out_lin", # distillbert
+ "transformer.h.{bid}.attn.out_proj", # gpt-j
+ "language_model.encoder.layers.{bid}.self_attention.dense", # persimmon
+ "model.layers.{bid}.self_attn.dense", # persimmon
+ "h.{bid}.attn.c_proj", # gpt2
+ "transformer.h.{bid}.mixer.out_proj", # phi2
+ "model.layers.layers.{bid}.self_attn.o_proj", # plamo
+ "model.layers.{bid}.attention.wo", # internlm2
+ "encoder.layers.{bid}.attn.out_proj", # nomic-bert
+ "encoder.layers.{bid}.mixer.out_proj", # jina
+ "transformer.decoder_layer.{bid}.multi_head_attention.linear", # Grok
+ "transformer.blocks.{bid}.norm_attn_norm.attn.out_proj", # dbrx
+ "encoder.layers.{bid}.self_attention.dense", # chatglm
+ "transformer.layers.{bid}.attn.out_proj", # openelm
+ "transformer.h.{bid}.attn.attention.out_proj", # exaone
+ "model.layers.{bid}.self_attn.o_proj", # llama4
+ "transformer_encoder.{bid}.wo", # neobert
+ ),
+
+ # Attention output norm
+ MODEL_TENSOR.ATTN_OUT_NORM: (
+ "encoder.layer.{bid}.attention.output.LayerNorm", # bert
+ "transformer.layer.{bid}.sa_layer_norm", # distillbert
+ "encoder.layers.{bid}.norm1", # nomic-bert
+ "transformer.decoder_layer.{bid}.rms_norm_1", # Grok
+ "transformer.blocks.{bid}.norm_attn_norm.norm_2", # dbrx
+ ),
+
+ MODEL_TENSOR.ATTN_POST_NORM: (
+ "model.layers.{bid}.post_attention_layernorm", # gemma2 olmo2 # ge
+ "model.layers.{bid}.post_self_attn_layernorm", # glm-4-0414
+ ),
+
+ # Rotary embeddings
+ MODEL_TENSOR.ATTN_ROT_EMBD: (
+ "model.layers.{bid}.self_attn.rotary_emb.inv_freq", # llama-hf
+ "layers.{bid}.attention.inner_attention.rope.freqs", # llama-pth
+ "model.layers.layers.{bid}.self_attn.rotary_emb.inv_freq", # plamo
+ "transformer.h.{bid}.attn.rotary_emb.inv_freq", # codeshell
+ ),
+
+ # Feed-forward norm
+ MODEL_TENSOR.FFN_NORM: (
+ "gpt_neox.layers.{bid}.post_attention_layernorm", # gptneox
+ "transformer.h.{bid}.ln_2", # gpt2 refact qwen jais exaone
+ "h.{bid}.post_attention_layernorm", # bloom
+ "transformer.blocks.{bid}.norm_2", # mpt
+ "model.layers.{bid}.post_attention_layernorm", # llama-hf nemotron olmoe phimoe
+ "layers.{bid}.ffn_norm", # llama-pth
+ "language_model.encoder.layers.{bid}.post_attention_layernorm", # persimmon
+ "model.layers.{bid}.ln2", # yi
+ "h.{bid}.ln_2", # gpt2
+ "model.layers.{bid}.ffn_norm", # internlm2
+ "transformer.decoder_layer.{bid}.rms_norm_2", # Grok
+ "encoder.layers.{bid}.post_attention_layernorm", # chatglm
+ "transformer.layers.{bid}.ffn_norm", # openelm
+ "model.layers.{bid}.post_attention_layernorm", # llama4
+ "transformer_encoder.{bid}.ffn_norm", # neobert
+ ),
+
+ # Post feed-forward norm
+ MODEL_TENSOR.FFN_PRE_NORM: (
+ "model.layers.{bid}.pre_feedforward_layernorm", # gemma2
+ ),
+
+ # Post feed-forward norm
+ MODEL_TENSOR.FFN_POST_NORM: (
+ "model.layers.{bid}.post_feedforward_layernorm", # gemma2 olmo2
+ "model.layers.{bid}.post_mlp_layernorm", # glm-4-0414
+ ),
+
+ MODEL_TENSOR.FFN_GATE_INP: (
+ "layers.{bid}.feed_forward.gate", # mixtral
+ "model.layers.{bid}.block_sparse_moe.gate", # mixtral phimoe
+ "model.layers.{bid}.mlp.gate", # qwen2moe olmoe
+ "transformer.decoder_layer.{bid}.router", # Grok
+ "transformer.blocks.{bid}.ffn.router.layer", # dbrx
+ "model.layers.{bid}.block_sparse_moe.router.layer", # granitemoe
+ "model.layers.{bid}.feed_forward.router", # llama4
+ "encoder.layers.{bid}.mlp.router.layer", # nomic-bert-moe
+ ),
+
+ MODEL_TENSOR.FFN_GATE_INP_SHEXP: (
+ "model.layers.{bid}.mlp.shared_expert_gate", # qwen2moe
+ ),
+
+ MODEL_TENSOR.FFN_EXP_PROBS_B: (
+ "model.layers.{bid}.mlp.gate.e_score_correction", # deepseek-v3 dots1
+ ),
+
+ # Feed-forward up
+ MODEL_TENSOR.FFN_UP: (
+ "gpt_neox.layers.{bid}.mlp.dense_h_to_4h", # gptneox
+ "transformer.h.{bid}.mlp.c_fc", # gpt2 jais
+ "transformer.blocks.{bid}.ffn.up_proj", # mpt
+ "transformer.h.{bid}.mlp.dense_h_to_4h", # falcon
+ "h.{bid}.mlp.dense_h_to_4h", # bloom
+ "model.layers.{bid}.mlp.up_proj", # llama-hf refact nemotron olmo2
+ "layers.{bid}.feed_forward.w3", # llama-pth
+ "encoder.layer.{bid}.intermediate.dense", # bert
+ "transformer.layer.{bid}.ffn.lin1", # distillbert
+ "transformer.h.{bid}.mlp.fc_in", # gpt-j
+ "transformer.h.{bid}.mlp.linear_3", # refact
+ "language_model.encoder.layers.{bid}.mlp.dense_h_to_4h", # persimmon
+ "model.layers.{bid}.mlp.dense_h_to_4h", # persimmon
+ "transformer.h.{bid}.mlp.w1", # qwen
+ "h.{bid}.mlp.c_fc", # gpt2
+ "transformer.h.{bid}.mlp.fc1", # phi2
+ "model.layers.{bid}.mlp.fc1", # phi2
+ "model.layers.{bid}.mlp.gate_up_proj", # phi3 glm-4-0414
+ "model.layers.layers.{bid}.mlp.up_proj", # plamo
+ "model.layers.{bid}.feed_forward.w3", # internlm2
+ "encoder.layers.{bid}.mlp.fc11", # nomic-bert
+ "encoder.layers.{bid}.mlp.fc1", # nomic-bert-moe
+ "model.layers.{bid}.mlp.c_fc", # starcoder2
+ "encoder.layer.{bid}.mlp.gated_layers_v", # jina-bert-v2 (split up/gate, no longer used)
+ "encoder.layer.{bid}.mlp.gated_layers", # jina-bert-v2 (GEGLU)
+ "encoder.layer.{bid}.mlp.up_gated_layer", # jina-v2-code (GEGLU)
+ "model.layers.{bid}.residual_mlp.w3", # arctic
+ "encoder.layers.{bid}.mlp.dense_h_to_4h", # chatglm
+ "transformer.h.{bid}.mlp.c_fc_1", # exaone
+ "model.layers.{bid}.feed_forward.up_proj", # llama4
+ "transformer_encoder.{bid}.ffn.w12", # neobert
+ ),
+
+ MODEL_TENSOR.FFN_UP_EXP: (
+ "layers.{bid}.feed_forward.experts.w3", # mixtral (merged)
+ "transformer.decoder_layer.{bid}.moe.linear_v", # Grok (merged)
+ "transformer.blocks.{bid}.ffn.experts.mlp.v1", # dbrx
+ "model.layers.{bid}.mlp.experts.up_proj", # qwen2moe olmoe (merged)
+ "model.layers.{bid}.block_sparse_moe.experts.w3", # phimoe (merged)
+ "model.layers.{bid}.feed_forward.experts.up_proj", # llama4
+ "encoder.layers.{bid}.mlp.experts.mlp.w1", # nomic-bert-moe
+ ),
+
+ MODEL_TENSOR.FFN_UP_SHEXP: (
+ "model.layers.{bid}.mlp.shared_expert.up_proj", # qwen2moe
+ "model.layers.{bid}.mlp.shared_experts.up_proj", # deepseek deepseek2
+ "model.layers.{bid}.feed_forward.shared_expert.up_proj", # llama4
+ ),
+
+ # AWQ-activation gate
+ MODEL_TENSOR.FFN_ACT: (
+ "transformer.blocks.{bid}.ffn.act", # mpt
+ ),
+
+ # Feed-forward gate
+ MODEL_TENSOR.FFN_GATE: (
+ "model.layers.{bid}.mlp.gate_proj", # llama-hf refact olmo2
+ "layers.{bid}.feed_forward.w1", # llama-pth
+ "transformer.h.{bid}.mlp.w2", # qwen
+ "transformer.h.{bid}.mlp.c_fc2", # jais
+ "model.layers.layers.{bid}.mlp.gate_proj", # plamo
+ "model.layers.{bid}.feed_forward.w1", # internlm2
+ "encoder.layers.{bid}.mlp.fc12", # nomic-bert
+ "encoder.layer.{bid}.mlp.gated_layers_w", # jina-bert-v2 (split up/gate, no longer used)
+ "transformer.h.{bid}.mlp.linear_1", # refact
+ "model.layers.{bid}.residual_mlp.w1", # arctic
+ "transformer.h.{bid}.mlp.c_fc_0", # exaone
+ "model.layers.{bid}.feed_forward.gate_proj", # llama4
+ ),
+
+ MODEL_TENSOR.FFN_GATE_EXP: (
+ "layers.{bid}.feed_forward.experts.w1", # mixtral (merged)
+ "transformer.decoder_layer.{bid}.moe.linear", # Grok (merged)
+ "transformer.blocks.{bid}.ffn.experts.mlp.w1", # dbrx
+ "model.layers.{bid}.mlp.experts.gate_proj", # qwen2moe olmoe (merged)
+ "model.layers.{bid}.block_sparse_moe.experts.w1", # phimoe (merged)
+ "model.layers.{bid}.feed_forward.experts.gate_proj", # llama4
+ ),
+
+ MODEL_TENSOR.FFN_GATE_SHEXP: (
+ "model.layers.{bid}.mlp.shared_expert.gate_proj", # qwen2moe
+ "model.layers.{bid}.mlp.shared_experts.gate_proj", # deepseek deepseek2
+ "model.layers.{bid}.feed_forward.shared_expert.gate_proj", # llama4
+ ),
+
+ # Feed-forward down
+ MODEL_TENSOR.FFN_DOWN: (
+ "gpt_neox.layers.{bid}.mlp.dense_4h_to_h", # gptneox
+ "transformer.h.{bid}.mlp.c_proj", # gpt2 refact qwen jais
+ "transformer.blocks.{bid}.ffn.down_proj", # mpt
+ "transformer.h.{bid}.mlp.dense_4h_to_h", # falcon
+ "h.{bid}.mlp.dense_4h_to_h", # bloom
+ "model.layers.{bid}.mlp.down_proj", # llama-hf nemotron olmo2
+ "layers.{bid}.feed_forward.w2", # llama-pth
+ "encoder.layer.{bid}.output.dense", # bert
+ "transformer.layer.{bid}.ffn.lin2", # distillbert
+ "transformer.h.{bid}.mlp.fc_out", # gpt-j
+ "language_model.encoder.layers.{bid}.mlp.dense_4h_to_h", # persimmon
+ "model.layers.{bid}.mlp.dense_4h_to_h", # persimmon
+ "h.{bid}.mlp.c_proj", # gpt2
+ "transformer.h.{bid}.mlp.fc2", # phi2
+ "model.layers.{bid}.mlp.fc2", # phi2
+ "model.layers.layers.{bid}.mlp.down_proj", # plamo
+ "model.layers.{bid}.feed_forward.w2", # internlm2
+ "encoder.layers.{bid}.mlp.fc2", # nomic-bert
+ "model.layers.{bid}.mlp.c_proj", # starcoder2
+ "encoder.layer.{bid}.mlp.wo", # jina-bert-v2
+ "transformer.layers.{bid}.ffn.proj_2", # openelm
+ "model.layers.{bid}.residual_mlp.w2", # arctic
+ "encoder.layer.{bid}.mlp.down_layer", # jina-bert-v2
+ "encoder.layers.{bid}.mlp.dense_4h_to_h", # chatglm
+ "model.layers.h.{bid}.mlp.c_proj", # exaone
+ "model.layers.{bid}.feed_forward.down_proj", # llama4
+ "transformer_encoder.{bid}.ffn.w3", # neobert
+ ),
+
+ MODEL_TENSOR.FFN_DOWN_EXP: (
+ "layers.{bid}.feed_forward.experts.w2", # mixtral (merged)
+ "transformer.decoder_layer.{bid}.moe.linear_1", # Grok (merged)
+ "transformer.blocks.{bid}.ffn.experts.mlp.w2", # dbrx
+ "model.layers.{bid}.mlp.experts.down_proj", # qwen2moe olmoe (merged)
+ "model.layers.{bid}.block_sparse_moe.output_linear", # granitemoe
+ "model.layers.{bid}.block_sparse_moe.experts.w2", # phimoe (merged)
+ "model.layers.{bid}.feed_forward.experts.down_proj", # llama4
+ "encoder.layers.{bid}.mlp.experts.mlp.w2", # nomic-bert-moe
+ ),
+
+ MODEL_TENSOR.FFN_DOWN_SHEXP: (
+ "model.layers.{bid}.mlp.shared_expert.down_proj", # qwen2moe
+ "model.layers.{bid}.mlp.shared_experts.down_proj", # deepseek deepseek2
+ "model.layers.{bid}.feed_forward.shared_expert.down_proj", # llama4
+ "model.layers.{bid}.shared_mlp.output_linear", # granitemoe
+ ),
+
+ MODEL_TENSOR.ATTN_Q_NORM: (
+ "language_model.encoder.layers.{bid}.self_attention.q_layernorm",
+ "model.layers.{bid}.self_attn.q_layernorm", # persimmon
+ "model.layers.{bid}.self_attn.q_norm", # cohere olmoe chameleon olmo2
+ "transformer.blocks.{bid}.attn.q_ln", # sea-lion
+ "encoder.layer.{bid}.attention.self.layer_norm_q", # jina-bert-v2
+ "transformer.layers.{bid}.attn.q_norm", # openelm
+ ),
+
+ MODEL_TENSOR.ATTN_K_NORM: (
+ "language_model.encoder.layers.{bid}.self_attention.k_layernorm",
+ "model.layers.{bid}.self_attn.k_layernorm", # persimmon
+ "model.layers.{bid}.self_attn.k_norm", # cohere olmoe chameleon olmo2
+ "transformer.blocks.{bid}.attn.k_ln", # sea-lion
+ "encoder.layer.{bid}.attention.self.layer_norm_k", # jina-bert-v2
+ "transformer.layers.{bid}.attn.k_norm", # openelm
+ ),
+
+ MODEL_TENSOR.ROPE_FREQS: (
+ "language_model.encoder.layers.{bid}.self_attention.rotary_emb.inv_freq", # persimmon
+ ),
+
+ MODEL_TENSOR.LAYER_OUT_NORM: (
+ "encoder.layer.{bid}.output.LayerNorm", # bert
+ "transformer.layer.{bid}.output_layer_norm", # distillbert
+ "encoder.layers.{bid}.norm2", # nomic-bert
+ "transformer.decoder_layer.{bid}.rms_norm_3", # Grok
+ "encoder.layer.{bid}.mlp.layernorm", # jina-bert-v2
+ "encoder.layer.{bid}.layer_norm_2" # jina-v2-code
+ ),
+
+ MODEL_TENSOR.SSM_IN: (
+ "model.layers.{bid}.in_proj",
+ "backbone.layers.{bid}.mixer.in_proj",
+ ),
+
+ MODEL_TENSOR.SSM_CONV1D: (
+ "model.layers.{bid}.conv1d",
+ "backbone.layers.{bid}.mixer.conv1d",
+ ),
+
+ MODEL_TENSOR.SSM_X: (
+ "model.layers.{bid}.x_proj",
+ "backbone.layers.{bid}.mixer.x_proj",
+ ),
+
+ MODEL_TENSOR.SSM_DT: (
+ "model.layers.{bid}.dt_proj",
+ "backbone.layers.{bid}.mixer.dt_proj",
+ ),
+
+ MODEL_TENSOR.SSM_A: (
+ "model.layers.{bid}.A_log",
+ "backbone.layers.{bid}.mixer.A_log",
+ ),
+
+ MODEL_TENSOR.SSM_D: (
+ "model.layers.{bid}.D",
+ "backbone.layers.{bid}.mixer.D",
+ ),
+
+ MODEL_TENSOR.SSM_OUT: (
+ "model.layers.{bid}.out_proj",
+ "backbone.layers.{bid}.mixer.out_proj",
+ ),
+
+ MODEL_TENSOR.TIME_MIX_W0: (
+ "model.layers.{bid}.attention.w0", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_W1: (
+ "rwkv.blocks.{bid}.attention.time_maa_w1", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_w1", # rwkv6qwen2
+ "model.layers.{bid}.attention.w1", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_W2: (
+ "rwkv.blocks.{bid}.attention.time_maa_w2", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_w2", # rwkv6qwen2
+ "model.layers.{bid}.attention.w2", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_A0: (
+ "model.layers.{bid}.attention.a0", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_A1: (
+ "model.layers.{bid}.attention.a1", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_A2: (
+ "model.layers.{bid}.attention.a2", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_V0: (
+ "model.layers.{bid}.attention.v0", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_V1: (
+ "model.layers.{bid}.attention.v1", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_V2: (
+ "model.layers.{bid}.attention.v2", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_G1: (
+ "model.layers.{bid}.attention.g1", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_G2: (
+ "model.layers.{bid}.attention.g2", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_K_K: (
+ "model.layers.{bid}.attention.k_k", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_K_A: (
+ "model.layers.{bid}.attention.k_a", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_R_K: (
+ "model.layers.{bid}.attention.r_k", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_X: (
+ "rwkv.blocks.{bid}.attention.time_maa_x", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_x", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_K: (
+ "rwkv.blocks.{bid}.attention.time_maa_k", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_k", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_V: (
+ "rwkv.blocks.{bid}.attention.time_maa_v", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_v", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_R: (
+ "rwkv.blocks.{bid}.attention.time_maa_r", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_r", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_G: (
+ "rwkv.blocks.{bid}.attention.time_maa_g", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_g", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LERP_W: (
+ "rwkv.blocks.{bid}.attention.time_maa_w", # rwkv6
+ "model.layers.{bid}.self_attn.time_maa_w", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_FIRST: (
+ "rwkv.blocks.{bid}.attention.time_faaaa", # rwkv6
+ ),
+
+ MODEL_TENSOR.TIME_MIX_DECAY: (
+ "rwkv.blocks.{bid}.attention.time_decay", # rwkv6
+ "model.layers.{bid}.self_attn.time_decay", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_DECAY_W1: (
+ "rwkv.blocks.{bid}.attention.time_decay_w1", # rwkv6
+ "model.layers.{bid}.self_attn.time_decay_w1", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_DECAY_W2: (
+ "rwkv.blocks.{bid}.attention.time_decay_w2", # rwkv6
+ "model.layers.{bid}.self_attn.time_decay_w2", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_KEY: (
+ "rwkv.blocks.{bid}.attention.key", # rwkv6
+ "model.layers.{bid}.self_attn.k_proj", # rwkv6qwen2
+ "model.layers.{bid}.attention.key", # rwkv7
+ "model.layers.{bid}.attention.k_proj", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_VALUE: (
+ "rwkv.blocks.{bid}.attention.value", # rwkv6
+ "model.layers.{bid}.self_attn.v_proj", # rwkv6qwen2
+ "model.layers.{bid}.attention.value", # rwkv7
+ "model.layers.{bid}.attention.v_proj", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_RECEPTANCE: (
+ "rwkv.blocks.{bid}.attention.receptance", # rwkv6
+ "model.layers.{bid}.self_attn.q_proj", # rwkv6qwen2
+ "model.layers.{bid}.attention.receptance", # rwkv7
+ "model.layers.{bid}.attention.r_proj", # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_GATE: (
+ "rwkv.blocks.{bid}.attention.gate", # rwkv6
+ "model.layers.{bid}.self_attn.gate", # rwkv6qwen2
+ ),
+
+ MODEL_TENSOR.TIME_MIX_LN: (
+ "rwkv.blocks.{bid}.attention.ln_x", # rwkv6
+ "model.layers.{bid}.attention.ln_x" # rwkv7
+ ),
+
+ MODEL_TENSOR.TIME_MIX_OUTPUT: (
+ "rwkv.blocks.{bid}.attention.output", # rwkv6
+ "model.layers.{bid}.self_attn.o_proj", # rwkv6qwen2
+ "model.layers.{bid}.attention.output", # rwkv7
+ "model.layers.{bid}.attention.o_proj", # rwkv7
+ ),
+
+ MODEL_TENSOR.CHANNEL_MIX_LERP_K: (
+ "rwkv.blocks.{bid}.feed_forward.time_maa_k", # rwkv6
+ "model.layers.{bid}.feed_forward.x_k", # rwkv7
+ ),
+
+ MODEL_TENSOR.CHANNEL_MIX_LERP_R: (
+ "rwkv.blocks.{bid}.feed_forward.time_maa_r", # rwkv6
+ ),
+
+ MODEL_TENSOR.CHANNEL_MIX_KEY: (
+ "rwkv.blocks.{bid}.feed_forward.key", # rwkv6
+ "model.layers.{bid}.feed_forward.key", # rwkv7
+ ),
+
+ MODEL_TENSOR.CHANNEL_MIX_RECEPTANCE: (
+ "rwkv.blocks.{bid}.feed_forward.receptance", # rwkv6
+ ),
+
+ MODEL_TENSOR.CHANNEL_MIX_VALUE: (
+ "rwkv.blocks.{bid}.feed_forward.value", # rwkv6
+ "model.layers.{bid}.feed_forward.value", # rwkv7
+ ),
+
+ MODEL_TENSOR.ATTN_Q_A: (
+ "model.layers.{bid}.self_attn.q_a_proj", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_Q_B: (
+ "model.layers.{bid}.self_attn.q_b_proj", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_KV_A_MQA: (
+ "model.layers.{bid}.self_attn.kv_a_proj_with_mqa", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_KV_B: (
+ "model.layers.{bid}.self_attn.kv_b_proj", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_K_B: (
+ "model.layers.{bid}.self_attn.k_b_proj", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_V_B: (
+ "model.layers.{bid}.self_attn.v_b_proj", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_Q_A_NORM: (
+ "model.layers.{bid}.self_attn.q_a_layernorm", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_KV_A_NORM: (
+ "model.layers.{bid}.self_attn.kv_a_layernorm", # deepseek2
+ ),
+
+ MODEL_TENSOR.ATTN_SUB_NORM: (
+ "model.layers.{bid}.self_attn.inner_attn_ln", # bitnet
+ ),
+
+ MODEL_TENSOR.FFN_SUB_NORM: (
+ "model.layers.{bid}.mlp.ffn_layernorm", # bitnet
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_NORM: (
+ "decoder.block.{bid}.layer.0.layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_Q: (
+ "decoder.block.{bid}.layer.0.SelfAttention.q", # t5
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_K: (
+ "decoder.block.{bid}.layer.0.SelfAttention.k", # t5
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_V: (
+ "decoder.block.{bid}.layer.0.SelfAttention.v", # t5
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_OUT: (
+ "decoder.block.{bid}.layer.0.SelfAttention.o", # t5
+ ),
+
+ MODEL_TENSOR.DEC_ATTN_REL_B: (
+ "decoder.block.{bid}.layer.0.SelfAttention.relative_attention_bias", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_NORM: (
+ "decoder.block.{bid}.layer.1.layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_Q: (
+ "decoder.block.{bid}.layer.1.EncDecAttention.q", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_K: (
+ "decoder.block.{bid}.layer.1.EncDecAttention.k", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_V: (
+ "decoder.block.{bid}.layer.1.EncDecAttention.v", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_OUT: (
+ "decoder.block.{bid}.layer.1.EncDecAttention.o", # t5
+ ),
+
+ MODEL_TENSOR.DEC_CROSS_ATTN_REL_B: (
+ "decoder.block.{bid}.layer.1.EncDecAttention.relative_attention_bias", # t5
+ ),
+
+ MODEL_TENSOR.DEC_FFN_NORM: (
+ "decoder.block.{bid}.layer.2.layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.DEC_FFN_GATE: (
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi_0", # flan-t5
+ ),
+
+ MODEL_TENSOR.DEC_FFN_UP: (
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi", # t5
+ "decoder.block.{bid}.layer.2.DenseReluDense.wi_1", # flan-t5
+ ),
+
+ MODEL_TENSOR.DEC_FFN_DOWN: (
+ "decoder.block.{bid}.layer.2.DenseReluDense.wo", # t5
+ ),
+
+ MODEL_TENSOR.DEC_OUTPUT_NORM: (
+ "decoder.final_layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_NORM: (
+ "encoder.block.{bid}.layer.0.layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_Q: (
+ "encoder.block.{bid}.layer.0.SelfAttention.q", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_K: (
+ "encoder.block.{bid}.layer.0.SelfAttention.k", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_V: (
+ "encoder.block.{bid}.layer.0.SelfAttention.v", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_OUT: (
+ "encoder.block.{bid}.layer.0.SelfAttention.o", # t5
+ ),
+
+ MODEL_TENSOR.ENC_ATTN_REL_B: (
+ "encoder.block.{bid}.layer.0.SelfAttention.relative_attention_bias", # t5
+ ),
+
+ MODEL_TENSOR.ENC_FFN_NORM: (
+ "encoder.block.{bid}.layer.1.layer_norm", # t5
+ ),
+
+ MODEL_TENSOR.ENC_FFN_GATE: (
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi_0", # flan-t5
+ ),
+
+ MODEL_TENSOR.ENC_FFN_UP: (
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi", # t5
+ "encoder.block.{bid}.layer.1.DenseReluDense.wi_1", # flan-t5
+ ),
+
+ MODEL_TENSOR.ENC_FFN_DOWN: (
+ "encoder.block.{bid}.layer.1.DenseReluDense.wo", # t5
+ ),
+
+ ############################################################################
+ # TODO: these do not belong to block_mappings_cfg - move them to mappings_cfg
+ MODEL_TENSOR.ENC_OUTPUT_NORM: (
+ "encoder.final_layer_norm", # t5
+ "layer_norm", # neobert
+ ),
+
+ MODEL_TENSOR.CLS: (
+ "classifier", # jina
+ "classifier.dense", # roberta
+ "pre_classifier", # distillbert
+ "dense", # neobert
+ ),
+
+ MODEL_TENSOR.CLS_OUT: (
+ "classifier.out_proj", # roberta
+ ),
+ #############################################################################
+
+ MODEL_TENSOR.CONVNEXT_DW: (
+ "backbone.convnext.{bid}.dwconv", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.CONVNEXT_NORM: (
+ "backbone.convnext.{bid}.norm", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.CONVNEXT_PW1: (
+ "backbone.convnext.{bid}.pwconv1", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.CONVNEXT_PW2: (
+ "backbone.convnext.{bid}.pwconv2", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.CONVNEXT_GAMMA: (
+ "backbone.convnext.{bid}.gamma", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_CONV1: (
+ "backbone.posnet.{bid}.conv1", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_CONV2: (
+ "backbone.posnet.{bid}.conv2", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_NORM: (
+ "backbone.posnet.{bid}.norm", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_NORM1: (
+ "backbone.posnet.{bid}.norm1", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_NORM2: (
+ "backbone.posnet.{bid}.norm2", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_ATTN_NORM: (
+ "backbone.posnet.{bid}.norm", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_ATTN_Q: (
+ "backbone.posnet.{bid}.q", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_ATTN_K: (
+ "backbone.posnet.{bid}.k", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_ATTN_V: (
+ "backbone.posnet.{bid}.v", # wavtokenizer
+ ),
+
+ MODEL_TENSOR.POSNET_ATTN_OUT: (
+ "backbone.posnet.{bid}.proj_out", # wavtokenizer
+ ),
+
+ #############################################################################
+ ## Vision encoder
+
+ MODEL_TENSOR.V_MMPROJ: (
+ "multi_modal_projector.linear_{bid}",
+ "visual.merger.mlp.{bid}", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_MMPROJ_FC: (
+ "model.connector.modality_projection.proj", # SmolVLM
+ ),
+
+ MODEL_TENSOR.V_MMPROJ_MLP: (
+ "model.mm_projector.mlp.mlp.{bid}",
+ "vision_model.vision_adapter.mlp.fc{bid}", # llama 4
+ "mlp1.{bid}", # InternVL
+ ),
+
+ MODEL_TENSOR.V_MMPROJ_PEG: (
+ "model.mm_projector.peg.peg.{bid}",
+ ),
+
+ MODEL_TENSOR.V_ENC_EMBD_CLS: (
+ "vision_tower.vision_model.embeddings.class_embedding",
+ "vision_model.class_embedding", # llama 4
+ ),
+
+ MODEL_TENSOR.V_ENC_EMBD_PATCH: (
+ "vision_tower.vision_model.embeddings.patch_embedding",
+ "vpm.embeddings.patch_embedding",
+ "model.vision_model.embeddings.patch_embedding", # SmolVLM
+ "vision_tower.patch_conv", # pixtral
+ "vision_model.patch_embedding.linear", # llama 4
+ "visual.patch_embed.proj", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_ENC_EMBD_POS: (
+ "vision_tower.vision_model.embeddings.position_embedding",
+ "vpm.embeddings.position_embedding",
+ "model.vision_model.embeddings.position_embedding", # SmolVLM
+ "vision_model.positional_embedding_vlm", # llama 4
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_Q: (
+ "vision_tower.vision_model.encoder.layers.{bid}.self_attn.q_proj",
+ "vpm.encoder.layers.{bid}.self_attn.q_proj",
+ "model.vision_model.encoder.layers.{bid}.self_attn.q_proj", # SmolVLM
+ "vision_model.model.layers.{bid}.self_attn.q_proj", # llama4
+ "vision_tower.transformer.layers.{bid}.attention.q_proj", # pixtral
+ "visual.blocks.{bid}.attn.q", # qwen2vl, generated
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_Q_NORM: (
+ "vision_tower.vision_model.encoder.layers.{bid}.attn.q_norm", # InternVL
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_K: (
+ "vision_tower.vision_model.encoder.layers.{bid}.self_attn.k_proj",
+ "vpm.encoder.layers.{bid}.self_attn.k_proj",
+ "model.vision_model.encoder.layers.{bid}.self_attn.k_proj", # SmolVLM
+ "vision_model.model.layers.{bid}.self_attn.k_proj", # llama4
+ "vision_tower.transformer.layers.{bid}.attention.k_proj", # pixtral
+ "visual.blocks.{bid}.attn.k", # qwen2vl, generated
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_K_NORM: (
+ "vision_tower.vision_model.encoder.layers.{bid}.attn.k_norm", # InternVL
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_V: (
+ "vision_tower.vision_model.encoder.layers.{bid}.self_attn.v_proj",
+ "vpm.encoder.layers.{bid}.self_attn.v_proj",
+ "model.vision_model.encoder.layers.{bid}.self_attn.v_proj", # SmolVLM
+ "vision_model.model.layers.{bid}.self_attn.v_proj", # llama4
+ "vision_tower.transformer.layers.{bid}.attention.v_proj", # pixtral
+ "visual.blocks.{bid}.attn.v", # qwen2vl, generated
+ ),
+
+ MODEL_TENSOR.V_ENC_INPUT_NORM: (
+ "vision_tower.vision_model.encoder.layers.{bid}.layer_norm1",
+ "vision_tower.vision_model.encoder.layers.{bid}.norm1", # InternVL
+ "vpm.encoder.layers.{bid}.layer_norm1",
+ "model.vision_model.encoder.layers.{bid}.layer_norm1", # SmolVLM
+ "vision_tower.transformer.layers.{bid}.attention_norm", # pixtral
+ "vision_model.model.layers.{bid}.input_layernorm", # llama4
+ "visual.blocks.{bid}.norm1", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_ENC_ATTN_O: (
+ "vision_tower.vision_model.encoder.layers.{bid}.self_attn.out_proj",
+ "vision_tower.vision_model.encoder.layers.{bid}.attn.proj", # InternVL
+ "vpm.encoder.layers.{bid}.self_attn.out_proj",
+ "model.vision_model.encoder.layers.{bid}.self_attn.out_proj", # SmolVLM
+ "vision_model.model.layers.{bid}.self_attn.o_proj", # llama4
+ "vision_tower.transformer.layers.{bid}.attention.o_proj", # pixtral
+ "visual.blocks.{bid}.attn.proj", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_ENC_POST_ATTN_NORM: (
+ "vision_tower.vision_model.encoder.layers.{bid}.layer_norm2",
+ "vision_tower.vision_model.encoder.layers.{bid}.norm2", # InternVL
+ "vpm.encoder.layers.{bid}.layer_norm2",
+ "model.vision_model.encoder.layers.{bid}.layer_norm2", # SmolVLM
+ "vision_model.model.layers.{bid}.post_attention_layernorm", # llama4
+ "vision_tower.transformer.layers.{bid}.ffn_norm", # pixtral
+ "visual.blocks.{bid}.norm2", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_ENC_FFN_UP: (
+ "vision_tower.vision_model.encoder.layers.{bid}.mlp.fc1",
+ "vpm.encoder.layers.{bid}.mlp.fc1",
+ "model.vision_model.encoder.layers.{bid}.mlp.fc1", # SmolVLM, gemma3
+ "vision_tower.transformer.layers.{bid}.feed_forward.up_proj", # pixtral
+ "vision_model.model.layers.{bid}.mlp.fc1", # llama4
+ "visual.blocks.{bid}.mlp.fc1", # qwen2vl
+ "visual.blocks.{bid}.mlp.up_proj", # qwen2.5vl
+ ),
+
+ MODEL_TENSOR.V_ENC_FFN_GATE: (
+ "vision_tower.transformer.layers.{bid}.feed_forward.gate_proj", # pixtral
+ "visual.blocks.{bid}.mlp.gate_proj", # qwen2.5vl
+ ),
+
+ MODEL_TENSOR.V_ENC_FFN_DOWN: (
+ "vision_tower.vision_model.encoder.layers.{bid}.mlp.fc2",
+ "vpm.encoder.layers.{bid}.mlp.fc2",
+ "model.vision_model.encoder.layers.{bid}.mlp.fc2", # SmolVLM, gemma3
+ "vision_tower.transformer.layers.{bid}.feed_forward.down_proj", # pixtral
+ "vision_model.model.layers.{bid}.mlp.fc2", # llama4
+ "visual.blocks.{bid}.mlp.fc2", # qwen2vl
+ "visual.blocks.{bid}.mlp.down_proj", # qwen2.5vl
+ ),
+
+ MODEL_TENSOR.V_LAYER_SCALE_1: (
+ "vision_tower.vision_model.encoder.layers.{bid}.ls1", # InternVL
+ ),
+
+ MODEL_TENSOR.V_LAYER_SCALE_2: (
+ "vision_tower.vision_model.encoder.layers.{bid}.ls2", # InternVL
+ ),
+
+ MODEL_TENSOR.V_PRE_NORM: (
+ "vision_tower.vision_model.pre_layrnorm",
+ "vision_tower.ln_pre", # pixtral
+ "vision_model.layernorm_pre", # llama4
+ ),
+
+ MODEL_TENSOR.V_POST_NORM: (
+ "vision_tower.vision_model.post_layernorm",
+ "model.vision_model.post_layernorm", # SmolVLM
+ "vision_model.layernorm_post", # llama4
+ "visual.merger.ln_q", # qwen2vl
+ ),
+
+ MODEL_TENSOR.V_MM_INP_PROJ: (
+ "multi_modal_projector.mm_input_projection",
+ ),
+
+ MODEL_TENSOR.V_MM_INP_NORM: (
+ "multi_modal_projector.norm",
+ ),
+
+ MODEL_TENSOR.V_MM_SOFT_EMB_NORM: (
+ "multi_modal_projector.mm_soft_emb_norm",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_POS_EMBD_K: (
+ "resampler.pos_embed_k",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_ATTN_Q: (
+ "resampler.attn.in_proj_q", # tensor generated from resampler.attn.in_proj
+ ),
+
+ MODEL_TENSOR.V_RESMPL_ATTN_K: (
+ "resampler.attn.in_proj_k", # tensor generated from resampler.attn.in_proj
+ ),
+
+ MODEL_TENSOR.V_RESMPL_ATTN_V: (
+ "resampler.attn.in_proj_v", # tensor generated from resampler.attn.in_proj
+ ),
+
+ MODEL_TENSOR.V_RESMPL_ATTN_OUT: (
+ "resampler.attn.out_proj",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_KV: (
+ "resampler.kv_proj",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_POST_NORM: (
+ "resampler.ln_post",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_KV_NORM: (
+ "resampler.ln_kv",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_Q_NORM: (
+ "resampler.ln_q",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_PROJ: (
+ "resampler.proj",
+ ),
+
+ MODEL_TENSOR.V_RESMPL_QUERY: (
+ "resampler.query",
+ ),
+
+ MODEL_TENSOR.V_TOK_EMBD_IMG_BREAK: (
+ "v.token_embd.img_break", # for pixtral, this is a generated vector
+ ),
+
+ MODEL_TENSOR.V_MM_PATCH_MERGER: (
+ "multi_modal_projector.patch_merger.merging_layer", # mistral small 3.1
+ ),
+
+ # audio (mtmd)
+
+ MODEL_TENSOR.A_ENC_EMBD_POS: (
+ "audio_tower.embed_positions", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_CONV1D: (
+ "audio_tower.conv{bid}", # ultravox
+ ),
+
+ MODEL_TENSOR.A_PRE_NORM: (),
+
+ MODEL_TENSOR.A_POST_NORM: (
+ "audio_tower.layer_norm", # ultravox
+ "audio_tower.ln_post", # qwen2omni
+ ),
+
+ MODEL_TENSOR.A_ENC_ATTN_Q: (
+ "audio_tower.layers.{bid}.self_attn.q_proj", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_ATTN_K: (
+ "audio_tower.layers.{bid}.self_attn.k_proj", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_ATTN_V: (
+ "audio_tower.layers.{bid}.self_attn.v_proj", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_INPUT_NORM: (
+ "audio_tower.layers.{bid}.self_attn_layer_norm", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_OUTPUT: (
+ "audio_tower.layers.{bid}.self_attn.out_proj", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_OUTPUT_NORM: (
+ "audio_tower.layers.{bid}.final_layer_norm", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_FFN_UP: (
+ "audio_tower.layers.{bid}.fc1", # ultravox
+ ),
+
+ MODEL_TENSOR.A_ENC_FFN_GATE: (),
+
+ MODEL_TENSOR.A_ENC_FFN_DOWN: (
+ "audio_tower.layers.{bid}.fc2", # ultravox
+ ),
+
+ # note: some tensors below has "audio." pseudo-prefix, to prevent conflicts with vision tensors
+ # this prefix is added in the conversion code in modify_tensors()
+
+ MODEL_TENSOR.A_MMPROJ: (
+ "audio.multi_modal_projector.linear_{bid}", # ultravox
+ ),
+
+ MODEL_TENSOR.A_MMPROJ_FC: (
+ "audio.multi_modal_projector.linear", # qwen2audio
+ "audio_tower.proj", # qwen2omni
+ ),
+
+ MODEL_TENSOR.A_MM_NORM_PRE: (
+ "audio.multi_modal_projector.ln_pre", # ultravox
+ ),
+
+ MODEL_TENSOR.A_MM_NORM_MID: (
+ "audio.multi_modal_projector.ln_mid", # ultravox
+ ),
+ }
+
+ # architecture-specific block mappings
+ arch_block_mappings_cfg: dict[MODEL_ARCH, dict[MODEL_TENSOR, tuple[str, ...]]] = {
+ MODEL_ARCH.ARCTIC: {
+ MODEL_TENSOR.FFN_NORM: (
+ "model.layers.{bid}.residual_layernorm",
+ ),
+ MODEL_TENSOR.FFN_NORM_EXP: (
+ "model.layers.{bid}.post_attention_layernorm",
+ ),
+ },
+ }
+
+ mapping: dict[str, tuple[MODEL_TENSOR, str]]
+
+ def __init__(self, arch: MODEL_ARCH, n_blocks: int):
+ self.mapping = {}
+ for tensor, keys in self.mappings_cfg.items():
+ if tensor not in MODEL_TENSORS[arch]:
+ continue
+ tensor_name = TENSOR_NAMES[tensor]
+ self.mapping[tensor_name] = (tensor, tensor_name)
+ for key in keys:
+ self.mapping[key] = (tensor, tensor_name)
+ if arch in self.arch_block_mappings_cfg:
+ self.block_mappings_cfg.update(self.arch_block_mappings_cfg[arch])
+ for bid in range(n_blocks):
+ for tensor, keys in self.block_mappings_cfg.items():
+ if tensor not in MODEL_TENSORS[arch]:
+ continue
+
+ tensor_name = TENSOR_NAMES[tensor].format(bid = bid)
+ self.mapping[tensor_name] = (tensor, tensor_name)
+ for key in keys:
+ key = key.format(bid = bid)
+ self.mapping[key] = (tensor, tensor_name)
+
+ def get_type_and_name(self, key: str, try_suffixes: Sequence[str] = ()) -> tuple[MODEL_TENSOR, str] | None:
+ result = self.mapping.get(key)
+ if result is not None:
+ return result
+ for suffix in try_suffixes:
+ if key.endswith(suffix):
+ result = self.mapping.get(key[:-len(suffix)])
+ if result is not None:
+ return result[0], result[1] + suffix
+ return None
+
+ def get_name(self, key: str, try_suffixes: Sequence[str] = ()) -> str | None:
+ result = self.get_type_and_name(key, try_suffixes = try_suffixes)
+ if result is None:
+ return None
+ return result[1]
+
+ def get_type(self, key: str, try_suffixes: Sequence[str] = ()) -> MODEL_TENSOR | None:
+ result = self.get_type_and_name(key, try_suffixes = try_suffixes)
+ if result is None:
+ return None
+ return result[0]
+
+ def __getitem__(self, key: str) -> str:
+ try:
+ return self.mapping[key][1]
+ except KeyError:
+ raise KeyError(key)
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.mapping
+
+ def __repr__(self) -> str:
+ return repr(self.mapping)
+
+
+def get_tensor_name_map(arch: MODEL_ARCH, n_blocks: int) -> TensorNameMap:
+ return TensorNameMap(arch, n_blocks)
diff --git a/venv/lib/python3.10/site-packages/gguf/utility.py b/venv/lib/python3.10/site-packages/gguf/utility.py
new file mode 100644
index 0000000000000000000000000000000000000000..00adcbc937398d1e7a9d4b7159a54052bb79ae64
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/utility.py
@@ -0,0 +1,264 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+
+import os
+import json
+
+
+def fill_templated_filename(filename: str, output_type: str | None) -> str:
+ # Given a file name fill in any type templates e.g. 'some-model-name.{ftype}.gguf'
+ ftype_lowercase: str = output_type.lower() if output_type is not None else ""
+ ftype_uppercase: str = output_type.upper() if output_type is not None else ""
+ return filename.format(ftype_lowercase,
+ outtype=ftype_lowercase, ftype=ftype_lowercase,
+ OUTTYPE=ftype_uppercase, FTYPE=ftype_uppercase)
+
+
+def model_weight_count_rounded_notation(model_params_count: int, min_digits: int = 2) -> str:
+ if model_params_count > 1e12 :
+ # Trillions Of Parameters
+ scaled_model_params = model_params_count * 1e-12
+ scale_suffix = "T"
+ elif model_params_count > 1e9 :
+ # Billions Of Parameters
+ scaled_model_params = model_params_count * 1e-9
+ scale_suffix = "B"
+ elif model_params_count > 1e6 :
+ # Millions Of Parameters
+ scaled_model_params = model_params_count * 1e-6
+ scale_suffix = "M"
+ else:
+ # Thousands Of Parameters
+ scaled_model_params = model_params_count * 1e-3
+ scale_suffix = "K"
+
+ fix = max(min_digits - len(str(round(scaled_model_params)).lstrip('0')), 0)
+
+ return f"{scaled_model_params:.{fix}f}{scale_suffix}"
+
+
+def size_label(total_params: int, shared_params: int, expert_params: int, expert_count: int) -> str:
+
+ if expert_count > 0:
+ pretty_size = model_weight_count_rounded_notation(abs(shared_params) + abs(expert_params), min_digits=2)
+ size_class = f"{expert_count}x{pretty_size}"
+ else:
+ size_class = model_weight_count_rounded_notation(abs(total_params), min_digits=2)
+
+ return size_class
+
+
+def naming_convention(model_name: str | None, base_name: str | None, finetune_string: str | None, version_string: str | None, size_label: str | None, output_type: str | None, model_type: Literal['vocab', 'LoRA'] | None = None) -> str:
+ # Reference: https://github.com/ggml-org/ggml/blob/master/docs/gguf.md#gguf-naming-convention
+
+ if base_name is not None:
+ name = base_name.strip().replace(' ', '-').replace('/', '-')
+ elif model_name is not None:
+ name = model_name.strip().replace(' ', '-').replace('/', '-')
+ else:
+ name = "ggml-model"
+
+ parameters = f"-{size_label}" if size_label is not None else ""
+
+ finetune = f"-{finetune_string.strip().replace(' ', '-')}" if finetune_string is not None else ""
+
+ version = f"-{version_string.strip().replace(' ', '-')}" if version_string is not None else ""
+
+ encoding = f"-{output_type.strip().replace(' ', '-').upper()}" if output_type is not None else ""
+
+ kind = f"-{model_type.strip().replace(' ', '-')}" if model_type is not None else ""
+
+ return f"{name}{parameters}{finetune}{version}{encoding}{kind}"
+
+
+@dataclass
+class RemoteTensor:
+ dtype: str
+ shape: tuple[int, ...]
+ offset_start: int
+ size: int
+ url: str
+
+ def data(self) -> bytearray:
+ # TODO: handle request errors (maybe with limited retries?)
+ # NOTE: using a bytearray, otherwise PyTorch complains the buffer is not writeable
+ data = bytearray(SafetensorRemote.get_data_by_range(url=self.url, start=self.offset_start, size=self.size))
+ return data
+
+
+class SafetensorRemote:
+ """
+ Uility class to handle remote safetensor files.
+ This class is designed to work with Hugging Face model repositories.
+
+ Example (one model has single safetensor file, the other has multiple):
+ for model_id in ["ngxson/TEST-Tiny-Llama4", "Qwen/Qwen2.5-7B-Instruct"]:
+ tensors = SafetensorRemote.get_list_tensors_hf_model(model_id)
+ print(tensors)
+
+ Example reading tensor data:
+ tensors = SafetensorRemote.get_list_tensors_hf_model(model_id)
+ for name, meta in tensors.items():
+ dtype, shape, offset_start, size, remote_safetensor_url = meta
+ # read the tensor data
+ data = SafetensorRemote.get_data_by_range(remote_safetensor_url, offset_start, size)
+ print(data)
+ """
+
+ BASE_DOMAIN = "https://huggingface.co"
+ ALIGNMENT = 8 # bytes
+
+ @classmethod
+ def get_list_tensors_hf_model(cls, model_id: str) -> dict[str, RemoteTensor]:
+ """
+ Get list of tensors from a Hugging Face model repository.
+
+ Returns a dictionary of tensor names and their metadata.
+ Each tensor is represented as a tuple of (dtype, shape, offset_start, size, remote_safetensor_url)
+ """
+ # case 1: model has only one single model.safetensor file
+ is_single_file = cls.check_file_exist(f"{cls.BASE_DOMAIN}/{model_id}/resolve/main/model.safetensors")
+ if is_single_file:
+ url = f"{cls.BASE_DOMAIN}/{model_id}/resolve/main/model.safetensors"
+ return cls.get_list_tensors(url)
+
+ # case 2: model has multiple files
+ index_url = f"{cls.BASE_DOMAIN}/{model_id}/resolve/main/model.safetensors.index.json"
+ is_multiple_files = cls.check_file_exist(index_url)
+ if is_multiple_files:
+ # read the index file
+ index_data = cls.get_data_by_range(index_url, 0)
+ index_str = index_data.decode('utf-8')
+ index_json = json.loads(index_str)
+ assert index_json.get("weight_map") is not None, "weight_map not found in index file"
+ weight_map = index_json["weight_map"]
+ # get the list of files
+ all_files = list(set(weight_map.values()))
+ all_files.sort() # make sure we load shard files in order
+ # get the list of tensors
+ tensors: dict[str, RemoteTensor] = {}
+ for file in all_files:
+ url = f"{cls.BASE_DOMAIN}/{model_id}/resolve/main/{file}"
+ for key, val in cls.get_list_tensors(url).items():
+ tensors[key] = val
+ return tensors
+
+ raise ValueError(f"Model {model_id} does not have any safetensor files")
+
+ @classmethod
+ def get_list_tensors(cls, url: str) -> dict[str, RemoteTensor]:
+ """
+ Get list of tensors from a remote safetensor file.
+
+ Returns a dictionary of tensor names and their metadata.
+ Each tensor is represented as a tuple of (dtype, shape, offset_start, size)
+ """
+ metadata, data_start_offset = cls.get_metadata(url)
+ res: dict[str, RemoteTensor] = {}
+
+ for name, meta in metadata.items():
+ if name == "__metadata__":
+ continue
+ if not isinstance(meta, dict):
+ raise ValueError(f"Invalid metadata for tensor '{name}': {meta}")
+ try:
+ dtype = meta["dtype"]
+ shape = meta["shape"]
+ offset_start_relative, offset_end_relative = meta["data_offsets"]
+ size = offset_end_relative - offset_start_relative
+ offset_start = data_start_offset + offset_start_relative
+ res[name] = RemoteTensor(dtype=dtype, shape=tuple(shape), offset_start=offset_start, size=size, url=url)
+ except KeyError as e:
+ raise ValueError(f"Missing key in metadata for tensor '{name}': {e}, meta = {meta}")
+
+ return res
+
+ @classmethod
+ def get_metadata(cls, url: str) -> tuple[dict, int]:
+ """
+ Get JSON metadata from a remote safetensor file.
+
+ Returns tuple of (metadata, data_start_offset)
+ """
+ # Request first 5MB of the file (hopefully enough for metadata)
+ read_size = 5 * 1024 * 1024
+ raw_data = cls.get_data_by_range(url, 0, read_size)
+
+ # Parse header
+ # First 8 bytes contain the metadata length as u64 little-endian
+ if len(raw_data) < 8:
+ raise ValueError("Not enough data to read metadata size")
+ metadata_length = int.from_bytes(raw_data[:8], byteorder='little')
+
+ # Calculate the data start offset
+ data_start_offset = 8 + metadata_length
+ alignment = SafetensorRemote.ALIGNMENT
+ if data_start_offset % alignment != 0:
+ data_start_offset += alignment - (data_start_offset % alignment)
+
+ # Check if we have enough data to read the metadata
+ if len(raw_data) < 8 + metadata_length:
+ raise ValueError(f"Could not read complete metadata. Need {8 + metadata_length} bytes, got {len(raw_data)}")
+
+ # Extract metadata bytes and parse as JSON
+ metadata_bytes = raw_data[8:8 + metadata_length]
+ metadata_str = metadata_bytes.decode('utf-8')
+ try:
+ metadata = json.loads(metadata_str)
+ return metadata, data_start_offset
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Failed to parse safetensor metadata as JSON: {e}")
+
+ @classmethod
+ def get_data_by_range(cls, url: str, start: int, size: int = -1) -> bytes:
+ """
+ Get raw byte data from a remote file by range.
+ If size is not specified, it will read the entire file.
+ """
+ import requests
+ from urllib.parse import urlparse
+
+ parsed_url = urlparse(url)
+ if not parsed_url.scheme or not parsed_url.netloc:
+ raise ValueError(f"Invalid URL: {url}")
+
+ headers = cls._get_request_headers()
+ if size > -1:
+ headers["Range"] = f"bytes={start}-{start + size}"
+ response = requests.get(url, allow_redirects=True, headers=headers)
+ response.raise_for_status()
+
+ # Get raw byte data
+ return response.content[slice(size if size > -1 else None)]
+
+ @classmethod
+ def check_file_exist(cls, url: str) -> bool:
+ """
+ Check if a file exists at the given URL.
+ Returns True if the file exists, False otherwise.
+ """
+ import requests
+ from urllib.parse import urlparse
+
+ parsed_url = urlparse(url)
+ if not parsed_url.scheme or not parsed_url.netloc:
+ raise ValueError(f"Invalid URL: {url}")
+
+ try:
+ headers = cls._get_request_headers()
+ headers["Range"] = "bytes=0-0"
+ response = requests.head(url, allow_redirects=True, headers=headers)
+ # Success (2xx) or redirect (3xx)
+ return 200 <= response.status_code < 400
+ except requests.RequestException:
+ return False
+
+ @classmethod
+ def _get_request_headers(cls) -> dict[str, str]:
+ """Prepare common headers for requests."""
+ headers = {"User-Agent": "convert_hf_to_gguf"}
+ if os.environ.get("HF_TOKEN"):
+ headers["Authorization"] = f"Bearer {os.environ['HF_TOKEN']}"
+ return headers
diff --git a/venv/lib/python3.10/site-packages/gguf/vocab.py b/venv/lib/python3.10/site-packages/gguf/vocab.py
new file mode 100644
index 0000000000000000000000000000000000000000..44d066ee75a7ece48dabb168c5054fb4053f5d48
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gguf/vocab.py
@@ -0,0 +1,498 @@
+from __future__ import annotations
+
+import re
+import logging
+import json
+import os
+from pathlib import Path
+from typing import Any, Callable, Sequence, Mapping, Iterable, Protocol, ClassVar, runtime_checkable
+
+try:
+ from sentencepiece import SentencePieceProcessor
+except ImportError:
+ SentencePieceProcessor = None
+
+import gguf
+
+from .gguf_writer import GGUFWriter
+
+logger = logging.getLogger(__name__)
+
+
+class SpecialVocab:
+ merges: list[str]
+ add_special_token: dict[str, bool]
+ special_token_ids: dict[str, int]
+ chat_template: str | Sequence[Mapping[str, str]] | None
+
+ def __init__(
+ self, path: str | os.PathLike[str], load_merges: bool = False,
+ special_token_types: Iterable[str] | None = None,
+ n_vocab: int | None = None,
+ ):
+ self.special_token_ids = {}
+ self.add_special_token = {}
+ self.n_vocab = n_vocab
+ self.load_merges = load_merges
+ self.merges = []
+ self.chat_template = None
+ if special_token_types is not None:
+ self.special_token_types = special_token_types
+ else:
+ self.special_token_types = ('bos', 'eos', 'unk', 'sep', 'pad', 'cls', 'mask')
+ self._load(Path(path))
+
+ def __repr__(self) -> str:
+ return ''.format(
+ len(self.merges), self.special_token_ids or "unset", self.add_special_token or "unset",
+ )
+
+ def add_to_gguf(self, gw: GGUFWriter, quiet: bool = False) -> None:
+ if self.merges:
+ if not quiet:
+ logger.info(f'Adding {len(self.merges)} merge(s).')
+ gw.add_token_merges(self.merges)
+ elif self.load_merges:
+ logger.warning('Adding merges requested but no merges found, output may be non-functional.')
+ for typ, tokid in self.special_token_ids.items():
+ id_handler: Callable[[int], None] | None = getattr(gw, f'add_{typ}_token_id', None)
+ if id_handler is None:
+ logger.warning(f'No handler for special token type {typ} with id {tokid} - skipping')
+ continue
+ if not quiet:
+ logger.info(f'Setting special token type {typ} to {tokid}')
+ id_handler(tokid)
+ for typ, value in self.add_special_token.items():
+ add_handler: Callable[[bool], None] | None = getattr(gw, f'add_add_{typ}_token', None)
+ if add_handler is None:
+ logger.warning(f'No handler for add_{typ}_token with value {value} - skipping')
+ continue
+ if not quiet:
+ logger.info(f'Setting add_{typ}_token to {value}')
+ add_handler(value)
+ if self.chat_template is not None:
+ if not quiet:
+ logger.info(f'Setting chat_template to {self.chat_template}')
+ gw.add_chat_template(self.chat_template)
+
+ def _load(self, path: Path) -> None:
+ self._try_load_from_tokenizer_json(path)
+ self._try_load_from_config_json(path)
+ if self.load_merges and not self.merges:
+ self._try_load_merges_txt(path)
+
+ def _try_load_merges_txt(self, path: Path) -> bool:
+ merges_file = path / 'merges.txt'
+ if not merges_file.is_file():
+ return False
+ with open(merges_file, 'r', encoding = 'utf-8') as fp:
+ first_line = next(fp, '').strip()
+ if not first_line.startswith('#'):
+ fp.seek(0)
+ line_num = 0
+ else:
+ line_num = 1
+ merges = []
+ for line in fp:
+ line_num += 1
+ line = line.strip()
+ if not line:
+ continue
+ parts = line.split(None, 3)
+ if len(parts) != 2:
+ logger.warning(f'{merges_file.name}: Line {line_num}: Entry malformed, ignoring')
+ continue
+ merges.append(f'{parts[0]} {parts[1]}')
+ self.merges = merges
+ return True
+
+ def _set_special_token(self, typ: str, tid: Any) -> None:
+ if not isinstance(tid, int):
+ return
+ if tid < 0:
+ raise ValueError(f'invalid value for special token type {typ}: {tid}')
+ if self.n_vocab is None or tid < self.n_vocab:
+ if typ in self.special_token_ids:
+ return
+ self.special_token_ids[typ] = tid
+ return
+ logger.warning(f'Special token type {typ}, id {tid} out of range, must be under {self.n_vocab} - skipping')
+
+ def _try_load_from_tokenizer_json(self, path: Path) -> bool:
+ tokenizer_file = path / 'tokenizer.json'
+ if tokenizer_file.is_file():
+ with open(tokenizer_file, encoding = 'utf-8') as f:
+ tokenizer = json.load(f)
+ if self.load_merges:
+ merges = tokenizer.get('model', {}).get('merges')
+ if isinstance(merges, list) and merges:
+ if isinstance(merges[0], str):
+ self.merges = merges
+ elif isinstance(merges[0], list) and len(merges[0]) == 2 and isinstance(merges[0][0], str):
+ # New format since transformers 4.45 to support spaces in merges
+ # ref: https://github.com/ggml-org/llama.cpp/issues/9692
+ # TODO: internally store as the new format instead of converting to old
+ if any(' ' in s for pair in merges for s in pair):
+ logger.warning(f'Spaces in merges detected, encoding as {chr(ord(" ") + 256)!r}')
+ self.merges = [
+ ' '.join(
+ [
+ # ensure the spaces are properly encoded
+ ''.join(
+ chr(ord(c) + 256) if c == ' ' else c
+ for c in part
+ )
+ for part in pair
+ ]
+ )
+ for pair in merges
+ ]
+ else:
+ raise ValueError("Unknown tokenizer merges format")
+ added_tokens = tokenizer.get('added_tokens', {})
+ else:
+ added_tokens = {}
+ tokenizer_config_file = path / 'tokenizer_config.json'
+ if not tokenizer_config_file.is_file():
+ return True
+ with open(tokenizer_config_file, encoding = 'utf-8') as f:
+ tokenizer_config = json.load(f)
+ chat_template_alt = None
+ chat_template_file = path / 'chat_template.json'
+ if chat_template_file.is_file():
+ with open(chat_template_file, encoding = 'utf-8') as f:
+ chat_template_alt = json.load(f).get('chat_template')
+ chat_template = tokenizer_config.get('chat_template', chat_template_alt)
+ if chat_template is None or isinstance(chat_template, (str, list)):
+ self.chat_template = chat_template
+ else:
+ logger.warning(f'Bad type for chat_template field in {tokenizer_config_file!r} - ignoring')
+ for typ in self.special_token_types:
+ add_entry = tokenizer_config.get(f'add_{typ}_token')
+ if isinstance(add_entry, bool):
+ self.add_special_token[typ] = add_entry
+ entry = tokenizer_config.get(f'{typ}_token')
+ if isinstance(entry, str):
+ tc_content = entry
+ elif isinstance(entry, dict):
+ entry_content = entry.get('content')
+ if not isinstance(entry_content, str):
+ continue
+ tc_content = entry_content
+ else:
+ continue
+ # We only need the first match here.
+ maybe_token_id = next(
+ (atok.get('id') for atok in added_tokens if atok.get('content') == tc_content),
+ None,
+ )
+ self._set_special_token(typ, maybe_token_id)
+ return True
+
+ def _try_load_from_config_json(self, path: Path) -> bool:
+ config_file = path / 'config.json'
+ if not config_file.is_file():
+ return False
+ with open(config_file, encoding = 'utf-8') as f:
+ config = json.load(f)
+ for typ in self.special_token_types:
+ self._set_special_token(typ, config.get(f'{typ}_token_id'))
+ return True
+
+
+@runtime_checkable
+class BaseVocab(Protocol):
+ tokenizer_model: ClassVar[str]
+ name: ClassVar[str]
+
+
+@runtime_checkable
+class Vocab(BaseVocab, Protocol):
+ vocab_size: int
+ added_tokens_dict: dict[str, int]
+ added_tokens_list: list[str]
+ fname_tokenizer: Path
+
+ def __init__(self, base_path: Path): ...
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: ...
+
+
+class NoVocab(BaseVocab):
+ tokenizer_model = "no_vocab"
+ name = "no_vocab"
+
+ def __repr__(self) -> str:
+ return ""
+
+
+class BpeVocab(Vocab):
+ tokenizer_model = "gpt2"
+ name = "bpe"
+
+ def __init__(self, base_path: Path):
+ added_tokens: dict[str, int] = {}
+
+ if (fname_tokenizer := base_path / 'vocab.json').exists():
+ # "slow" tokenizer
+ with open(fname_tokenizer, encoding="utf-8") as f:
+ self.vocab = json.load(f)
+
+ try:
+ # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
+ with open(base_path / 'added_tokens.json', encoding="utf-8") as f:
+ added_tokens = json.load(f)
+ except FileNotFoundError:
+ pass
+ else:
+ # "fast" tokenizer
+ fname_tokenizer = base_path / 'tokenizer.json'
+
+ # if this fails, FileNotFoundError propagates to caller
+ with open(fname_tokenizer, encoding="utf-8") as f:
+ tokenizer_json = json.load(f)
+
+ tokenizer_model: dict[str, Any] = tokenizer_json['model']
+ if (
+ tokenizer_model['type'] != 'BPE' or tokenizer_model.get('byte_fallback', False)
+ or tokenizer_json['decoder']['type'] != 'ByteLevel'
+ ):
+ raise FileNotFoundError('Cannot find GPT-2 BPE tokenizer')
+
+ self.vocab = tokenizer_model["vocab"]
+
+ if (added := tokenizer_json.get('added_tokens')) is not None:
+ # Added tokens here can be duplicates of the main vocabulary.
+ added_tokens = {item['content']: item['id']
+ for item in added
+ if item['content'] not in self.vocab}
+
+ vocab_size = len(self.vocab)
+ expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
+ actual_ids = sorted(added_tokens.values())
+ if expected_ids != actual_ids:
+ expected_end_id = vocab_size + len(actual_ids) - 1
+ raise ValueError(f"Expected the {len(actual_ids)} added token ID(s) to be sequential in the range "
+ f"{vocab_size} - {expected_end_id}; got {actual_ids}")
+
+ items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
+ self.added_tokens_dict = added_tokens
+ self.added_tokens_list = [text for (text, idx) in items]
+ self.vocab_size_base = vocab_size
+ self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
+ self.fname_tokenizer = fname_tokenizer
+
+ def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ reverse_vocab = {id: encoded_tok for encoded_tok, id in self.vocab.items()}
+
+ for i, _ in enumerate(self.vocab):
+ yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
+
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ for text in self.added_tokens_list:
+ score = -1000.0
+ yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
+
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ yield from self.bpe_tokens()
+ yield from self.added_tokens()
+
+ def __repr__(self) -> str:
+ return f""
+
+
+class SentencePieceVocab(Vocab):
+ tokenizer_model = "llama"
+ name = "spm"
+
+ def __init__(self, base_path: Path):
+ if SentencePieceProcessor is None:
+ raise RuntimeError("sentencepiece is not installed")
+
+ added_tokens: dict[str, int] = {}
+ if (fname_tokenizer := base_path / 'tokenizer.model').exists():
+ # normal location
+ try:
+ with open(base_path / 'added_tokens.json', encoding="utf-8") as f:
+ added_tokens = json.load(f)
+ except FileNotFoundError:
+ pass
+ elif not (fname_tokenizer := base_path.parent / 'tokenizer.model').exists():
+ # not found in alternate location either
+ raise FileNotFoundError('Cannot find tokenizer.model')
+
+ self.sentencepiece_tokenizer = SentencePieceProcessor()
+ self.sentencepiece_tokenizer.LoadFromFile(str(fname_tokenizer))
+ vocab_size = self.sentencepiece_tokenizer.vocab_size()
+
+ new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
+ expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
+ actual_new_ids = sorted(new_tokens.keys())
+
+ if expected_new_ids != actual_new_ids:
+ raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
+
+ # Token pieces that were added to the base vocabulary.
+ self.added_tokens_dict = added_tokens
+ self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
+ self.vocab_size_base = vocab_size
+ self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
+ self.fname_tokenizer = fname_tokenizer
+
+ def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ tokenizer = self.sentencepiece_tokenizer
+ for i in range(tokenizer.vocab_size()):
+ piece = tokenizer.IdToPiece(i)
+ text = piece.encode("utf-8")
+ score: float = tokenizer.GetScore(i)
+
+ toktype = gguf.TokenType.NORMAL
+ if tokenizer.IsUnknown(i):
+ toktype = gguf.TokenType.UNKNOWN
+ if tokenizer.IsControl(i):
+ toktype = gguf.TokenType.CONTROL
+
+ # NOTE: I think added_tokens are user defined.
+ # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
+ # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
+
+ if tokenizer.IsUnused(i):
+ toktype = gguf.TokenType.UNUSED
+ if tokenizer.IsByte(i):
+ toktype = gguf.TokenType.BYTE
+
+ yield text, score, toktype
+
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ for text in self.added_tokens_list:
+ score = -1000.0
+ yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
+
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ yield from self.sentencepiece_tokens()
+ yield from self.added_tokens()
+
+ def __repr__(self) -> str:
+ return f""
+
+
+class LlamaHfVocab(Vocab):
+ tokenizer_model = "llama"
+ name = "hfft"
+
+ def __init__(self, base_path: Path):
+ fname_tokenizer = base_path / 'tokenizer.json'
+ # if this fails, FileNotFoundError propagates to caller
+ with open(fname_tokenizer, encoding='utf-8') as f:
+ tokenizer_json = json.load(f)
+
+ # pre-check so we know if we need transformers
+ tokenizer_model: dict[str, Any] = tokenizer_json['model']
+ is_llama3 = (
+ tokenizer_model['type'] == 'BPE' and tokenizer_model.get('ignore_merges', False)
+ and not tokenizer_model.get('byte_fallback', True)
+ )
+ if is_llama3:
+ raise TypeError('Llama 3 must be converted with BpeVocab')
+
+ if not is_llama3 and (
+ tokenizer_model['type'] != 'BPE' or not tokenizer_model.get('byte_fallback', False)
+ or tokenizer_json['decoder']['type'] != 'Sequence'
+ ):
+ raise FileNotFoundError('Cannot find Llama BPE tokenizer')
+
+ try:
+ from transformers import AutoTokenizer
+ except ImportError as e:
+ raise ImportError(
+ "To use LlamaHfVocab, please install the `transformers` package. "
+ "You can install it with `pip install transformers`."
+ ) from e
+
+ # Allow the tokenizer to default to slow or fast versions.
+ # Explicitly set tokenizer to use local paths.
+ self.tokenizer = AutoTokenizer.from_pretrained(
+ base_path,
+ cache_dir=base_path,
+ local_files_only=True,
+ )
+ assert self.tokenizer.is_fast # assume tokenizer.json is used
+
+ # Initialize lists and dictionaries for added tokens
+ self.added_tokens_list = []
+ self.added_tokens_dict = dict()
+ self.added_tokens_ids = set()
+
+ # Process added tokens
+ for tok, tokidx in sorted(
+ self.tokenizer.get_added_vocab().items(), key=lambda x: x[1]
+ ):
+ # Only consider added tokens that are not in the base vocabulary
+ if tokidx >= self.tokenizer.vocab_size:
+ self.added_tokens_list.append(tok)
+ self.added_tokens_dict[tok] = tokidx
+ self.added_tokens_ids.add(tokidx)
+
+ # Store special tokens and their IDs
+ self.specials = {
+ tok: self.tokenizer.get_vocab()[tok]
+ for tok in self.tokenizer.all_special_tokens
+ }
+ self.special_ids = set(self.tokenizer.all_special_ids)
+
+ # Set vocabulary sizes
+ self.vocab_size_base = self.tokenizer.vocab_size
+ self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
+
+ self.fname_tokenizer = fname_tokenizer
+
+ def hf_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ reverse_vocab = {
+ id: encoded_tok for encoded_tok, id in self.tokenizer.get_vocab().items()
+ }
+
+ for token_id in range(self.vocab_size_base):
+ # Skip processing added tokens here
+ if token_id in self.added_tokens_ids:
+ continue
+
+ # Convert token text to bytes
+ token_text = reverse_vocab[token_id].encode("utf-8")
+
+ # Yield token text, score, and type
+ yield token_text, self.get_token_score(token_id), self.get_token_type(
+ token_id, token_text, self.special_ids # Reuse already stored special IDs
+ )
+
+ def get_token_type(self, token_id: int, token_text: bytes, special_ids: set[int]) -> gguf.TokenType:
+ # Special case for byte tokens
+ if re.fullmatch(br"<0x[0-9A-Fa-f]{2}>", token_text):
+ return gguf.TokenType.BYTE
+
+ # Determine token type based on whether it's a special token
+ return gguf.TokenType.CONTROL if token_id in special_ids else gguf.TokenType.NORMAL
+
+ def get_token_score(self, token_id: int) -> float:
+ # Placeholder for actual logic to determine the token's score
+ # This needs to be implemented based on specific requirements
+ return -1000.0 # Default score
+
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ for text in self.added_tokens_list:
+ if text in self.specials:
+ toktype = self.get_token_type(self.specials[text], b'', self.special_ids)
+ score = self.get_token_score(self.specials[text])
+ else:
+ toktype = gguf.TokenType.USER_DEFINED
+ score = -1000.0
+
+ yield text.encode("utf-8"), score, toktype
+
+ def has_newline_token(self):
+ return "<0x0A>" in self.tokenizer.vocab or "\n" in self.tokenizer.vocab
+
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
+ yield from self.hf_tokens()
+ yield from self.added_tokens()
+
+ def __repr__(self) -> str:
+ return f""
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..c761329198f8a4b1df0e7bf88244d12a64600760
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/METADATA
@@ -0,0 +1,163 @@
+Metadata-Version: 2.4
+Name: google-api-python-client
+Version: 2.178.0
+Summary: Google API Client Library for Python
+Home-page: https://github.com/googleapis/google-api-python-client/
+Author: Google LLC
+Author-email: googleapis-packages@google.com
+License: Apache 2.0
+Keywords: google api client
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Operating System :: OS Independent
+Classifier: Topic :: Internet :: WWW/HTTP
+Requires-Python: >=3.7
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: httplib2<1.0.0,>=0.19.0
+Requires-Dist: google-auth!=2.24.0,!=2.25.0,<3.0.0,>=1.32.0
+Requires-Dist: google-auth-httplib2<1.0.0,>=0.2.0
+Requires-Dist: google-api-core!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0,<3.0.0,>=1.31.5
+Requires-Dist: uritemplate<5,>=3.0.1
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-dist
+Dynamic: requires-python
+Dynamic: summary
+
+# Google API Client
+
+[](https://badge.fury.io/py/google-api-python-client)
+
+This is the [Google API Python client library](https://cloud.google.com/apis/docs/client-libraries-explained#google_api_client_libraries)
+for Google's discovery based APIs. To get started, please see the
+[docs folder](https://github.com/googleapis/google-api-python-client/blob/main/docs/README.md).
+
+This library is considered complete and is in maintenance mode. This means
+that we will address critical bugs and security issues but will not add any
+new features.
+
+This library is officially supported by Google. However, the maintainers of
+this repository recommend using [Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python),
+where possible, for new code development. For more information, please visit
+[Client Libraries Explained](https://cloud.google.com/apis/docs/client-libraries-explained).
+
+## Version 2.0 Release
+The 2.0 release of `google-api-python-client` includes a substantial reliability
+improvement, compared with 1.x, as discovery documents are now cached in the library
+rather than fetched dynamically. It is highly recommended to upgrade from v1.x to v2.x.
+
+Only python 3.7 and newer is supported. If you are not able to upgrade python, then
+please continue to use version 1.x as we will continue supporting python 2.7+ in
+[v1](https://github.com/googleapis/google-api-python-client/tree/v1).
+
+Discovery documents will no longer be retrieved dynamically when
+you call `discovery.build()`. The discovery documents will instead be retrieved
+from the client library directly. New versions of this library are released weekly.
+As a result of caching the discovery documents, the size of this package is at least
+50 MB larger compared to the previous version.
+
+Please see the [Migration Guide](https://github.com/googleapis/google-api-python-client/blob/main/UPGRADING.md)
+for more information.
+
+## Documentation
+
+See the [docs folder](https://github.com/googleapis/google-api-python-client/blob/main/docs/README.md) for more detailed instructions and additional documentation.
+
+## Other Google API libraries
+
+The maintainers of this repository recommend using
+[Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python),
+where possible, for new code development due to the following reasons:
+
+With [Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python):
+- There is a separate client library for each API, so you can choose
+which client libraries to download. Whereas, `google-api-python-client` is a
+single client library for all APIs. As a result, the total package size for
+`google-api-python-client` exceeds 50MB.
+- There are stricter controls for breaking changes to the underlying APIs
+as each client library is focused on a specific API.
+- There are more features in these Cloud Client Libraries as each library is
+focused on a specific API, and in some cases, the libraries are owned by team
+who specialized in that API.
+- Developers will benefit from intellisense.
+
+For more information, please visit
+[Client Libraries Explained](https://cloud.google.com/apis/docs/client-libraries-explained).
+
+Although there are many benefits to moving to
+[Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python),
+the maintainers want to emphasize that `google-api-python-client` will continue
+to be supported.
+
+For Google Ads API, we recommend using [Google Ads API Client Library for Python](https://github.com/googleads/google-ads-python/).
+
+For Google Firebase Admin API, we recommend using [Firebase Admin Python SDK](https://github.com/firebase/firebase-admin-python).
+
+## Installation
+
+Install this library in a [virtualenv](https://virtualenv.pypa.io/en/latest/) using pip. virtualenv is a tool to
+create isolated Python environments. The basic problem it addresses is one of
+dependencies and versions, and indirectly permissions.
+
+With virtualenv, it's possible to install this library without needing system
+install permissions, and without clashing with the installed system
+dependencies.
+
+### Mac/Linux
+
+```bash
+pip3 install virtualenv
+virtualenv
+source /bin/activate
+/bin/pip install google-api-python-client
+```
+
+### Windows
+
+```batch
+pip install virtualenv
+virtualenv
+\Scripts\activate
+\Scripts\pip.exe install google-api-python-client
+```
+
+## Supported Python Versions
+
+Python 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 are fully supported and tested. This library may work on later versions of 3, but we do not currently run tests against those versions.
+
+## Unsupported Python Versions
+
+Python < 3.7
+
+## Third Party Libraries and Dependencies
+
+The following libraries will be installed when you install the client library:
+* [httplib2](https://github.com/httplib2/httplib2)
+* [uritemplate](https://github.com/sigmavirus24/uritemplate)
+
+For development you will also need the following libraries:
+* [WebTest](https://pypi.org/project/WebTest/)
+* [pyopenssl](https://pypi.python.org/pypi/pyOpenSSL)
+
+## Contributing
+
+Please see our [Contribution Guide](https://github.com/googleapis/google-api-python-client/blob/main/CONTRIBUTING.rst).
+In particular, we love pull requests - but please make sure to sign
+the contributor license agreement.
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..abcb37167fd9d360c75e826507d207143d5371ec
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/RECORD
@@ -0,0 +1,589 @@
+apiclient/__init__.py,sha256=U1SOZ1GeeF3uCr0fzO5Od-rpe17R12-Ppyq25NTSbow,746
+apiclient/__pycache__/__init__.cpython-310.pyc,,
+google_api_python_client-2.178.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+google_api_python_client-2.178.0.dist-info/METADATA,sha256=yz7HCpbEUx7Go3VHj3AShILOQkvc84Mr6txS0PijYNk,6952
+google_api_python_client-2.178.0.dist-info/RECORD,,
+google_api_python_client-2.178.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+google_api_python_client-2.178.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
+google_api_python_client-2.178.0.dist-info/top_level.txt,sha256=lbWgdDwQ3oww0ub0pmZ3fmIYAOTHf18Two4U9CxRlnw,58
+googleapiclient/__init__.py,sha256=kFWxKShJalbnrCuV0klL7mjZaiXfPpjlqmyKyI8yfTU,904
+googleapiclient/__pycache__/__init__.cpython-310.pyc,,
+googleapiclient/__pycache__/_auth.cpython-310.pyc,,
+googleapiclient/__pycache__/_helpers.cpython-310.pyc,,
+googleapiclient/__pycache__/channel.cpython-310.pyc,,
+googleapiclient/__pycache__/discovery.cpython-310.pyc,,
+googleapiclient/__pycache__/errors.cpython-310.pyc,,
+googleapiclient/__pycache__/http.cpython-310.pyc,,
+googleapiclient/__pycache__/mimeparse.cpython-310.pyc,,
+googleapiclient/__pycache__/model.cpython-310.pyc,,
+googleapiclient/__pycache__/sample_tools.cpython-310.pyc,,
+googleapiclient/__pycache__/schema.cpython-310.pyc,,
+googleapiclient/__pycache__/version.cpython-310.pyc,,
+googleapiclient/_auth.py,sha256=QttUwhmp7BmhW5CReaAOVGH6kEtITYmEHhVCVmsnDPs,5736
+googleapiclient/_helpers.py,sha256=iNxILG6iNNFukr7lhaYfVqX4oFM5SERvcsU3JxeOo6I,6723
+googleapiclient/channel.py,sha256=Fc4nxu-RxGkjY_STp9bwJfZaLan6VdX-DNniH-ANSuE,11054
+googleapiclient/discovery.py,sha256=9TKz9stsr8Q9TPTjKG1I6yHoPH1ISRvh58q_NoX3mOM,66341
+googleapiclient/discovery_cache/__init__.py,sha256=ww_vl0vhVLuHSEdRTv3-gq6EDG--Ff7rILYHHFifnzc,2315
+googleapiclient/discovery_cache/__pycache__/__init__.cpython-310.pyc,,
+googleapiclient/discovery_cache/__pycache__/appengine_memcache.cpython-310.pyc,,
+googleapiclient/discovery_cache/__pycache__/base.cpython-310.pyc,,
+googleapiclient/discovery_cache/__pycache__/file_cache.cpython-310.pyc,,
+googleapiclient/discovery_cache/appengine_memcache.py,sha256=6T1pQj-toAhDwfgLuiggFGhxKNGw5y-NnLUzLIF_M4s,1657
+googleapiclient/discovery_cache/base.py,sha256=yCDPtxnbNN-p5_9fzBacC6P3wcUPlaCQIy5v_dXTons,1389
+googleapiclient/discovery_cache/documents/abusiveexperiencereport.v1.json,sha256=S71sOgX6Jaa_CVbAYzdQANp6oxb8poocJieP6Q0KW0E,5671
+googleapiclient/discovery_cache/documents/acceleratedmobilepageurl.v1.json,sha256=pyMbFLPRkHJ-j_vpoXoTgLeJmB_Ff8aGoY94qtSIjC4,6729
+googleapiclient/discovery_cache/documents/accessapproval.v1.json,sha256=BRI423YSaihTrt0cM8SIhfJwC0gCWlWeuRT5DyzO3c0,52051
+googleapiclient/discovery_cache/documents/accesscontextmanager.v1.json,sha256=rYacI7DtJne564oH_O14r3llLVOn9cqXlyCMw9PDUWw,117752
+googleapiclient/discovery_cache/documents/accesscontextmanager.v1beta.json,sha256=Vsv_nz7ubkkbGwNgxirN2AWgUuYH0mADUx9LFaqKu_c,51062
+googleapiclient/discovery_cache/documents/acmedns.v1.json,sha256=l4yO_s08Dowy9AdSBd857ZVqw6Ea4PWt1KE1OqOb9mE,6858
+googleapiclient/discovery_cache/documents/addressvalidation.v1.json,sha256=JQV7-cW61aZFFdW9MFu86CVTCg6XiBvSa8EGIt7Vks4,50336
+googleapiclient/discovery_cache/documents/adexchangebuyer.v1.2.json,sha256=0-XVzUa3kcqFiCZYk_W0au5mIV5-w3AgBtQJsSnWL9w,20475
+googleapiclient/discovery_cache/documents/adexchangebuyer.v1.3.json,sha256=6lFs8ULCDsQuo8s48oBpFdDCVbwICk6MNaCvDVrhP9Q,59967
+googleapiclient/discovery_cache/documents/adexchangebuyer.v1.4.json,sha256=pgYvRj3gK2vBxH7Dh4YoCqd7TXTzTDPQqVqOlVRxITk,136987
+googleapiclient/discovery_cache/documents/adexchangebuyer2.v2beta1.json,sha256=DsPe2AUTiMhcL_RQl_DIP6jVj_C_6BwM9knbgdt6auY,231740
+googleapiclient/discovery_cache/documents/adexperiencereport.v1.json,sha256=ZcB2Sna6t35lyCS6gJZ-FBePqKfGK9y1m2K8zVNDkN0,6644
+googleapiclient/discovery_cache/documents/admin.datatransfer_v1.json,sha256=X0fsf--Hl-o4vnRBulXOjJEWYued_nVmxrqM47rFyOg,12132
+googleapiclient/discovery_cache/documents/admin.datatransferv1.json,sha256=X0fsf--Hl-o4vnRBulXOjJEWYued_nVmxrqM47rFyOg,12132
+googleapiclient/discovery_cache/documents/admin.directory_v1.json,sha256=A3d38Jaxq_PaphIrzJudEx5tnPwdfAg1HpEAh5LLnaw,279074
+googleapiclient/discovery_cache/documents/admin.directoryv1.json,sha256=A3d38Jaxq_PaphIrzJudEx5tnPwdfAg1HpEAh5LLnaw,279074
+googleapiclient/discovery_cache/documents/admin.reports_v1.json,sha256=m13yNxmLcs-ZJ44mTXU6LVIFMqzPzAgrr8oWTiUImaQ,60701
+googleapiclient/discovery_cache/documents/admin.reportsv1.json,sha256=m13yNxmLcs-ZJ44mTXU6LVIFMqzPzAgrr8oWTiUImaQ,60701
+googleapiclient/discovery_cache/documents/admob.v1.json,sha256=KqHlEbdrL6m9INFAwhX9wFuqvR5Kjk_rdfu6mtc4XY4,52164
+googleapiclient/discovery_cache/documents/admob.v1beta.json,sha256=gcGNiedgQiUsitwzTPPv-yTsWzcR7iCV3_A9VO5G2f8,91957
+googleapiclient/discovery_cache/documents/adsense.v2.json,sha256=54PjFeWncbnat_yip6M45yE8K5NoSfKvUFhKRUOTuVk,106527
+googleapiclient/discovery_cache/documents/adsensehost.v4.1.json,sha256=kKGnNG3aFbYwLFOLJkIGph3m7vC2heaob68rlmV4J28,37965
+googleapiclient/discovery_cache/documents/adsenseplatform.v1.json,sha256=sxqJvzMQS0OW7i_spxKrvmpI2BTZ-fPguABRUzEeKWs,20170
+googleapiclient/discovery_cache/documents/adsenseplatform.v1alpha.json,sha256=0aXwY1GPvIV4Qs09ixPjP2QGgI6YIJjvA1_ChZMv288,34957
+googleapiclient/discovery_cache/documents/advisorynotifications.v1.json,sha256=LjKYP_4Fy_is5k-nccRqXa9usXF5_rBxhE_qdN9FkqE,20673
+googleapiclient/discovery_cache/documents/aiplatform.v1.json,sha256=LVoqtddzKQXTsPEDaa9q0YTQ3vJ0HflGiohvwZ94mWQ,1865664
+googleapiclient/discovery_cache/documents/aiplatform.v1beta1.json,sha256=OneHf92j8XkJ42Nn3ReWUzHfYf-3WO0_B8dDZg0M2p4,2247495
+googleapiclient/discovery_cache/documents/airquality.v1.json,sha256=Jid1ijxffWKiYwOdpwu_toVra3fOeowW8QuMkz2wpao,40963
+googleapiclient/discovery_cache/documents/alertcenter.v1beta1.json,sha256=mGQhl9nyAkBKYbJvHtem2LVzKnzHi2wkkSAIlim07lk,69312
+googleapiclient/discovery_cache/documents/alloydb.v1.json,sha256=WA2zNv2cKwn27BJkt54suv3eJUwP7AjTC5Z5W7EjKjs,221645
+googleapiclient/discovery_cache/documents/alloydb.v1alpha.json,sha256=5oWfP2IX-27yQ19jAy2HecgK2f7jOyVObwxyy54rVFQ,229551
+googleapiclient/discovery_cache/documents/alloydb.v1beta.json,sha256=5825NwtKW21TYl1fQLEFAr9EFXj0EhZvPGc7CjDvQjg,228913
+googleapiclient/discovery_cache/documents/analytics.v3.json,sha256=pq5nLmdNvFR-k8Sre800U3mI2tU6hVZGdQCNX_VJNiE,195428
+googleapiclient/discovery_cache/documents/analyticsadmin.v1alpha.json,sha256=XLHJyB_BgODx05koChpjvxgTXVbl9jloxBV0v6LrJps,335909
+googleapiclient/discovery_cache/documents/analyticsadmin.v1beta.json,sha256=cPjvjzFbBQkY6C3g5ITM3E9NTNgCwui7XALSx_Rh-Ek,124871
+googleapiclient/discovery_cache/documents/analyticsdata.v1alpha.json,sha256=3rdVFqqDjQQ7-0qi_UkAYpRthvRKjoXJ8SJzulNHBn0,80445
+googleapiclient/discovery_cache/documents/analyticsdata.v1beta.json,sha256=-ptvrqUp-0rNGlell3IyH12yzL7LQbz9nBKOukMThkE,97076
+googleapiclient/discovery_cache/documents/analyticshub.v1.json,sha256=cQmTUHMaAe5FwbebXWcZsUaLchco9RoG34AOPCnrzVs,101959
+googleapiclient/discovery_cache/documents/analyticshub.v1beta1.json,sha256=E41woRHEKP3MhxdW2LcbCYoBJyA0qhVHL-CVyTqh3kY,58342
+googleapiclient/discovery_cache/documents/analyticsreporting.v4.json,sha256=8S4FyrAstnlesJ3ss4fYM7V18YvJgMh9S9jIo-vAOY8,61333
+googleapiclient/discovery_cache/documents/androiddeviceprovisioning.v1.json,sha256=VMdXCj6OCgTEktYH3Q_o4SHxg8niniZP9CHbJzVEb2o,61064
+googleapiclient/discovery_cache/documents/androidenterprise.v1.json,sha256=0nMZWAgW4itGY9sXtMWtGZxn4MA3Wb78ol_62nwbqyI,160733
+googleapiclient/discovery_cache/documents/androidmanagement.v1.json,sha256=gQRLjulepW5G4SvmbpMGPL1Jdl2hG-8AnlTTRiA8ee4,326454
+googleapiclient/discovery_cache/documents/androidpublisher.v3.json,sha256=MzqlSXKkqiNEg6gWooH4JQsy5TK9nVfkL1ZlK_wVo4g,402562
+googleapiclient/discovery_cache/documents/apigateway.v1.json,sha256=iT3Nbapbon_vlL96E0zn5QB0x62Le0nby17mm9euAl8,67624
+googleapiclient/discovery_cache/documents/apigateway.v1beta.json,sha256=AlaLyzdwk_VDpObVjgEseM6do0Uv17o7OR68K5dVu3A,69337
+googleapiclient/discovery_cache/documents/apigee.v1.json,sha256=Pxr2lIb7A5LnWb_Q7LxukqygXDJpcGH4T05evoiyBDA,717288
+googleapiclient/discovery_cache/documents/apigeeregistry.v1.json,sha256=hCu1irwJNFHGEQgiTM5HJtqvF1JUeqpBVA8SGUn9syQ,156027
+googleapiclient/discovery_cache/documents/apihub.v1.json,sha256=Cxou6P0LocyPciXUW8KWgPOjLoPdceUWWHg9aInF6Jg,259212
+googleapiclient/discovery_cache/documents/apikeys.v2.json,sha256=FZBL7LZgNkiOp8cChbkg38Xd0oRqDyn9MQRFouSiqRg,22352
+googleapiclient/discovery_cache/documents/apim.v1alpha.json,sha256=vEIuLE-GKaFKbEsNNTZFsDXHe1o1_oytjiHXHPT3h_M,48406
+googleapiclient/discovery_cache/documents/appengine.v1.json,sha256=65gMax89RoLfrrhxg-qhq9DkN1U-llaMAemPNlfNm-I,173074
+googleapiclient/discovery_cache/documents/appengine.v1alpha.json,sha256=7uAqJvDKcKnXelZ9QwU1FTfuSHJlVucIw7bdSStl71g,73992
+googleapiclient/discovery_cache/documents/appengine.v1beta.json,sha256=s7grm0Xa3d6JZvdurHWDIOs4mFNoV2XYstzjS8LcUP4,180798
+googleapiclient/discovery_cache/documents/appengine.v1beta4.json,sha256=yELseCdExWSunuF7afIqEw_94UU7PvKCXDmWkyAbYWg,110912
+googleapiclient/discovery_cache/documents/appengine.v1beta5.json,sha256=OHCPs6izs9jPAEuG8s9dr76KCn3f5lKdfWE5NaQBhZo,110227
+googleapiclient/discovery_cache/documents/apphub.v1.json,sha256=z7tKJ70C9tJbDFcMHqjJAMKR0Q0GzRW4FuVOpKhZ38s,92728
+googleapiclient/discovery_cache/documents/apphub.v1alpha.json,sha256=TDQ5Xr8sQ9ovg4ia-TwK_QsgbUD5J7X3VJxRApMF5Tc,97346
+googleapiclient/discovery_cache/documents/area120tables.v1alpha1.json,sha256=W3nRxsh01aYTWrEV05o-14Ubu4UvIqDelbu01_s9Ve0,26671
+googleapiclient/discovery_cache/documents/areainsights.v1.json,sha256=0NQcZ9gGKOP6UEEMT5XxOC4FxJX7QshdqbVSef0oZFs,13908
+googleapiclient/discovery_cache/documents/artifactregistry.v1.json,sha256=YP7dTr7Tzk3DCK4UDHWFfzbsG9IM9WlLL39R51WEkp4,156307
+googleapiclient/discovery_cache/documents/artifactregistry.v1beta1.json,sha256=k4_yLd-_h7L6vJjtyJhntCmsGuZoOldyb6Ky0G1MHBQ,63804
+googleapiclient/discovery_cache/documents/artifactregistry.v1beta2.json,sha256=Zk-6KXrQVMK2_e36yceZYPl4BVHvEkPFyovXI2Dhvr8,82401
+googleapiclient/discovery_cache/documents/assuredworkloads.v1.json,sha256=7tQoh0i49PkrlRYwzIIzNe1B2PkfdUnQb3wGunhhCQk,73947
+googleapiclient/discovery_cache/documents/assuredworkloads.v1beta1.json,sha256=508FE9wv59x2FP-KXfycNbWdIojNeJT2ncNQM0P1fE4,76128
+googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1.json,sha256=ReuPo9gijkSYfjf2POLjKSLgZsR33LGYYhLWCM991lY,111045
+googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1alpha.json,sha256=0qa-LitkQzNWYpgvcRf4TcNofuW8mBqHILnljTvwBO4,119894
+googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1beta.json,sha256=dC_ReHXZVQWAPLwr08SjvbsdrDS1bBUzwvBTPJGcre0,12485
+googleapiclient/discovery_cache/documents/backupdr.v1.json,sha256=hMjNhydiZQvZ8p4xHrdWFcUanzP54kaMFWpW07iu7lU,222594
+googleapiclient/discovery_cache/documents/baremetalsolution.v1.json,sha256=DgpA2txkVyJ3FJmckMnRzB1LGtD8K6qo8F2eYT6Bi3c,13574
+googleapiclient/discovery_cache/documents/baremetalsolution.v1alpha1.json,sha256=LWBZqVLJQlt0qgc4yoRJWQfwH0oPL8aS4wHGF8LRfzk,19186
+googleapiclient/discovery_cache/documents/baremetalsolution.v2.json,sha256=WWaMmuGvau4vIHHkwYZTQmABw8ZVSsTK7v352CtG3q0,105820
+googleapiclient/discovery_cache/documents/batch.v1.json,sha256=0wcgnE6s8l2GyFjkYpngexkbEn7k0f66d_BDpLZDQb4,89199
+googleapiclient/discovery_cache/documents/beyondcorp.v1.json,sha256=5Z6dYJrYUcCUHmUQbHGplINKddsEK20-vWfSmsbuE5Q,150395
+googleapiclient/discovery_cache/documents/beyondcorp.v1alpha.json,sha256=sZTIfIaMpjuXLiGdAbbD78kRKPuzWYIkopgHWu3IMu4,247634
+googleapiclient/discovery_cache/documents/biglake.v1.json,sha256=b2PX2xQk1os4gE3uIb4XLmjfGcACkexHFN6T5uhcWhI,26554
+googleapiclient/discovery_cache/documents/bigquery.v2.json,sha256=NJA2QokHCsZElDH8Itkb7665BOyoCVzzqjAqYI4-qOI,417358
+googleapiclient/discovery_cache/documents/bigqueryconnection.v1.json,sha256=uogtso7Bp7eexOLF2Syb3hapjEHyOU1Wx62pnBGwefI,43660
+googleapiclient/discovery_cache/documents/bigqueryconnection.v1beta1.json,sha256=d45MeNg37AdYm_s8hO7ZqLd8hDw3qbpif9ecV1OMYIA,32721
+googleapiclient/discovery_cache/documents/bigquerydatapolicy.v1.json,sha256=Nnzx-_JwLwMWOPvbonPg1bLR14ROCPuCiEQWGRjxK7U,35034
+googleapiclient/discovery_cache/documents/bigquerydatatransfer.v1.json,sha256=m6hUZ3p28aOzbpYgz-1Pukx-jLc3Zcj0e6QaRJv6y1U,91300
+googleapiclient/discovery_cache/documents/bigqueryreservation.v1.json,sha256=m0cmwNi5t8VYXYNRi0r5f63ruZWXCTua0Y15sfTfOnA,95319
+googleapiclient/discovery_cache/documents/bigqueryreservation.v1alpha2.json,sha256=u1WvY6zx7CYg_q9OhtqB5I8Su4b1kEA7p3VwegecO8U,44509
+googleapiclient/discovery_cache/documents/bigqueryreservation.v1beta1.json,sha256=zVtHmOXJTgtYX3JK9YoFUW8uNNHwi-ZPHs4gQN-Y0cY,60957
+googleapiclient/discovery_cache/documents/bigtableadmin.v1.json,sha256=udwAbAWXjShMSJcvAaxRNI-V5QFFQdE6InVOhHT-y7Q,32684
+googleapiclient/discovery_cache/documents/bigtableadmin.v2.json,sha256=Y4ekXOg5RtgTs_9Yvi4Np8cDSR_6SOws0d_Od6QwZzY,233269
+googleapiclient/discovery_cache/documents/billingbudgets.v1.json,sha256=v3YOJsAFLFb0dBL3DDh40t5RYi_K8YZUszEi-IY0XQM,27319
+googleapiclient/discovery_cache/documents/billingbudgets.v1beta1.json,sha256=W1XxaGkQBjVGfxUdSJFFi2WIfppU-rP-rkFpSuTKvqk,26850
+googleapiclient/discovery_cache/documents/binaryauthorization.v1.json,sha256=VbVagXrsIjQFnLWQNo7wffILvWF_rvPatEnLx1T_i70,85436
+googleapiclient/discovery_cache/documents/binaryauthorization.v1beta1.json,sha256=9zlVIEnahifUYLArioJ_ycDpVZpet2mkIrclt_WkKQ4,50127
+googleapiclient/discovery_cache/documents/blockchainnodeengine.v1.json,sha256=a1Ofj3cZkV0TgdbkUN88FKmGBeDYWg59orqr0eLjIDY,33214
+googleapiclient/discovery_cache/documents/blogger.v2.json,sha256=_Mn53e4gp6cs6YtNt7826ROf1ne6mpuRjKVWUCBa4D0,21624
+googleapiclient/discovery_cache/documents/blogger.v3.json,sha256=6fBSJsQdIaX4ijJr1hsje92WC8n0jVn0zseJkxnqqpE,44163
+googleapiclient/discovery_cache/documents/books.v1.json,sha256=dWEew3bc3mDWbAhR-f26d9JqXKqiPtpXQ7We2VBfQVs,110062
+googleapiclient/discovery_cache/documents/businessprofileperformance.v1.json,sha256=2FQwtRgx3ObOq_qdL-a_M9evFaluSAUCpPAXZ15JpmM,24459
+googleapiclient/discovery_cache/documents/calendar.v3.json,sha256=PnI_dBpYlyBLYPrRLNdcgUhNC2b-PxX4PY2JEd2jdOU,124158
+googleapiclient/discovery_cache/documents/certificatemanager.v1.json,sha256=YUfN_Zv8VCyn8tbnlJZNcueFEhK7k9VWV3uvmdq-bOQ,73726
+googleapiclient/discovery_cache/documents/chat.v1.json,sha256=ZLYTzPyM_rmpIh2QFE2cqjnOusgkZEGb6tOO1xzDsUU,300431
+googleapiclient/discovery_cache/documents/checks.v1alpha.json,sha256=_Ko7Qb9yYJxCarWZa3mlQg08Y5azaxIAj7smjiqmviA,91808
+googleapiclient/discovery_cache/documents/chromemanagement.v1.json,sha256=gRvNgpEX4z3wkO9SSlEqCCE-v1hxOzs1Y4B5sD-D0sQ,201086
+googleapiclient/discovery_cache/documents/chromepolicy.v1.json,sha256=F_laa2i3Vpu-MZs3oG2WYhfaCDCA6wnF-qGVURohieI,62781
+googleapiclient/discovery_cache/documents/chromeuxreport.v1.json,sha256=B_gPbscveC48075QTg7o8DVwhrw62NnpNdwJlg13Zgk,22609
+googleapiclient/discovery_cache/documents/civicinfo.v2.json,sha256=JjCi8opRulrv88oZVoDyhzsDk7uwp6XV2GvIF9yM8Fs,30843
+googleapiclient/discovery_cache/documents/classroom.v1.json,sha256=jVcsmge-7bqe9eW67nppAraD6dhIECFXV9GbxgQaIQg,245513
+googleapiclient/discovery_cache/documents/cloudasset.v1.json,sha256=3JE1AyYm0cC2DAUZHDhoyPMXR5BWxtuFWYGMXsOgiPc,260056
+googleapiclient/discovery_cache/documents/cloudasset.v1beta1.json,sha256=5_lUxBFrf6WekxeYqMLL5AXBJzk4f0lz3IE85aRjqkY,95594
+googleapiclient/discovery_cache/documents/cloudasset.v1p1beta1.json,sha256=r3Jdq7Re-xz6GOxJ0-Weo5O1wW8V0iadoUhGwtvsRV4,83762
+googleapiclient/discovery_cache/documents/cloudasset.v1p4beta1.json,sha256=RT5pGxMQhQ_T9JKt97G6G94znnnweuqgSwEnby7Vkck,110574
+googleapiclient/discovery_cache/documents/cloudasset.v1p5beta1.json,sha256=R0MmgDRSV1UbtpnsbTSG98ZLWrJoMLNZIfBnhcO40q4,82419
+googleapiclient/discovery_cache/documents/cloudasset.v1p7beta1.json,sha256=9-ptO1OeQc7yRX4cnSpE9LjRIw84CZvv6SIPCwtSufg,88076
+googleapiclient/discovery_cache/documents/cloudbilling.v1.json,sha256=jg1-B4LYm5Dp-V9jUomBsLVOd9H4uPlgCTjME9AHUrs,61261
+googleapiclient/discovery_cache/documents/cloudbilling.v1beta.json,sha256=y3ieQV-zwpC7zVWbfuYdq2z7DmA5p6i7kNIHHFVaXLU,60257
+googleapiclient/discovery_cache/documents/cloudbuild.v1.json,sha256=mi1pZ7wvg5rpHVL675zErZPYPZCeQaBlf05zreZ8jIE,197211
+googleapiclient/discovery_cache/documents/cloudbuild.v1alpha1.json,sha256=tN8lxatpJZdx4mhuKWjgzYeBfbN3ZFgZOhdDI8HdMTc,103536
+googleapiclient/discovery_cache/documents/cloudbuild.v1alpha2.json,sha256=FqGePJRUozQZ3MgYXXDeeBwhKb38oRdL3RDyfn5LKOA,102139
+googleapiclient/discovery_cache/documents/cloudbuild.v1beta1.json,sha256=Z9D0XmsAbFI1Ug2BBm8i4hocf4dzGW0MP_3rprbHH2I,105268
+googleapiclient/discovery_cache/documents/cloudbuild.v2.json,sha256=fzvj1L49M3LSOgrDKSkcHX8DdDCsQFSLwrW9Tel91Ew,113374
+googleapiclient/discovery_cache/documents/cloudchannel.v1.json,sha256=8ftPzRu5DWWy7bCMQe_ks_2RVTcFS-ichTIGbIEKcHA,249757
+googleapiclient/discovery_cache/documents/cloudcommerceprocurement.v1.json,sha256=NtXgLDh60lxmnNf3YKeRYfUr2suT9B1KvXUyXvfeXuU,40056
+googleapiclient/discovery_cache/documents/cloudcontrolspartner.v1.json,sha256=rMIB1jLBv1Hx5BP1XHy1P6SjL5dzpxtgQ0C2JrWdkE8,39795
+googleapiclient/discovery_cache/documents/cloudcontrolspartner.v1beta.json,sha256=WMIVTmWBALeWRidAdfvDf5UMnsjHgJ0m8LZxez5XPQc,39907
+googleapiclient/discovery_cache/documents/clouddebugger.v2.json,sha256=2IO6Cc_uKUbDzdXhyc02Xr2Y7vd8TIRq_2iWDhwGYPE,53446
+googleapiclient/discovery_cache/documents/clouddeploy.v1.json,sha256=Oj50CXluTUqRV6ayyMekTi0vAbcRYnAzrAEpOhPb9kA,259765
+googleapiclient/discovery_cache/documents/clouderrorreporting.v1beta1.json,sha256=LT3OJ_dSdWCJnai8IcrGZ5Gxr4xti3uIknpzRPbNzN8,46460
+googleapiclient/discovery_cache/documents/cloudfunctions.v1.json,sha256=LyCgf0RL_0C2u84WMl91yE7Jgy27OBFxt4UKYw4mEtU,65107
+googleapiclient/discovery_cache/documents/cloudfunctions.v2.json,sha256=uxJghvcBGyUlh39gFzs6SD6RkJ7eEGtqUGhxw_0C9D8,86776
+googleapiclient/discovery_cache/documents/cloudfunctions.v2alpha.json,sha256=sSttj4gAWPpRPQOKHNDx51mefZJ1JIcOHQAepx4iqk0,87041
+googleapiclient/discovery_cache/documents/cloudfunctions.v2beta.json,sha256=9P6-d-vHPklQeJ6hZSvec5SnestkWKQ1PlnQAgj5IG4,86988
+googleapiclient/discovery_cache/documents/cloudidentity.v1.json,sha256=6b2GWS6vTu0tjnS57IyAk0tY2BmY0cLmscyqx_b001k,165545
+googleapiclient/discovery_cache/documents/cloudidentity.v1beta1.json,sha256=3eKjAv53qiWOimOD2TA5dDIgcsVgWIdz6TRMgVAohGY,194846
+googleapiclient/discovery_cache/documents/cloudiot.v1.json,sha256=BLM9X9po2P0rn8osda4MgRc990yAYWFVbRMnoCTjN6w,94703
+googleapiclient/discovery_cache/documents/cloudkms.v1.json,sha256=GE3SPnyU-em3AJdW4YbpZ2BagUGeaXDPNh_0B3KcFB0,211499
+googleapiclient/discovery_cache/documents/cloudlocationfinder.v1alpha.json,sha256=zBbdUnBqS9mkj33dj2RRPxqRzHHI49wT2FRRfMpAwtE,14586
+googleapiclient/discovery_cache/documents/cloudprofiler.v2.json,sha256=DKiyeC2Z010ehm-WHvDJBGMnfVFow8daU56CAP1hlkE,14920
+googleapiclient/discovery_cache/documents/cloudresourcemanager.v1.json,sha256=Ze84AMCb0NrobGUsOppZf84ZMGkyVg3q2qCG76BWM3Y,101735
+googleapiclient/discovery_cache/documents/cloudresourcemanager.v1beta1.json,sha256=pDTAX1oOSWZiGw825NDYsl7cIYz__1ctAege_ysSdSU,58765
+googleapiclient/discovery_cache/documents/cloudresourcemanager.v2.json,sha256=FKliR52dUB8gdJTRYxiAxO5GE8fChL4bbhJj36_VE30,52486
+googleapiclient/discovery_cache/documents/cloudresourcemanager.v2beta1.json,sha256=HYYwrbxp5uvt1c_Oq3AWqfgDPLOjp_i0iJf44X1jA48,52496
+googleapiclient/discovery_cache/documents/cloudresourcemanager.v3.json,sha256=v5y53JMOXgtw6E8KHiqx_M-jf2PYz-89IeA9A1chT80,134613
+googleapiclient/discovery_cache/documents/cloudscheduler.v1.json,sha256=9_pki0w7ePlHy82k2z2CEfkAqNlnpB6bUy9Sfpr0zlo,47107
+googleapiclient/discovery_cache/documents/cloudscheduler.v1beta1.json,sha256=WuGy9dX2WqnKnqSFSVBDAIdvYg1Xmi-GJ2z_gCfJ7os,43317
+googleapiclient/discovery_cache/documents/cloudsearch.v1.json,sha256=zioYxBar0l7onDdnYAfGKjcguMEdRkybFuuQlawHHDE,247310
+googleapiclient/discovery_cache/documents/cloudshell.v1.json,sha256=pRDGK9lNQ9_ADOmlBcTUVzBX422WFWCijv2LK--rzUA,22895
+googleapiclient/discovery_cache/documents/cloudshell.v1alpha1.json,sha256=XoIskUrEjFBy7Saxe7cApOT6ShmcKZlwzRDAiIoxgSI,25615
+googleapiclient/discovery_cache/documents/cloudsupport.v2.json,sha256=bgzxdZLCW_ECHALWO18hIRvYsmo34G6gCD-lSpAn214,51905
+googleapiclient/discovery_cache/documents/cloudsupport.v2beta.json,sha256=rIT5tiNtlXf3I4SPsCWx9nv44Eg-s4VotYzG2qGQhNk,57895
+googleapiclient/discovery_cache/documents/cloudtasks.v2.json,sha256=0sGe-mnA2IeFAiHPThdaUrucNRy3gIENpwYDPB1Gp9s,96758
+googleapiclient/discovery_cache/documents/cloudtasks.v2beta2.json,sha256=3INmN9jyGLRTOU_qNQjeAagECPrA4hu7GLeBlBY3Ojw,113423
+googleapiclient/discovery_cache/documents/cloudtasks.v2beta3.json,sha256=K8KT6FH4hZfX-8cdkXioqZpdnM9F3qIOVi4s4WX-wpk,103749
+googleapiclient/discovery_cache/documents/cloudtrace.v1.json,sha256=Po2AzlboBENj1bTgIVRd7PP7ux9lZ3HrwO1glYEJlkg,12084
+googleapiclient/discovery_cache/documents/cloudtrace.v2.json,sha256=YqE6jcB7F-7Wc-xuHMgXcxO4rxS-QBbjuCDOWaonJ8E,21232
+googleapiclient/discovery_cache/documents/cloudtrace.v2beta1.json,sha256=C-rFqBUcGEdGeys6I18EtbUb-LV2oI5FL8D7EGbrLNk,11533
+googleapiclient/discovery_cache/documents/composer.v1.json,sha256=qH3fnC_gyU8a02OCoafj58vM8CPyj9Ld57eE6o24HvY,105994
+googleapiclient/discovery_cache/documents/composer.v1beta1.json,sha256=yI3F0wTacfqQiOYFvqJUFlZqG4zJl4cKUS6Q0kwv_SM,108920
+googleapiclient/discovery_cache/documents/compute.alpha.json,sha256=6OgbASSwciE-QDOHtE6sitH_CkVJkN6aMg0fiPzORIM,5056610
+googleapiclient/discovery_cache/documents/compute.beta.json,sha256=jrygn0nDlhDFFtY3QtkpCHr21H3cP8dNqVeI2CZaSAw,4488140
+googleapiclient/discovery_cache/documents/compute.v1.json,sha256=mQVBLTXad5LNVWiiXa4xxgOiJlldKduC54AGaTUD2fw,4048262
+googleapiclient/discovery_cache/documents/config.v1.json,sha256=s0GWOZOlfF82W7ae_sQsM4E1UuMJshn5PFO8g11UTmw,113507
+googleapiclient/discovery_cache/documents/connectors.v1.json,sha256=TOUfFrZDCMN68eNcdEVAB5Cj0Lup8bhIFXEL5cJp4nQ,262205
+googleapiclient/discovery_cache/documents/connectors.v2.json,sha256=2bFLJEEKBxwIA1-1_SBlPln4lCwf56uBOPGvJsslnzI,71814
+googleapiclient/discovery_cache/documents/contactcenteraiplatform.v1alpha1.json,sha256=PdSAGqtS9kFWWnmx-DERqKMgiKGGi2QjOB_mkbbjZx8,44331
+googleapiclient/discovery_cache/documents/contactcenterinsights.v1.json,sha256=P5JaFkx_L9Z_hi6ktjq_jfjD1q6xqFdbBOXYcO1TR78,468862
+googleapiclient/discovery_cache/documents/container.v1.json,sha256=fxFa8W364HAoW5pANyVktdnWUVXwfHNFVfbfRaQackY,358019
+googleapiclient/discovery_cache/documents/container.v1beta1.json,sha256=6AKgP-1dZRZquzG3Vg-2zPLJYomlgty196VKaDdJhY4,381432
+googleapiclient/discovery_cache/documents/containeranalysis.v1.json,sha256=LR4BpDI3pnbEmpnpmE-7cUw0HQiT7924oKqQL8RwowU,236694
+googleapiclient/discovery_cache/documents/containeranalysis.v1alpha1.json,sha256=ZZTkrLGyEWOacE9TElIJrbeLeMHqL5z_yXuCMB1KCnw,258243
+googleapiclient/discovery_cache/documents/containeranalysis.v1beta1.json,sha256=0-ZNLJJOiDXh_q-9Hw40lqLRDwRtexxvMOoBF--6OL4,248296
+googleapiclient/discovery_cache/documents/content.v2.1.json,sha256=TEZL-VfEYFmDE89C8G5bkpFB1BobvVxSUJ-7M22YdWk,467702
+googleapiclient/discovery_cache/documents/content.v2.json,sha256=PuV1X8AOtI9T1gaQphOf14GgA06gplme2e31cRNVSlU,389993
+googleapiclient/discovery_cache/documents/contentwarehouse.v1.json,sha256=mvMFtg4zcLO64JQheZ2qUKQCg3I69Wm9TE3TMKuVn6U,226184
+googleapiclient/discovery_cache/documents/css.v1.json,sha256=oDmW6d1Gpr1FORwtwlIscKiMovcuxFilKtBvAnj85Hs,44472
+googleapiclient/discovery_cache/documents/customsearch.v1.json,sha256=gkOUqUMB14JgNUySDvnSooKihyAmZWmbBYJ6Jpz0wHs,63076
+googleapiclient/discovery_cache/documents/datacatalog.v1.json,sha256=x3y4VADlx7N6xFPY6cCx7As86TPmNKZvf9ggVsl8dPk,193895
+googleapiclient/discovery_cache/documents/datacatalog.v1beta1.json,sha256=56ECzij7A64lKIEzGFThCmPfjF_JOFo_PombFxA36mg,182855
+googleapiclient/discovery_cache/documents/dataflow.v1b3.json,sha256=yoPvVUFLI5S3DhMjWoMrj8LJVfPZNX901rM4SsOmtJI,273250
+googleapiclient/discovery_cache/documents/dataform.v1beta1.json,sha256=dPfxZoVCOmAqVtviBcm4gc8aNXPp3xv8owIfjzp2y-U,151108
+googleapiclient/discovery_cache/documents/datafusion.v1.json,sha256=sGSoT575n-amUztEjHEPtYFd8QoF6dSNTQZ_th79jUs,67691
+googleapiclient/discovery_cache/documents/datafusion.v1beta1.json,sha256=053Oj0b65FVbbP5xNo1lOTL-t1emNJTymEd1UognsWM,76628
+googleapiclient/discovery_cache/documents/datalabeling.v1beta1.json,sha256=5AdOFMYk2uvTezbB0CLjZkRnBRzrasRNJaEdZC4TCJc,202109
+googleapiclient/discovery_cache/documents/datalineage.v1.json,sha256=tsC72HLAIXEsB7JwjUaHNLmW_oyv0GGbyUthWXcLN5w,52857
+googleapiclient/discovery_cache/documents/datamigration.v1.json,sha256=LDmS8z_5A8JL1DA2jkHG3nEszWgnWoUx_U1VMf03ydw,241202
+googleapiclient/discovery_cache/documents/datamigration.v1beta1.json,sha256=DHWhpOaH5DusAJflQUl7hpeMi8tCrBQZ6gJFJ3aVYOw,84129
+googleapiclient/discovery_cache/documents/datapipelines.v1.json,sha256=vocmGOA8i7K12Yy3kAeZ1IsUfm3fza3QWFE6taPqP6Y,38301
+googleapiclient/discovery_cache/documents/dataplex.v1.json,sha256=IhTwqk0eJ-k3kEp2w3lboE3gmOxutG9IC9FyI_1dVgs,514257
+googleapiclient/discovery_cache/documents/dataportability.v1.json,sha256=KE3U8M7npfZHnFd_vpoKr8k5IV-3chvTUwErXbDG89E,50269
+googleapiclient/discovery_cache/documents/dataportability.v1beta.json,sha256=GKW5WuiYCWYHCwSmIeIqSF9TKvy3yojt1jpVhXNKEwI,50325
+googleapiclient/discovery_cache/documents/dataproc.v1.json,sha256=b0qvitXrNn3D7UHcxd2IsaYVrv1Qr871nND9FZU1Wvc,428116
+googleapiclient/discovery_cache/documents/dataproc.v1beta2.json,sha256=jfuxbI0IJ3EFmdqwKxUp_DvxU6gLnDToTAicOhZM0qo,256974
+googleapiclient/discovery_cache/documents/datastore.v1.json,sha256=rLgPJcB4W-7TvccUrWyZ7OOWcmQJtBa05kwNvr_k9eM,100229
+googleapiclient/discovery_cache/documents/datastore.v1beta1.json,sha256=Yid7Qf4pqbNmwl1tWayQ_cYyNn7liUImn1YS-bbeijo,28932
+googleapiclient/discovery_cache/documents/datastore.v1beta3.json,sha256=7PvsBf-qzpwJ4jndS7gh34AfWU6OLjnpSn0JzM-YTlI,77221
+googleapiclient/discovery_cache/documents/datastream.v1.json,sha256=VWMcGinGrxGD_L9MT1EwSP8ENrdfSXWvwHkZ-9g2Jmo,122728
+googleapiclient/discovery_cache/documents/datastream.v1alpha1.json,sha256=Z39NqlEop9vBYHYwozndO42Dn7ITrQrf0sChxdaUTew,78971
+googleapiclient/discovery_cache/documents/deploymentmanager.alpha.json,sha256=41TotKSko5LlRXLiPWdj--WrDR5JQxtm9azbm5PFFEc,157016
+googleapiclient/discovery_cache/documents/deploymentmanager.v2.json,sha256=nNECN8yB7JQsazZOTeasWlBXmsSI5Uxgqtp-V1XsXrE,110758
+googleapiclient/discovery_cache/documents/deploymentmanager.v2beta.json,sha256=v8aSTs6IQFilQgKYWabMUR6_tS4pcwQNVo6XrCThW10,153106
+googleapiclient/discovery_cache/documents/developerconnect.v1.json,sha256=j8l-8kiAwBvH7IjOG7LSML6gsCLZVrrmwSKpddfN-KQ,100878
+googleapiclient/discovery_cache/documents/dfareporting.v3.3.json,sha256=AaucsfQ-9Hx6evOCWHX3E6n6llRjAlvVFEqLD2bpYXE,721039
+googleapiclient/discovery_cache/documents/dfareporting.v3.4.json,sha256=0KvRG3-gvfK5CunHotnX5uTGYwl8W_af_vg0LX0q_NU,748283
+googleapiclient/discovery_cache/documents/dfareporting.v3.5.json,sha256=E0e7bs-i0WQg8X-rLjIOn5DpeCDtiE9yDB_-J4VuCAw,17300
+googleapiclient/discovery_cache/documents/dfareporting.v4.json,sha256=_mAKU4QlT8B2alpLzXBBnkYysMGqIGpvgjppuEfirHw,597447
+googleapiclient/discovery_cache/documents/dialogflow.v2.json,sha256=vw95tOuNGU5DlutCCoDcuYV9tOA6zDVxNXr6GSfXEJk,946953
+googleapiclient/discovery_cache/documents/dialogflow.v2beta1.json,sha256=Svg0azzFwt9-kjkjBljOebjSWPJpuTcqtr04pTLbHaU,962322
+googleapiclient/discovery_cache/documents/dialogflow.v3.json,sha256=t179mbikan3StURtCULvttptjXEqqa865iboAQgPuFc,808323
+googleapiclient/discovery_cache/documents/dialogflow.v3beta1.json,sha256=HJcJq9ChepKqHgqQEEcKbLVtgOiuSxEdJlBXzMHoXOg,857446
+googleapiclient/discovery_cache/documents/digitalassetlinks.v1.json,sha256=3CICeK-vxTL7U-PF6KQfUjQxPO39tHKmLa32-6kwqsw,29872
+googleapiclient/discovery_cache/documents/discovery.v1.json,sha256=OQvmfp6aUxzASZk9m__FvI0wuRXNWI_41RykyxtDkzU,18215
+googleapiclient/discovery_cache/documents/discoveryengine.v1.json,sha256=oJ-Q5P92HKiK2ZEbCPeEDUnTD--xlOaBWY2O7P7hWOc,1070900
+googleapiclient/discovery_cache/documents/discoveryengine.v1alpha.json,sha256=iitTARGKjD7ApODS-hTxlOIWD3I0e2Ojl1yy5UWWwG8,1223621
+googleapiclient/discovery_cache/documents/discoveryengine.v1beta.json,sha256=pXq1dPyaXizvNpPcYcVAyGPYn2a11-TKacQMMH5bAiA,1120819
+googleapiclient/discovery_cache/documents/displayvideo.v1.json,sha256=RRZQfVKtGzhfs9Kx6Rp2mrBcfaRJ9p5B9I76uIcVf4c,737810
+googleapiclient/discovery_cache/documents/displayvideo.v2.json,sha256=Yvxpp6dxLN2QgxbhxpYWEBcJfmZo6GH0SAZgxj55Jr4,848538
+googleapiclient/discovery_cache/documents/displayvideo.v3.json,sha256=1m3HmPrM-yaPKK_9PopBzJt1Hh7dpw1zhqQ5RZqjR6o,914416
+googleapiclient/discovery_cache/documents/displayvideo.v4.json,sha256=wfa6rCzUHp61p5G5hlr55GbyNMSHIuEEHH0xrwsCB3o,914010
+googleapiclient/discovery_cache/documents/dlp.v2.json,sha256=uEiP4LXUBlVZO3mqr0b5mtyf5ViYCtdRLfcjVkaZMZc,527929
+googleapiclient/discovery_cache/documents/dns.v1.json,sha256=yLqVURduJwi3t7Jg_43UBOTPnG74K4kkrT53XpGHEro,121299
+googleapiclient/discovery_cache/documents/dns.v1beta2.json,sha256=p5ymbYYTMHIZyjOm5TxHg0t4Wolzko5gaFjwHi16tm4,121683
+googleapiclient/discovery_cache/documents/dns.v2.json,sha256=uMSPBTHSlq6gMc-OC9ap_C9WuE34lwbub8U8wOlwoTY,136579
+googleapiclient/discovery_cache/documents/docs.v1.json,sha256=TygbvHb6iYjxvWRXXgWYnCvbPNtkAdXipHTI4QH6aro,179902
+googleapiclient/discovery_cache/documents/documentai.v1.json,sha256=T8uThRVLN-vXilbtKRObJMVTxHD6G0m0NSwo2VXUA2g,217968
+googleapiclient/discovery_cache/documents/documentai.v1beta2.json,sha256=gOemdhcv2MjxnsArox4YiE7zXia3wVKtMsD6eqBauYw,213046
+googleapiclient/discovery_cache/documents/documentai.v1beta3.json,sha256=nuR_lCeU93rZZ_t0vs-Qe0ZFC6oxhS5c1PeiFscSnIs,249077
+googleapiclient/discovery_cache/documents/domains.v1.json,sha256=3Eui21VVZWEtdjp_EEQV6R_VBTpi0BZaHKrezY29q-8,121515
+googleapiclient/discovery_cache/documents/domains.v1alpha2.json,sha256=72bRYKwL6d7FELZsbiHgqM_HbEiuviL9ATseeZXiRio,122168
+googleapiclient/discovery_cache/documents/domains.v1beta1.json,sha256=KHOaPQoDkM0KpOYPet7whUbpdBp5jMc9yIxGb-OyAJU,121805
+googleapiclient/discovery_cache/documents/domainsrdap.v1.json,sha256=0kMvTxrY_-Slq8YjmDxT3Q1LZsiE4EkltzeZvzj7R3s,11381
+googleapiclient/discovery_cache/documents/doubleclickbidmanager.v1.1.json,sha256=jHYIGcAx7c3WN_5Mvr6LpEFpkB-VYgyz-rpoi41Fl-8,117347
+googleapiclient/discovery_cache/documents/doubleclickbidmanager.v1.json,sha256=c-oeCNUdKAdNJa3Bm3sqAgb6LpgiCn-s6NUUp4rsUt8,3347
+googleapiclient/discovery_cache/documents/doubleclickbidmanager.v2.json,sha256=y_jmaALx58H7CcutbeZdjITVzjYpeA-Y6aUFAmnvP_E,21518
+googleapiclient/discovery_cache/documents/doubleclicksearch.v2.json,sha256=hKxva7ErQGWge70V83F4EHAk9YSSGEmBjlt-CG1Gbeg,34911
+googleapiclient/discovery_cache/documents/drive.v2.json,sha256=i1UdnwC7H098dPUZ7HW6OdlYhMEQ5uqBj0uPA1KjXPA,204601
+googleapiclient/discovery_cache/documents/drive.v3.json,sha256=XEjjECJBzMm8vC5yJexihFt6DGdaNGnAPm1gntQ0XE0,173544
+googleapiclient/discovery_cache/documents/driveactivity.v2.json,sha256=SexajzanodYVuVUGQG6TXbAZo9tQXZwnaiqiTRFbUIk,37015
+googleapiclient/discovery_cache/documents/drivelabels.v2.json,sha256=XEniMP6MnFB_cAlTfWQKVZj-hOUy6-ML3KCaq3mMMSo,108498
+googleapiclient/discovery_cache/documents/drivelabels.v2beta.json,sha256=P3QqTd8FIfrED20ud5cHs6lue-40sBZ6tz37PNzwTq4,109974
+googleapiclient/discovery_cache/documents/essentialcontacts.v1.json,sha256=HL3qRBgEecmFCMjYEZJwnoykj5EQ5szQQwXDHLd1Nek,34502
+googleapiclient/discovery_cache/documents/eventarc.v1.json,sha256=ngvQ22CHilGip17H-QMrIoIa3VKjuHV0msAptX5rX_s,167620
+googleapiclient/discovery_cache/documents/eventarc.v1beta1.json,sha256=mY2ecbNBWJyhuWfnF0fndnDH0Dqr1a38N8c36huuixw,46836
+googleapiclient/discovery_cache/documents/factchecktools.v1alpha1.json,sha256=W4CxWFn3fyxidiE6iML3nT2EJg8FsBTVPgOOGjXKy6I,22449
+googleapiclient/discovery_cache/documents/fcm.v1.json,sha256=vYDeam9XTAI9UBDZpX3kksMg4PfLAAGTPfazbK7-nPo,31853
+googleapiclient/discovery_cache/documents/fcmdata.v1beta1.json,sha256=MyF9jSa11RwspABXDPfTYu7GVCMRxKoOOAeb6FkJiIY,15964
+googleapiclient/discovery_cache/documents/file.v1.json,sha256=kfd3ILgt-Rg_9EKGV3yOAyTje3KbNwUK7Z0mnkfs5xE,84721
+googleapiclient/discovery_cache/documents/file.v1beta1.json,sha256=8wHQp8NLZe4nqNGSZRxL7PpfWVJ8Pe32nRqxMLUbCsY,97698
+googleapiclient/discovery_cache/documents/firebase.v1beta1.json,sha256=zY_XPnBN8IKgUNmxXwRSw0xvfhwA1TjCyjmoVx-8zFw,116623
+googleapiclient/discovery_cache/documents/firebaseappcheck.v1.json,sha256=4sJ6aL6BDdt90T5PJa-4W5DbSIrHL0SvxCL4Dp5Xyxw,101098
+googleapiclient/discovery_cache/documents/firebaseappcheck.v1beta.json,sha256=ZgX4sBB3YsiZzB1iKf47-uyZKWS4hKs9F9UriqctAcI,119685
+googleapiclient/discovery_cache/documents/firebaseappdistribution.v1.json,sha256=mU5U6Iw-dcVvFKKcCWGDW9yf_gCJH3CxgYobhvNNqpU,65376
+googleapiclient/discovery_cache/documents/firebaseappdistribution.v1alpha.json,sha256=iTomZPSP4zvcinoHBkk8ZAwAhfeMp-n11NxGL15u5ho,58208
+googleapiclient/discovery_cache/documents/firebaseapphosting.v1.json,sha256=QgTbX7a0yIgK6BiY0OABIZ433mQNTwYeBvLcUqa6Fy0,97764
+googleapiclient/discovery_cache/documents/firebaseapphosting.v1beta.json,sha256=m9ED-LVbszSVgJ2uzaW1cCOWjgVMuK4jFD3gX80fHcs,100572
+googleapiclient/discovery_cache/documents/firebasedatabase.v1beta.json,sha256=CDrBLeHyVymSxQdwRs4RMA7M-WBCs5Jg79lnLExxtuE,15647
+googleapiclient/discovery_cache/documents/firebasedataconnect.v1.json,sha256=xJVwCwXg6XyvgfZLWhlqDBWMZFe-EuuR-vGUhSqBSHU,72705
+googleapiclient/discovery_cache/documents/firebasedataconnect.v1beta.json,sha256=DsbcH2FuIalrVD4ewz78iknExow-OD66Rx7Emxg9t8Y,72913
+googleapiclient/discovery_cache/documents/firebasedynamiclinks.v1.json,sha256=rncuTrigAtLNh7coo5yBLG10g9E7qNRzMl7D9Lrs6Uo,33276
+googleapiclient/discovery_cache/documents/firebasehosting.v1.json,sha256=iUmcrmwQcS2COWiCL1POQJOfbbFVMfnpo9eqWWUiyN0,26742
+googleapiclient/discovery_cache/documents/firebasehosting.v1beta1.json,sha256=35WM0roy6_pJoCwTgml7DPn-xXi3QU5jaZZDMfESBfc,133655
+googleapiclient/discovery_cache/documents/firebaseml.v1.json,sha256=fshZd5QIjB4RNnuMlW2r_7Sa50JKTyE-UHjmIEwDPik,10356
+googleapiclient/discovery_cache/documents/firebaseml.v1beta2.json,sha256=1Ajl7yL81dyXtz5SQPKdh6GpKMR6W3dw-tdYjI1Sky4,16713
+googleapiclient/discovery_cache/documents/firebaseml.v2beta.json,sha256=Y9F1HlToS4ILa1e_SIH_BAmP6a07oZCMsPIU4tCwFf4,92516
+googleapiclient/discovery_cache/documents/firebaserules.v1.json,sha256=ZJDkeRQTv28Vjex0ru4YEllbvnZbXMHPNxknLMZrUE4,34267
+googleapiclient/discovery_cache/documents/firebasestorage.v1beta.json,sha256=zOjCJ_8yjwYhvWe_8RQmeFP5aACyZe0DpTFgS5YNyS4,11253
+googleapiclient/discovery_cache/documents/firestore.v1.json,sha256=659jH62qouZWAcBQILQsilXC_OpPgGNkCouG_MUZetI,192785
+googleapiclient/discovery_cache/documents/firestore.v1beta1.json,sha256=oXPQDOmT8iAGu0AWYCKKjHpSZKK5dBpMel8ui3a5rFk,117729
+googleapiclient/discovery_cache/documents/firestore.v1beta2.json,sha256=txcECwtkTIOX8xI2IftwdWLDgDJlhgrgQXjLjjBNfoE,44575
+googleapiclient/discovery_cache/documents/fitness.v1.json,sha256=1MKnVrlqoJrCbnSw2dXGgsnVrTpsoUvAoPtF2bObQTE,62402
+googleapiclient/discovery_cache/documents/forms.v1.json,sha256=hnOruUSkg9PsT1ei2K9k5tvM5LsTbFtQCVd1NHtvzEc,53219
+googleapiclient/discovery_cache/documents/games.v1.json,sha256=7kUSswXqMS8ajF2QNAafJFSXmfgmAACPwVeqgzDTQqY,102349
+googleapiclient/discovery_cache/documents/gamesConfiguration.v1configuration.json,sha256=CavvLLS58hm3p1cUvCznVE4CqBqUjR6qED8wQObr-Jg,19280
+googleapiclient/discovery_cache/documents/gamesManagement.v1management.json,sha256=EZFK6Rxlm2Hy0hv2F3sBto6UMvjJsykQ_fcmUYXq1LQ,23171
+googleapiclient/discovery_cache/documents/gameservices.v1.json,sha256=E5MFFlyECvsMxSIdo45glqQhAagCDHzeRSo13RPcJ-o,54733
+googleapiclient/discovery_cache/documents/gameservices.v1beta.json,sha256=amIruWItU7wwP_wTWMXY_g2eoY-2FW24EWyPxwQtMvs,54813
+googleapiclient/discovery_cache/documents/genomics.v1.json,sha256=r75lm6eDRH0cxivOOnIQnsm-KkrMY0C8Kp1H6WirqHY,44128
+googleapiclient/discovery_cache/documents/genomics.v1alpha2.json,sha256=OBijBJvThGSucv3G0IILtC8RNGFmdxYrZeLTDFMncsM,66239
+googleapiclient/discovery_cache/documents/genomics.v2alpha1.json,sha256=80yCmc2cqlgSJfPYAxqPMCKFxDWRksFMZzsEkgcsQmI,63816
+googleapiclient/discovery_cache/documents/gkebackup.v1.json,sha256=MUL2SfBUaWb4CRPMguMhrth8JFhbnzX5R-Az2wJnm5w,192292
+googleapiclient/discovery_cache/documents/gkehub.v1.json,sha256=D2En603MRVpATgTooiXM6f1bBd4z14anRRZGEcIq9Ms,233669
+googleapiclient/discovery_cache/documents/gkehub.v1alpha.json,sha256=pHQ77OzpQDSHw81M3zvvBeFOOnCZF0d7xd7v7kN41TY,266728
+googleapiclient/discovery_cache/documents/gkehub.v1alpha2.json,sha256=jIsXo_cDmHYf0RJNlhYTrM1ELjde46sbGHhrfbOGDc4,65373
+googleapiclient/discovery_cache/documents/gkehub.v1beta.json,sha256=vsMOQm1ty4FE4eU3Zrv77pNuynSB8mLijvwlDFSZibc,237340
+googleapiclient/discovery_cache/documents/gkehub.v1beta1.json,sha256=bNG1Rs3WjmPfMoTikm_LMpcdfOYf06L2wRBG2n91KwI,71441
+googleapiclient/discovery_cache/documents/gkehub.v2.json,sha256=8zqSwa1WY-MGzHnaZMU32B0UyWoQRiFGrSTYULuhiWA,110186
+googleapiclient/discovery_cache/documents/gkehub.v2alpha.json,sha256=0-IFQ2N4mDj0se9j-AVqsjNq5oI3x9R_QL2NtzMTzJM,110296
+googleapiclient/discovery_cache/documents/gkehub.v2beta.json,sha256=IByvAcZhYb05-5R4PHIop9Fl5zZZ3nhe5mLg5hgrDMc,110274
+googleapiclient/discovery_cache/documents/gkeonprem.v1.json,sha256=P-CtgUh1Og6JaL6XMtFPbjfUeLJExkKff8P6mgWXjwE,253321
+googleapiclient/discovery_cache/documents/gmail.v1.json,sha256=aJZIcpn8h2vAchkBPOUBnLPXViytsfMnmxkBl40DhPw,138973
+googleapiclient/discovery_cache/documents/gmailpostmastertools.v1.json,sha256=hn1pbcIEUbxWLI43jDndfvBw67dJ2MrnPi5cR93SBNQ,19156
+googleapiclient/discovery_cache/documents/gmailpostmastertools.v1beta1.json,sha256=fDU0TzGeaILZGZMr20TN2heEXDYK-Akmz5cIT8hIicE,19543
+googleapiclient/discovery_cache/documents/groupsmigration.v1.json,sha256=D1av9Pn3hJa_u2CCR0QiAOJzO4dnWVlxKPtcNpZzEa0,3947
+googleapiclient/discovery_cache/documents/groupssettings.v1.json,sha256=PwxhV_pC71kBNg0BHpRw9Ten-Qbst58PfAXVY6Ua5j0,24702
+googleapiclient/discovery_cache/documents/healthcare.v1.json,sha256=KvXvhRE2qMg4nFyxIkCd4mv8JDePNUDZaG3IwkSWWFA,443618
+googleapiclient/discovery_cache/documents/healthcare.v1beta1.json,sha256=CWmzAmfDTmVbDrIxaC8p8cWxaxKFxfrRLFzrUM2Li24,501240
+googleapiclient/discovery_cache/documents/homegraph.v1.json,sha256=Cwu2HP23JFGVwoWYZvUUpVse8p6cknBNaDt8lz2FMa8,19598
+googleapiclient/discovery_cache/documents/iam.v1.json,sha256=mZE2bOki9g3dT4YpaHw_jYzrTeq28g-Dya_Jq71FJ50,279358
+googleapiclient/discovery_cache/documents/iam.v2.json,sha256=-PoSx-TxbrU8aYuDvtXphQeeKPYs6AV7aeuGUguEt3k,36073
+googleapiclient/discovery_cache/documents/iam.v2beta.json,sha256=b-lfD2P1OmmzpJVGCY23ZTBpsFs1bLBbn80HKbKP_LE,36197
+googleapiclient/discovery_cache/documents/iamcredentials.v1.json,sha256=vCHOpehUS4RsRn7dP0AaWNkBcNh0kHZEqgiy-ftgtww,19739
+googleapiclient/discovery_cache/documents/iap.v1.json,sha256=2EVgmOPXIAilBgxhESRdRPVfebytDD32E8qXHLfhWOM,60719
+googleapiclient/discovery_cache/documents/iap.v1beta1.json,sha256=E-FmRVtEg5CcmV2MtJcrhp_5yYwbUnm1y0sYagRdwUQ,20190
+googleapiclient/discovery_cache/documents/ideahub.v1alpha.json,sha256=PfWK6J_Vqz1f_-mYWGBlCxLWSc8iwHrn9QRu0fl3GBY,21042
+googleapiclient/discovery_cache/documents/ideahub.v1beta.json,sha256=9N4Jk-jHWcWC-Cd5Hb_ARxh7nB6h2HVqrDNPRtei-GY,18785
+googleapiclient/discovery_cache/documents/identitytoolkit.v1.json,sha256=QchNLhHkm8ODfNrFmpHesc2I7l64CXJ96w6IbI9_mNo,143803
+googleapiclient/discovery_cache/documents/identitytoolkit.v2.json,sha256=5gGGHt5hfjUTobVCK_XKlrQTfu-U4sLkO7ggUWGeW5Q,136457
+googleapiclient/discovery_cache/documents/identitytoolkit.v3.json,sha256=jg5fCSI6F9Ubd6pdyjUdL3KZboo1DwLrwX_fo1SQfIY,54662
+googleapiclient/discovery_cache/documents/ids.v1.json,sha256=Q2QF6Xb_8qM769F5dVZqncRpuQ0CkvrRN177T5Kbf54,25967
+googleapiclient/discovery_cache/documents/index.json,sha256=aToo8a5LH-shdyLDo4-_QRwB6s1vFYEsF2w-gmO3-eg,213200
+googleapiclient/discovery_cache/documents/indexing.v3.json,sha256=VniFOPVeV6ho_SPcRiHzZD1WuhDlrmib49WzGG6EUoU,5776
+googleapiclient/discovery_cache/documents/integrations.v1.json,sha256=q-1XvJ_0G-aLE5GTogIoqbAQMXFATVj3qW1yLX7LKCw,471358
+googleapiclient/discovery_cache/documents/integrations.v1alpha.json,sha256=-bp1QUgLeateldClVafXg6Z8lbasIk1B9x0Vc5UwSKk,376245
+googleapiclient/discovery_cache/documents/jobs.v2.json,sha256=L-aDKIJ86eq-tEmOrHZfKD2MmQkCP_uTwCCTQHSJcoQ,227088
+googleapiclient/discovery_cache/documents/jobs.v3.json,sha256=OCDFs1rw8-vh_vIchswkmKEqRosIhpaNOumknFxVE3s,121113
+googleapiclient/discovery_cache/documents/jobs.v3p1beta1.json,sha256=ycJYA6hdxv4Asou1NfqBkeKZbHFMdQbP4kqG5USORww,135102
+googleapiclient/discovery_cache/documents/jobs.v4.json,sha256=zJT9KRD5R56uuhwxPmUrV7f4VI5w8rLNxR7f4rBeikc,135236
+googleapiclient/discovery_cache/documents/keep.v1.json,sha256=4L9rSisFKCYF9sazu5Goh0j1_L77pYhAfwEgTq7ptAQ,16998
+googleapiclient/discovery_cache/documents/kgsearch.v1.json,sha256=ZwTdiUrvYERjzOanj4JdPhI2Z9Y_A43vI79EmFRr6io,4886
+googleapiclient/discovery_cache/documents/kmsinventory.v1.json,sha256=cVRB1ZAdKm76LQpL1NX0O0lAMf-nzAUy2ao7YBcnzC4,38700
+googleapiclient/discovery_cache/documents/language.v1.json,sha256=mE0uY0frqt4Wz_nBOocEv9mRhGEfW_4CTaC4sh7CWHM,151542
+googleapiclient/discovery_cache/documents/language.v1beta1.json,sha256=-Nwsr0Ls6nKWMZSQ3ZzkW1Zdvu2gEqb6yt4r65Z1xOU,38558
+googleapiclient/discovery_cache/documents/language.v1beta2.json,sha256=qLKTCEpVWCLgP8uT8FagfKPpDwir-PD0H4prgZWAXck,152340
+googleapiclient/discovery_cache/documents/language.v2.json,sha256=mbdj_eAp61zYoNMoP0ZSLNEEN_Qov2nZgaL6fbNJs5g,138008
+googleapiclient/discovery_cache/documents/libraryagent.v1.json,sha256=DoFPi9frga11E11_DL9e8wQ6cZQfLrr1TqUJq3oNNBc,9898
+googleapiclient/discovery_cache/documents/licensing.v1.json,sha256=CB4ka9YxsG5xl6ujOQN8JusXErFtL73mqgHHw0u5m74,15827
+googleapiclient/discovery_cache/documents/lifesciences.v2beta.json,sha256=ci2-lfSmer-UPyp34RLAJpE9nZwbQJOlhVVtLsMkwKU,52568
+googleapiclient/discovery_cache/documents/localservices.v1.json,sha256=x6aX43jOnqyA7U-kk3WhT81I9IiVEzWXvlibZ8BjARw,18779
+googleapiclient/discovery_cache/documents/logging.v2.json,sha256=tD5qYm74rHJDpkujY9j3-chKBoh5r-798rTUx5mpMR0,499074
+googleapiclient/discovery_cache/documents/looker.v1.json,sha256=sOpx_GR4FA8LklMo-FmFRR7CuY2ETckSBSCemvycHtc,45790
+googleapiclient/discovery_cache/documents/managedidentities.v1.json,sha256=Q2n75aQO9t_LsmTZqdtYv39CGHdaOtjKCNp7tvYnq-w,118816
+googleapiclient/discovery_cache/documents/managedidentities.v1alpha1.json,sha256=fAkJW-6Y6LsqyxtxgOHtJ0-aIssxdRIfZuKcCFEOOHM,118842
+googleapiclient/discovery_cache/documents/managedidentities.v1beta1.json,sha256=HxowKK3QiyXdNkLuF7-qlnQZ2Xc-QFA_n4KQbyQyOdg,119795
+googleapiclient/discovery_cache/documents/managedkafka.v1.json,sha256=xbaIqLVluwIARsxQzVysUkIh2cZoRZBLiI33wLwBrgk,151082
+googleapiclient/discovery_cache/documents/manufacturers.v1.json,sha256=U88bUQKj4jTRJg_6sfwe0z8J_-Il9R9TO5nAIxASzLo,41060
+googleapiclient/discovery_cache/documents/marketingplatformadmin.v1alpha.json,sha256=qTk0pcCjd6-CAIXuWIlogDucnUW-AU8Rde-UEsODlk0,12562
+googleapiclient/discovery_cache/documents/meet.v2.json,sha256=Qesrk9wWj88A3wQzujY2bwTZeD18DY_b_KY6D-cn6yc,43604
+googleapiclient/discovery_cache/documents/memcache.v1.json,sha256=PHK31QEOXRYkeSFkyy7yvwoaHUqveTd7Nm9dlRo_WmY,64890
+googleapiclient/discovery_cache/documents/memcache.v1beta2.json,sha256=FK5nlnEOzAiQwYK8Ngc96ZpRT75K-0rizjWYBIGjeNI,66816
+googleapiclient/discovery_cache/documents/merchantapi.accounts_v1beta.json,sha256=G72h5c6f_0L8l2K2yUrpEkw94yfWjwk8nnNURkWZbEY,195698
+googleapiclient/discovery_cache/documents/merchantapi.conversions_v1beta.json,sha256=xRrIlKaHMuyiSgGPzgIKY7yqk8pTcv7rU5PHmsQyYhQ,20633
+googleapiclient/discovery_cache/documents/merchantapi.datasources_v1beta.json,sha256=5dNgOAiGPAlOeG3m74t-QlBTXCXeOcH85NtW09oSlmc,36974
+googleapiclient/discovery_cache/documents/merchantapi.inventories_v1beta.json,sha256=jmeHxKKMzTRiYyjMrOp0GKjCpeTKI2Td4qEhQtbBZeQ,24258
+googleapiclient/discovery_cache/documents/merchantapi.issueresolution_v1beta.json,sha256=cf108YGXR70yF7uXdXiBQHUv7Ms8sw0eQMFZ3S2jUnY,50614
+googleapiclient/discovery_cache/documents/merchantapi.lfp_v1beta.json,sha256=JbhVEPdrrXEV7Mew8fiaDVg5kppVYHlsH4ymvsgbp3Y,28956
+googleapiclient/discovery_cache/documents/merchantapi.notifications_v1beta.json,sha256=TLSLS7V69FLKGdN1E9jhr8ziOI68lhfu3seynuyX_-o,15632
+googleapiclient/discovery_cache/documents/merchantapi.ordertracking_v1beta.json,sha256=tqyHB-yA33Kfc8ZfFKNcMRgL5_fLIeupegI1zyW97w8,18886
+googleapiclient/discovery_cache/documents/merchantapi.products_v1beta.json,sha256=bxtxue8kkn0oedW5MJlwsZy_SvK8dbko75aBDAyI2nw,69612
+googleapiclient/discovery_cache/documents/merchantapi.promotions_v1beta.json,sha256=yNaUHLHlS8It_M43YhDLaUsbj64f9me4sNAQ5pe4ih4,39834
+googleapiclient/discovery_cache/documents/merchantapi.quota_v1beta.json,sha256=vHbfGjuKXASRclsAEyUVL4igvxvPhcUiWiyce6t7HCA,11679
+googleapiclient/discovery_cache/documents/merchantapi.reports_v1beta.json,sha256=eIdbPJx6m59teQ2XwyZ5KwFExIUWUmDKrBqre0P8h7c,58764
+googleapiclient/discovery_cache/documents/merchantapi.reviews_v1beta.json,sha256=xtyOlLUBQpXqLFlWhem_xxkXLW-Sj-bmcTuI5WHnHPA,43073
+googleapiclient/discovery_cache/documents/metastore.v1.json,sha256=YGGRc9Lx0SglZpi5X7EBWBxMFs49tRACipSFAU_RM5k,141601
+googleapiclient/discovery_cache/documents/metastore.v1alpha.json,sha256=2oePEwq1JrH6iw8J1acBKxRI-uf_b5DRR6KO13lhyMY,151717
+googleapiclient/discovery_cache/documents/metastore.v1beta.json,sha256=LTvTF4sC-_FdZuy2TOh_2FEvMTpe4grjNeNkvogFk9w,151611
+googleapiclient/discovery_cache/documents/metastore.v2.json,sha256=QTDp6iCKRTDdBXjTLuuGBliz6jaTq5bBw2jlA5mN1dQ,66531
+googleapiclient/discovery_cache/documents/metastore.v2alpha.json,sha256=DPqtcLgeHhEGbxZWcU6NnFS9SmH5rxGvoi9y_yGq7mc,87673
+googleapiclient/discovery_cache/documents/metastore.v2beta.json,sha256=MrlztbziAhAib5eqcL4O5rUW_eYrcEzk8sICx_IVwZ8,87517
+googleapiclient/discovery_cache/documents/migrationcenter.v1.json,sha256=KbXLa4cfYbi2P1aHswZTk5nEdLk9eiEaxb-Moi2pZZc,208136
+googleapiclient/discovery_cache/documents/migrationcenter.v1alpha1.json,sha256=MpnIDfD2WOasdTxy5D2n3RuGmvpnuk6j5sQSh1ZB6u8,266767
+googleapiclient/discovery_cache/documents/ml.v1.json,sha256=Q-dBFvLCgnV25aG6YILqNCB3wpL6PK7pJ_TX_xXzxJo,175519
+googleapiclient/discovery_cache/documents/monitoring.v1.json,sha256=b9aY7ZM5Z-mmp9k4xzpXvkzL-XlG66DRBHM0XE-xMNw,115975
+googleapiclient/discovery_cache/documents/monitoring.v3.json,sha256=9_8n2nlSJD_Hj0r2qZGnmM0XtNe606qtz9M9Vfbm1Ak,343383
+googleapiclient/discovery_cache/documents/mybusinessaccountmanagement.v1.json,sha256=ue2l9wxhctz1M9pNi4G4fHHUBAzzmu0Sd2_qF7teoG4,31920
+googleapiclient/discovery_cache/documents/mybusinessbusinesscalls.v1.json,sha256=w_OnSvJZU62j-5J8o3Mt3CmA2Rk7_GKu5DuhsIV574Y,16209
+googleapiclient/discovery_cache/documents/mybusinessbusinessinformation.v1.json,sha256=CM9M9o2f_lkWgJ3TIfr-gz5KSZTHe71qtvho2QkYwH0,66404
+googleapiclient/discovery_cache/documents/mybusinesslodging.v1.json,sha256=3XznJiEG44cWQkgSHQrS0u8P7mX6J6Ck9P9hGN1Sf4Q,222770
+googleapiclient/discovery_cache/documents/mybusinessnotifications.v1.json,sha256=iuA9q6GqeWcDfbXU-FrSAkrjOAXOeRBSPUXbSiIVA1I,8029
+googleapiclient/discovery_cache/documents/mybusinessplaceactions.v1.json,sha256=EnWkiYLZggSlFINF0ujYooNwRMh1qPxdVLR2n-Ikhbk,14578
+googleapiclient/discovery_cache/documents/mybusinessqanda.v1.json,sha256=MBjZalhwZNuin_Y54kxl13lctTp5ODRexqgaUK0BCBM,14263
+googleapiclient/discovery_cache/documents/mybusinessverifications.v1.json,sha256=oLyKapAr-eX2mrWdCoKEMB-S1E-RDOUOhCFMRHzRBqo,28795
+googleapiclient/discovery_cache/documents/netapp.v1.json,sha256=yfaG40BEHfESuxSbImRGU1gsLgB1Dwmk7E8IzgKDjuY,132868
+googleapiclient/discovery_cache/documents/netapp.v1beta1.json,sha256=F29xX2sTekuNxNdEqID_TDe683OA23ExHBMLdvSEvig,137152
+googleapiclient/discovery_cache/documents/networkconnectivity.v1.json,sha256=Jn0zgPMdOzyPGetgo1YrLNhQSnpPlGrgINf5DLQ7YdU,233091
+googleapiclient/discovery_cache/documents/networkconnectivity.v1alpha1.json,sha256=BYbqeAQyAjdam-lAz5kv4jGmUU0i6Q3VTZEXYHACzeM,80819
+googleapiclient/discovery_cache/documents/networkmanagement.v1.json,sha256=DVWpxU0JgTanqN6_BTM18UoNt_B3J8l0ytQ0a7L5J8I,178347
+googleapiclient/discovery_cache/documents/networkmanagement.v1beta1.json,sha256=ecRmDco7e97CjtLLWCsdSHad1vNyDzgYdXtYF17vjVA,162109
+googleapiclient/discovery_cache/documents/networksecurity.v1.json,sha256=bj2BQ1a-Qk9vY7aBuF5UbiRQy8Y-ySEIpfPOKQIPuoY,324097
+googleapiclient/discovery_cache/documents/networksecurity.v1beta1.json,sha256=HfvpDDKmhbVoSbrUF_1LN9MZFgVCOOMw1GTnkBdRG_s,350813
+googleapiclient/discovery_cache/documents/networkservices.v1.json,sha256=-69HVlnNTbN-zDcTMZEmBILqKx5MKVuSh9totYtQvhU,240098
+googleapiclient/discovery_cache/documents/networkservices.v1beta1.json,sha256=1y769olyA7ubWtdoEoVXay69bHe0O-hg_L5KWP8xhMk,226444
+googleapiclient/discovery_cache/documents/notebooks.v1.json,sha256=ii6adyZhX9r5ekNsPuU4bd8TnpUpnvTZBZEiGUPYqDA,159045
+googleapiclient/discovery_cache/documents/notebooks.v2.json,sha256=1DP6GIaSRr-riers7Mhjt4yBKZ-57OHWyJaPvcpxVT4,81344
+googleapiclient/discovery_cache/documents/oauth2.v2.json,sha256=qbqQUKMu6g1IrIHIAfYwTAZZgIDf8j69Lr6i-rzbzLs,6601
+googleapiclient/discovery_cache/documents/observability.v1.json,sha256=3v1n8q4xGfvYHJiGrKUN4-8n4887eHXDzISOmfLSsRw,18284
+googleapiclient/discovery_cache/documents/ondemandscanning.v1.json,sha256=RlWelWdmPc5dsKJHTt8Igav1IMtKEy7BD4nCNFE9zh0,94143
+googleapiclient/discovery_cache/documents/ondemandscanning.v1beta1.json,sha256=PloJDEtVfLlxDibygVRLP_4LTNSscKiN5yl6FNlX6aY,93994
+googleapiclient/discovery_cache/documents/oracledatabase.v1.json,sha256=2N26Jq807X-64aiaJo1cgnBYruaucNV0fv5H99bzKSk,137312
+googleapiclient/discovery_cache/documents/orgpolicy.v2.json,sha256=kP7gol-Qbrp6o507uYp3UiaEFkCkcuNyibyDT4zn-28,55610
+googleapiclient/discovery_cache/documents/osconfig.v1.json,sha256=9C3Ux3zHWSR4Pd8KlzqltfDqnhxYMC6thFl5nMmhX54,142346
+googleapiclient/discovery_cache/documents/osconfig.v1alpha.json,sha256=MwoIfhyZYheo-lHaxkhChUSAFNJEyXyUv5ndl0tJdrM,106897
+googleapiclient/discovery_cache/documents/osconfig.v1beta.json,sha256=0K9K0Spr4Rt83E58qmvMq5Ht28A6uibpmBvLTS_0KQg,87545
+googleapiclient/discovery_cache/documents/osconfig.v2.json,sha256=qv7ZxoHKtUsbSrnmufwBB1hfHHDQlyaPE-akOKwYu54,88480
+googleapiclient/discovery_cache/documents/osconfig.v2beta.json,sha256=VQxFkLsqgf1UUB6K2AZWFCwGGZHA2cPS9tovx5UNzZk,88860
+googleapiclient/discovery_cache/documents/oslogin.v1.json,sha256=ilwmbOAL-S-KfXTcy4mUKI-dSH2ZV9tP61fSVl5hxzs,13149
+googleapiclient/discovery_cache/documents/oslogin.v1alpha.json,sha256=a43X8cDkL6qZA-knmrYL1Llgs1U-y_OYcoNI4FZNruw,21955
+googleapiclient/discovery_cache/documents/oslogin.v1beta.json,sha256=24Sfz5r1NM--HcaYN8Y7Li_WxYXjQN4DLNsGeqmm10A,21010
+googleapiclient/discovery_cache/documents/pagespeedonline.v5.json,sha256=HLFi19o2CGZYT-nR4oK9F-9tXBWrREeBDm9f3PKKcJY,28503
+googleapiclient/discovery_cache/documents/parallelstore.v1.json,sha256=aZs1oKvPCoOHr0rNNrRyst4-qxpf6ufFfWGL5hh29C4,36618
+googleapiclient/discovery_cache/documents/parallelstore.v1beta.json,sha256=bm2wwH5FIdeCNIJKi2ksy_7t4gVgj6YVW9ElrWl2tPw,36513
+googleapiclient/discovery_cache/documents/parametermanager.v1.json,sha256=YvkkIp7kihLiGa7b5gwaTksXMcSPByCsn9fYecqJW3k,32837
+googleapiclient/discovery_cache/documents/paymentsresellersubscription.v1.json,sha256=_wtIIwkxBmekME3fR7k_8cwpJanYgeW1ZOoVPaMySxw,68642
+googleapiclient/discovery_cache/documents/people.v1.json,sha256=9-aQd4MBUAhJkl5wpEfTccS2ipglZT8uf978tHdcKAU,112570
+googleapiclient/discovery_cache/documents/places.v1.json,sha256=2_PMLetGsAP1FSrC-KLkKoytyyOHmaRLIUBjqWpNRhA,110942
+googleapiclient/discovery_cache/documents/playablelocations.v3.json,sha256=wbkjdTm2IPCudHBKwwIOaAWwsRxfcinsOiKPR_C5G4M,25906
+googleapiclient/discovery_cache/documents/playcustomapp.v1.json,sha256=pG8LwuC9yO1R9lSyNXVskFTrZaBm_MQCl3JPegK2yck,5201
+googleapiclient/discovery_cache/documents/playdeveloperreporting.v1alpha1.json,sha256=ZD3dFjz_B-G6KJ9QLGJiGnmexwKfYQCMmA5cTt-d7JE,148544
+googleapiclient/discovery_cache/documents/playdeveloperreporting.v1beta1.json,sha256=1VGZvgncXNlUAwX4wS_b-dymag1-CmWEE_R8f9YRJ0o,148331
+googleapiclient/discovery_cache/documents/playgrouping.v1alpha1.json,sha256=IiCHjssDE3DyDE09U8j9GumZpi2t6SZfFiy_myuQm-s,6307
+googleapiclient/discovery_cache/documents/playintegrity.v1.json,sha256=2UG5AC_OwwBSTkNsgOlIaDZfeXa0LnLPQIwFVituiGE,22302
+googleapiclient/discovery_cache/documents/policyanalyzer.v1.json,sha256=UbzYQTXuhZcV_f8klEA9ps8syc4RTJ_30TpRYiLa5AE,11965
+googleapiclient/discovery_cache/documents/policyanalyzer.v1beta1.json,sha256=uc6Tw0al4RaKcVAwNyNoA2nEUNP7uzUdPxnZxnz6isQ,10922
+googleapiclient/discovery_cache/documents/policysimulator.v1.json,sha256=7JtCCRRcrKy4xLOLSk_ikWYQNNVcJn6hKloKfP3mFls,103353
+googleapiclient/discovery_cache/documents/policysimulator.v1alpha.json,sha256=wu4Ec5TyV5UDqmsTVJc8R7sVkIljCmgeWs2GHDJxOFY,61018
+googleapiclient/discovery_cache/documents/policysimulator.v1beta.json,sha256=ORhEexshbXzrnczyG3tvAfYioH5iuNGHwQ5Sm4VPI60,107746
+googleapiclient/discovery_cache/documents/policysimulator.v1beta1.json,sha256=Q1ufGYQSG04J4ufoZ0JH4hgwdeN1QeW1dhREOv-b0Pw,54107
+googleapiclient/discovery_cache/documents/policytroubleshooter.v1.json,sha256=3WWpBNOwDE2E_9qN56IAkB_QoNxbKa656bHHCbmGbB8,31718
+googleapiclient/discovery_cache/documents/policytroubleshooter.v1beta.json,sha256=k5NV64Ld0v4t3sr3ajAP0LfK9-k6OgfaR_AyZxJPQko,30156
+googleapiclient/discovery_cache/documents/pollen.v1.json,sha256=5yHEc8-STvhGa8G0J929bXjT8-YR4aUBN-U0yf4e6NA,21526
+googleapiclient/discovery_cache/documents/poly.v1.json,sha256=MI1zdlmWLLalpCwlx22n33nkszug6pksZb9_1x96K90,27091
+googleapiclient/discovery_cache/documents/privateca.v1.json,sha256=ggTWGfaz1fyeZElh0zB6UbPruvxRA3pb7nQ5oJasJIg,152263
+googleapiclient/discovery_cache/documents/privateca.v1beta1.json,sha256=-IYVzz8Z5iIw2AuWRzhg8A4Sq8H-jn6I9mNTnTiKvG0,44228
+googleapiclient/discovery_cache/documents/prod_tt_sasportal.v1alpha1.json,sha256=96j345PnT94kQzeYPHlixWSiQk6hQ_AGYkSe7190DEs,100005
+googleapiclient/discovery_cache/documents/publicca.v1.json,sha256=msybmT2yjAQKtsnvMrA37fvWwf6i92SS9zU5RiUMne0,4849
+googleapiclient/discovery_cache/documents/publicca.v1alpha1.json,sha256=lZTujGOmJFdOVOrYFlqse4jJOM85qOAYcV_4WhALNcU,4873
+googleapiclient/discovery_cache/documents/publicca.v1beta1.json,sha256=TamTpQDX3VRyn6vt6k89HyKLcMSf9UaI8pebzVqpWSw,4869
+googleapiclient/discovery_cache/documents/pubsub.v1.json,sha256=0sJBrNZk5ELSAAt90GE0UzFT1B17u5AjD8ao23IcYrQ,131361
+googleapiclient/discovery_cache/documents/pubsub.v1beta1a.json,sha256=BANlfJnV40qmdfOkDwirxdhSc11PDRjaeV7lh2QsBuQ,26028
+googleapiclient/discovery_cache/documents/pubsub.v1beta2.json,sha256=3Y211hPblsfNRtfZ1J1PhPJy3sn5y_knPVAaxndVWPU,51138
+googleapiclient/discovery_cache/documents/pubsublite.v1.json,sha256=WMbpgrapU3kLiHERlUxjwYWKRYbm5FRYPQd4j514NI4,53052
+googleapiclient/discovery_cache/documents/rapidmigrationassessment.v1.json,sha256=85IxZPgGgTo9OAsfzdOccKm5eeMTJzXdZo_PbglIOX0,32706
+googleapiclient/discovery_cache/documents/readerrevenuesubscriptionlinking.v1.json,sha256=jg9GE5YxOZEgHpJU99qBqwpDmYfTkb9uWX47p1LR0Qs,9170
+googleapiclient/discovery_cache/documents/realtimebidding.v1.json,sha256=H7rAgUK0WvN0jyw8tyfA7Pcv1M8UodsQAVIW68e01yg,118786
+googleapiclient/discovery_cache/documents/realtimebidding.v1alpha.json,sha256=0aZYwk8L6hmk_xVK_rr4BwT4FPEn56oiZWKVqin92rs,18365
+googleapiclient/discovery_cache/documents/recaptchaenterprise.v1.json,sha256=GYnsl3ylEb93iXJjK2SDrGe99tfbs5FQVW5Z0pam3rk,99156
+googleapiclient/discovery_cache/documents/recommendationengine.v1beta1.json,sha256=k0aW98mk8r7nsXNx8-yE_x0AIfu9uBMvo2XE14KkfeI,87898
+googleapiclient/discovery_cache/documents/recommender.v1.json,sha256=opxLJE3suZOJxlGLWEBWJCNdYVb2WAXiuuo5L42bHyE,98951
+googleapiclient/discovery_cache/documents/recommender.v1beta1.json,sha256=ZhhEVtBinUdLScN74LaAkBC84JCD-4DuJ-1S01qnMAc,111437
+googleapiclient/discovery_cache/documents/redis.v1.json,sha256=9goKFQeey1AglVEozjjq5BG57oqDhtqkI-Egd4NYYxM,169793
+googleapiclient/discovery_cache/documents/redis.v1beta1.json,sha256=2qQZDOA4rHigrXkfTe4EIGHOxbL3U-HHMfalebMfifk,170663
+googleapiclient/discovery_cache/documents/remotebuildexecution.v1.json,sha256=7GFLt5IiI_-OYe68YsVR99EYWAZbRDdQ7MBSu2yU8n4,117609
+googleapiclient/discovery_cache/documents/remotebuildexecution.v1alpha.json,sha256=hSDoD01FhwXYIVbrOwSe7cLI19DoN1AwZm4ylBQzTgU,124864
+googleapiclient/discovery_cache/documents/remotebuildexecution.v2.json,sha256=EII61EfJ8sqYPcx-Ilk5j-XosxGTIfrN48mLKLkGfnQ,148991
+googleapiclient/discovery_cache/documents/reseller.v1.json,sha256=Yj6bAjZzjoMxi574h73yo407FyuUUr5Xo7G_JlGkxx8,49119
+googleapiclient/discovery_cache/documents/resourcesettings.v1.json,sha256=PBtggh9NeN9JMcNY29fETTCUnggc6vP3cjwFXEEp_jo,22442
+googleapiclient/discovery_cache/documents/retail.v2.json,sha256=hZK5M747JSAhVNGyMhgZgkq5NxCQs27DNZhQrKchhe0,380291
+googleapiclient/discovery_cache/documents/retail.v2alpha.json,sha256=mCXKD5T-AvQ_SA23YvI_6UXBGUo6x56J06T81dQmO_w,444859
+googleapiclient/discovery_cache/documents/retail.v2beta.json,sha256=u6fl646DS1lGTM_1zlQhPYvnMr6vzcYJjxpLU2vJNSk,399624
+googleapiclient/discovery_cache/documents/run.v1.json,sha256=f3eq9GxB7OMZwRvLFyRmcVUbaLYwo-hONTbaSRMfaDU,258620
+googleapiclient/discovery_cache/documents/run.v1alpha1.json,sha256=Z0H_iXudGt7JDmcS4XZx09xCSBXPBv9MCktQqrAiayA,69965
+googleapiclient/discovery_cache/documents/run.v1beta1.json,sha256=huF9CDeN1HdW5tai_neIoAPtXOqg1t_KxstLag14WiE,40411
+googleapiclient/discovery_cache/documents/run.v2.json,sha256=PDTT9_ZAlI2FOI2L8k6fJPiFveI86Io1xzNqwYPhkVE,265791
+googleapiclient/discovery_cache/documents/runtimeconfig.v1.json,sha256=a9eko6S6zJLWmkOlnqRstqEfiRhdFG2KKWgrFmk2NCY,10289
+googleapiclient/discovery_cache/documents/runtimeconfig.v1beta1.json,sha256=U-Eglt6hR7I2J8zmVDlWhGK3R2gs1Iy4SRZ25Z9TmD8,55381
+googleapiclient/discovery_cache/documents/saasservicemgmt.v1beta1.json,sha256=GfTqN9utVvWU5IPOFQjhsBJxE8JBiRERC04Oav0rdBw,123001
+googleapiclient/discovery_cache/documents/safebrowsing.v4.json,sha256=swfVWEKVKLtGSoSNbRdA0LdXy48qohgK8Pnwf6yiIjE,38346
+googleapiclient/discovery_cache/documents/safebrowsing.v5.json,sha256=IaeiQ_bXsQZjBAvCXNAAjnA9tSlhwjN8V_q5rqMyS7s,28399
+googleapiclient/discovery_cache/documents/sasportal.v1alpha1.json,sha256=MYsQcG35bK_r5XtPy_fGHq9fhWGRDCbfyftXSDP9K8c,99260
+googleapiclient/discovery_cache/documents/script.v1.json,sha256=dz5W66zEcRwVrJr9waevmjrhwWEaAGQ3zXxV6OGj-Q4,48992
+googleapiclient/discovery_cache/documents/searchads360.v0.json,sha256=bFFdaWU_BFZ-XHtb3bUz8V8hZnt8DXauSHtaIgvnEEQ,333437
+googleapiclient/discovery_cache/documents/searchconsole.v1.json,sha256=GgtL29Gau3Ebbha_9D767GBUDxKXOuHlyZy9GrmDpGU,42567
+googleapiclient/discovery_cache/documents/secretmanager.v1.json,sha256=8TnZZZ0OtLOwksc4WvOL3VgUZ6K38KPLaWHmnUVni54,77055
+googleapiclient/discovery_cache/documents/secretmanager.v1beta1.json,sha256=Njx7uCWJekNpLMgVkr_8_8U8hZOSHDP_btLpVNcxPtQ,48876
+googleapiclient/discovery_cache/documents/secretmanager.v1beta2.json,sha256=it2nXNdg1fO5YyUu-3l58iMA1mGEARPkcyi9ZaKzMjg,77381
+googleapiclient/discovery_cache/documents/securesourcemanager.v1.json,sha256=FxbKIMjnVr0UZ2iqyJNwBw7_UxVLJO95VDd0qYOkWK8,129631
+googleapiclient/discovery_cache/documents/securitycenter.v1.json,sha256=fCXah79UzIEQnIsmKSpgapJ3B3TwWbRaZrVxODEHtXk,615236
+googleapiclient/discovery_cache/documents/securitycenter.v1beta1.json,sha256=fiLhD3LxcFfd7q7oglvoTeTPATge6mi34Wz2ruIl-_o,373364
+googleapiclient/discovery_cache/documents/securitycenter.v1beta2.json,sha256=ym6R8mf_9Cj27AIz6p2NeTcQ9UxGvHeufK0kKCwbjbM,396183
+googleapiclient/discovery_cache/documents/securityposture.v1.json,sha256=m4ST-HK_fSFEwNUC3qvti1qGOUqMacBqjHRwAMXjqVY,71415
+googleapiclient/discovery_cache/documents/serviceconsumermanagement.v1.json,sha256=EirSvUtw9-jSGNtU13utwZROGfSj8yiWyruOFXzcS1w,165579
+googleapiclient/discovery_cache/documents/serviceconsumermanagement.v1beta1.json,sha256=cfsfhWp-jql2QSAaM_-xO7RYhyGtoK0aasHGQ1Nk7kk,173061
+googleapiclient/discovery_cache/documents/servicecontrol.v1.json,sha256=l4vkhVKDwRHzx9mQcaNPYfEfgJTbkYE7JjMzBTLPWrk,98463
+googleapiclient/discovery_cache/documents/servicecontrol.v2.json,sha256=Yz7W2H74UR3n5AMQ672d8kyghGy-sA31Gpb_GdjEf-I,54820
+googleapiclient/discovery_cache/documents/servicedirectory.v1.json,sha256=xPTK7-3JD1nhXCXo8EOJ_9HDBM4iqlmJGlWNM3QGIS4,54438
+googleapiclient/discovery_cache/documents/servicedirectory.v1beta1.json,sha256=G3zhHnCaljMMYa9y4m4yhZ-RDP11aw6joKsg4YA-uqM,58940
+googleapiclient/discovery_cache/documents/servicemanagement.v1.json,sha256=82d_8dLDgapSO9BAFSMSB-XhJdy_EhZAoHDyxbyOZyI,185858
+googleapiclient/discovery_cache/documents/servicenetworking.v1.json,sha256=U8Cra1-VJrHmUbtbWXA4seTNjAVXH1ijKPAgFHyTFfc,203179
+googleapiclient/discovery_cache/documents/servicenetworking.v1beta.json,sha256=knAbvJZp7K1MDzm0VyLSjZKnAH_qqkGoGtrq0v03vy4,155728
+googleapiclient/discovery_cache/documents/serviceusage.v1.json,sha256=qOCPLIHFbUa2ezqnwpLtKxX36rfuSaHoLbMwnHotNAc,171674
+googleapiclient/discovery_cache/documents/serviceusage.v1beta1.json,sha256=ItPLD6WQyPnSZnnaMaEVAw5wFPy9v4AkOL1p_79nDbo,209272
+googleapiclient/discovery_cache/documents/sheets.v4.json,sha256=K46s2XtznVSxYshbAG61X-mXtRb3nZdeBr4zeE6yO0E,300187
+googleapiclient/discovery_cache/documents/siteVerification.v1.json,sha256=xvq_xsL575_6zsUckW9eo-jWWdxW6Ng13g8ohB2uGLA,8419
+googleapiclient/discovery_cache/documents/slides.v1.json,sha256=QUf-dtFq3TVqEyUT0Y8_ZagQmmF-BC7hB0UPKlsxBDA,185359
+googleapiclient/discovery_cache/documents/smartdevicemanagement.v1.json,sha256=VRNJs4ILczG5VbEi7-_jw3YjEkzGG78gRfeTwHHkUvM,12914
+googleapiclient/discovery_cache/documents/solar.v1.json,sha256=R0L-_8Rf3317nZZfvOMo9aKCrppE1OgIV3ZlLFlO3Xg,38899
+googleapiclient/discovery_cache/documents/sourcerepo.v1.json,sha256=PpTvPOAbVUYvw7py9gMn6bT_zn01aR939Fj9WvoSoTM,38672
+googleapiclient/discovery_cache/documents/spanner.v1.json,sha256=6_xMbgbtCJ0XRMnzb44qc6pkfaxH4W5mVOq7S97h8dI,370118
+googleapiclient/discovery_cache/documents/speech.v1.json,sha256=GGEKtQoIBpaSPC5aUoJ2ITnTKiz6pdQDynndl3t5xvQ,64012
+googleapiclient/discovery_cache/documents/speech.v1p1beta1.json,sha256=DRXTB7k62NiHvh0Ba2x1DZKAot2Hs6svqTAuKtOhVEU,65166
+googleapiclient/discovery_cache/documents/speech.v2beta1.json,sha256=uKUcKcn6zNl_egbyhzSYNTlr_o2tpGelQ0WctfRAU54,18493
+googleapiclient/discovery_cache/documents/sqladmin.v1.json,sha256=JsUudNDOmZCfCiExL77a2VSflfTeRTva3Hmc3jyhUyg,239088
+googleapiclient/discovery_cache/documents/sqladmin.v1beta4.json,sha256=8iu__iCsKDKFXnhLSSlhiPoVfpidD5NZsi1bZqp8GYA,240508
+googleapiclient/discovery_cache/documents/storage.v1.json,sha256=Kgqh0Hj9mfRSRTmkPfGtq8Ke5hWVSWNU4IUp13qK1VA,201255
+googleapiclient/discovery_cache/documents/storagebatchoperations.v1.json,sha256=juPc8bWuyWDug-Ta6QJSl8BQ67qr9sCq0E_aeKbX1uw,38891
+googleapiclient/discovery_cache/documents/storagetransfer.v1.json,sha256=nlECn8prj7FS-pK6zcBzt_SJWQp2rWvPL_zT_Mj7TV8,85407
+googleapiclient/discovery_cache/documents/streetviewpublish.v1.json,sha256=6yewpIR1whuQeotQcU0Z5FM9nNBtK4KxCT2nE6ihTz0,48408
+googleapiclient/discovery_cache/documents/sts.v1.json,sha256=JZ0k92FpUt6bBNTcRBit5cIKGi7pUi_EBlBydlFWVPk,33314
+googleapiclient/discovery_cache/documents/sts.v1beta.json,sha256=GKQBwAcg1z50o2nLoboaDf6T2YwJZPeYTlsbiv-qL-I,31941
+googleapiclient/discovery_cache/documents/tagmanager.v1.json,sha256=DwiLhm0oFCAxipKlqoeRcwRv3yNhi-exJXbl75AEaGM,75026
+googleapiclient/discovery_cache/documents/tagmanager.v2.json,sha256=oWixDj6ojiIGiRtH3ZZp0vL2NqhKtzo26smxTkarPUA,158728
+googleapiclient/discovery_cache/documents/tasks.v1.json,sha256=aMN5ZbCVhnMJx6cI_dvd-JNja954CwOlNfOH1wPE9vE,23620
+googleapiclient/discovery_cache/documents/testing.v1.json,sha256=i0Vm6YtDvgf-y8aYZIN907LrXTc_1yb9lNKHm35KUS4,98429
+googleapiclient/discovery_cache/documents/texttospeech.v1.json,sha256=_0qjMlD4MuwxVM2z0gIhW4Kk1ZYXps0aR04bGHWr114,29328
+googleapiclient/discovery_cache/documents/texttospeech.v1beta1.json,sha256=dTMWfXmjhcYjrbl2I_PjpJIHbEPcnSbBN85At-_R5TY,28167
+googleapiclient/discovery_cache/documents/toolresults.v1beta3.json,sha256=txzCTQaEl_0JhlHqxcsrKwyhkSlutnqmwzqNHm6bMWc,129592
+googleapiclient/discovery_cache/documents/tpu.v1.json,sha256=d4MxwMXoOQbDTE0VJ7VXWDL5tWp9j8ihVIf9fe_ff4I,32402
+googleapiclient/discovery_cache/documents/tpu.v1alpha1.json,sha256=E_1HljMKvrOK6uEENR-WSIBUnYOFtQZOipzYOUp9E5w,32817
+googleapiclient/discovery_cache/documents/tpu.v2.json,sha256=egFPh5wxG9-Fiu7QHoKuDlx9C7a7Xk0iC67lSeR5hTo,57594
+googleapiclient/discovery_cache/documents/tpu.v2alpha1.json,sha256=nUR5vEyf_WCuqxU1Prl3nihiBUXdEJU6zGx_7k0jg8g,69295
+googleapiclient/discovery_cache/documents/trafficdirector.v2.json,sha256=Mwr5Rl2tgkRXEwvkVxuYeYBMR1TlkznDoMZvp4TobFQ,32631
+googleapiclient/discovery_cache/documents/trafficdirector.v3.json,sha256=73LjJPXuT-soYvNwOdUwlzH-fF039bD8nvNWb9HiB_o,52057
+googleapiclient/discovery_cache/documents/transcoder.v1.json,sha256=j2HFv32fNStdixYOFVbKCz9JSsRa4D2piAmp7Tm8agI,70059
+googleapiclient/discovery_cache/documents/transcoder.v1beta1.json,sha256=nj-9u_qqRm_1H3tlaTpWZ2AEkXlgI6uIzwTqj7DZQYg,60514
+googleapiclient/discovery_cache/documents/translate.v2.json,sha256=uIVhWVyniBow5R6_BxTdei59xpeUcu2hPy_fLyX8Jig,11984
+googleapiclient/discovery_cache/documents/translate.v3.json,sha256=qZ6w_xQD6n04iuKmlI0eFDGtWLYREc7aGWeYmYPeSB0,119777
+googleapiclient/discovery_cache/documents/translate.v3beta1.json,sha256=3JskOUIdMmdpZX9neNh6amXt0BNmaMOfqO-_WBrfOp0,69036
+googleapiclient/discovery_cache/documents/travelimpactmodel.v1.json,sha256=huyUBdse6qFOBisyjgXj_JYN4U9QTW5hjU6uYTVxc9s,14749
+googleapiclient/discovery_cache/documents/vault.v1.json,sha256=Mr3YEAa6RvibJ7bZLn9UV4k-Ncu4nrHbyntcrYizizQ,78021
+googleapiclient/discovery_cache/documents/vectortile.v1.json,sha256=ox05W0ZLG7Yn-6uUQOP3yeXgibQfaQ6tqA6iv865DQg,47652
+googleapiclient/discovery_cache/documents/verifiedaccess.v1.json,sha256=ZkV9tEhH50MT-olunVV3JgrrUGBAOEjvqGlYD4bEaOg,6762
+googleapiclient/discovery_cache/documents/verifiedaccess.v2.json,sha256=0lDFzVooC54YvXSBhhBtzOTV08KKRa9K0soHeuBxqGk,20018
+googleapiclient/discovery_cache/documents/versionhistory.v1.json,sha256=bX1p4jg1aH-GQsQ9Ohk9yabe8NclxmJY40dxNROPSNI,17231
+googleapiclient/discovery_cache/documents/videointelligence.v1.json,sha256=nh_dk2sOEpCAQLCqwGyesX9rmLJHaoVg7BUisKI86zE,182086
+googleapiclient/discovery_cache/documents/videointelligence.v1beta2.json,sha256=aE11s_Nqt4YTnL9rXrk3bsdQqma-AhTQ_t5yO6kzBFw,174248
+googleapiclient/discovery_cache/documents/videointelligence.v1p1beta1.json,sha256=OjyDI_qHpu_X8tpRrtESYMg_OH3_j3Ch7Ru-aTHJd8s,174324
+googleapiclient/discovery_cache/documents/videointelligence.v1p2beta1.json,sha256=ad1dvpLWxfTXfeBzA1P-zBQWGeV_qjDMcLt04jsupxs,174324
+googleapiclient/discovery_cache/documents/videointelligence.v1p3beta1.json,sha256=RXkL68YPnk5J8LlAzkBq-dc6RpHxCWfhjLWTVEiW6DY,174375
+googleapiclient/discovery_cache/documents/vision.v1.json,sha256=h4oQU338yEcP8F9Ux5L9GRuUklohw0-BwS_nrzxbeLI,313435
+googleapiclient/discovery_cache/documents/vision.v1p1beta1.json,sha256=WLUhg3ah5PTFA_cV0gc1tuVy_mcwhTE7muurC0mKHeM,278159
+googleapiclient/discovery_cache/documents/vision.v1p2beta1.json,sha256=FRMYZPzEEih3EmJB48C0S0BaWaF8qy2JRvG58QC2gt8,278159
+googleapiclient/discovery_cache/documents/vmmigration.v1.json,sha256=Nx_KyE5DuMG7aMpGz-z5opJ7-O53SWLWfq-i57FxBNk,191047
+googleapiclient/discovery_cache/documents/vmmigration.v1alpha1.json,sha256=roy6RwwYqf5k4h0ZxY9SSVXPXqsowA3yjF1dug4NlJM,198662
+googleapiclient/discovery_cache/documents/vmwareengine.v1.json,sha256=9oNgyjRKCjNQa9ASjXxIVopIYvk115qyRvO9lCbbxqU,282049
+googleapiclient/discovery_cache/documents/vpcaccess.v1.json,sha256=0xLMLJ6JKIzey6zikIs1z_OIwYo25ylh0h_Oi3oBr54,21403
+googleapiclient/discovery_cache/documents/vpcaccess.v1beta1.json,sha256=8pFTdBK9Pn5sun_O8Wg6FJdPEg7f0cXt2OW0nJEJv70,21802
+googleapiclient/discovery_cache/documents/walletobjects.v1.json,sha256=cxUtoublK8zEq0_MFbOW2sRpI5qji_UpdtVZh6ZFq0g,355331
+googleapiclient/discovery_cache/documents/webfonts.v1.json,sha256=3Dih30_RQmnDPNqGXpfOKPHzak-iycUG9ZQZ4XwZcXo,6487
+googleapiclient/discovery_cache/documents/webmasters.v3.json,sha256=TOTCcpZyUk-dbmnjFVFoQam0hq2wFQg2UV9x-4fuVLY,20097
+googleapiclient/discovery_cache/documents/webrisk.v1.json,sha256=so8K_q7m91psDyyd3aZ_7fKz3CqxLChoz2_El0Pbaig,26588
+googleapiclient/discovery_cache/documents/websecurityscanner.v1.json,sha256=TNLC26NywAM_aK_DpxvkX01hCc7ImJ4sGKE6E8-0JAU,44775
+googleapiclient/discovery_cache/documents/websecurityscanner.v1alpha.json,sha256=QDkWVUfvc0d8Bw95U-_IKqyD3aJ1xXcIcsun53gHdaU,36660
+googleapiclient/discovery_cache/documents/websecurityscanner.v1beta.json,sha256=Cy-vHk51aVECUYd1QFrnow39K0KwVF_RVD9qPdUS9l8,42878
+googleapiclient/discovery_cache/documents/workflowexecutions.v1.json,sha256=ujXLrXbRGfsVWUuU5_3IqX6aM_HgwjWwo6MNMMR_tpE,39175
+googleapiclient/discovery_cache/documents/workflowexecutions.v1beta.json,sha256=tERDKKmiGTK-l3wOrCAhVaA1SjA9d2Wp2fcbqaScb4E,14318
+googleapiclient/discovery_cache/documents/workflows.v1.json,sha256=ojBWVt2y4JKlS6eH4ZjSmmTk8vW5Npq0LEpKJj0b6Rk,28821
+googleapiclient/discovery_cache/documents/workflows.v1beta.json,sha256=dUndWb1xhicFE3Ku6WHE7zx1s1Qe87U6Kh0GcUuAIyQ,22686
+googleapiclient/discovery_cache/documents/workloadmanager.v1.json,sha256=0zxrdjHMEFQe_gMyC1NLtf7RvrQCntgFSusFjfKHlpM,90441
+googleapiclient/discovery_cache/documents/workspaceevents.v1.json,sha256=Liz8N1rTk8-mtROTTpCTa89qpe7RqNV4ec2LHKSGgrA,31554
+googleapiclient/discovery_cache/documents/workstations.v1.json,sha256=qv0YSyJ4J8qi7Abn8E98AJ4Xwp_XOXOgMn6VoHGEsXU,106551
+googleapiclient/discovery_cache/documents/workstations.v1beta.json,sha256=vrM7hrAz90i2-bAAGrisG3Ms6BPzNONYT2Vq6yibymw,109521
+googleapiclient/discovery_cache/documents/youtube.v3.json,sha256=A8KgBvoHo-4H8hNg-cdSvnccCgz5LzfZu_Qk_s3VJ5k,376871
+googleapiclient/discovery_cache/documents/youtubeAnalytics.v1.json,sha256=KLPoKHO_XT4-LyIZjwSGh44f_htMwjePD2PXR8MH-YY,3220
+googleapiclient/discovery_cache/documents/youtubeAnalytics.v2.json,sha256=Ixl98t7bVU4LpG2rai6RgzSeW-TUmk4abOVGzzttGKQ,28888
+googleapiclient/discovery_cache/documents/youtubereporting.v1.json,sha256=fez-pYUk5gzTFG4W4mPJ7crQV1F1msk1Zdxf2DzpLl0,23094
+googleapiclient/discovery_cache/file_cache.py,sha256=sim3Mg4HgRYo3vX75jvcKy_aV568EvIrtBfvfbw-044,4774
+googleapiclient/errors.py,sha256=9h3uimcMcczBHZJFWAX_YDABzJeJugWB0jmj11rp-LI,5460
+googleapiclient/http.py,sha256=ITE51oqDBqN1-AA5D-Tnlj3egGc_5O0V5xSzBw3UTKI,68241
+googleapiclient/mimeparse.py,sha256=wwouQMCjppTocJtiQhkkTa27kocYwlFRALL2z11Xo1Y,6530
+googleapiclient/model.py,sha256=NQDO1GhOGNVCJlSSCLOecdA11yf8RDXfSLFxYb3R7EE,14085
+googleapiclient/sample_tools.py,sha256=hDBLJNwLluN6AGhaBR-3GXWDrOwRNPvXyseLOyz9l30,4315
+googleapiclient/schema.py,sha256=rR3u8WPQ_V8a7GCUsNuvtf6GxzwuMO0HaqsTBp3tnyM,10414
+googleapiclient/version.py,sha256=WMHStaO0iVOSIrx6sPG2pkzEa5BRXprf55lCvcVi-pY,599
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/licenses/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f907e7e175c8bc3cc7226dbe019836a82cefb1ea
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/google_api_python_client-2.178.0.dist-info/top_level.txt
@@ -0,0 +1,3 @@
+apiclient
+googleapiclient
+googleapiclient/discovery_cache
diff --git a/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..21e4ac84b4392588756347015fbcaa44b88126bf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/METADATA
@@ -0,0 +1,172 @@
+Metadata-Version: 2.4
+Name: gradio_client
+Version: 1.11.0
+Summary: Python library for easily interacting with trained machine learning models
+Project-URL: Homepage, https://github.com/gradio-app/gradio
+Author-email: Abubakar Abid , Ali Abid , Ali Abdalla , Dawood Khan , Ahsen Khaliq , Pete Allen , Freddy Boulton
+License-Expression: Apache-2.0
+Keywords: API,client,machine learning
+Classifier: Development Status :: 4 - Beta
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
+Classifier: Topic :: Software Development :: User Interfaces
+Requires-Python: >=3.10
+Requires-Dist: fsspec
+Requires-Dist: httpx>=0.24.1
+Requires-Dist: huggingface-hub>=0.19.3
+Requires-Dist: packaging
+Requires-Dist: typing-extensions~=4.0
+Requires-Dist: websockets<16.0,>=10.0
+Description-Content-Type: text/markdown
+
+# `gradio_client`: Use a Gradio app as an API -- in 3 lines of Python
+
+This directory contains the source code for `gradio_client`, a lightweight Python library that makes it very easy to use any Gradio app as an API.
+
+As an example, consider this [Hugging Face Space that transcribes audio files](https://huggingface.co/spaces/abidlabs/whisper) that are recorded from the microphone.
+
+
+
+Using the `gradio_client` library, we can easily use the Gradio as an API to transcribe audio files programmatically.
+
+Here's the entire code to do it:
+
+```python
+from gradio_client import Client
+
+client = Client("abidlabs/whisper")
+client.predict("audio_sample.wav")
+
+>> "This is a test of the whisper speech recognition model."
+```
+
+The Gradio client works with any Gradio Space, whether it be an image generator, a stateful chatbot, or a tax calculator.
+
+## Installation
+
+If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency.
+
+Otherwise, the lightweight `gradio_client` package can be installed from pip (or pip3) and works with Python versions 3.10 or higher:
+
+```bash
+$ pip install gradio_client
+```
+
+## Basic Usage
+
+### Connecting to a Space or a Gradio app
+
+Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Spaces (or anywhere else)!
+
+**Connecting to a Space**
+
+```python
+from gradio_client import Client
+
+client = Client("abidlabs/en2fr") # a Space that translates from English to French
+```
+
+You can also connect to private Spaces by passing in your HF token with the `hf_token` parameter. You can get your HF token here: https://huggingface.co/settings/tokens
+
+```python
+from gradio_client import Client
+
+client = Client("abidlabs/my-private-space", hf_token="...")
+```
+
+**Duplicating a Space for private use**
+
+While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,
+and then use it to make as many requests as you'd like!
+
+The `gradio_client` includes a class method: `Client.duplicate()` to make this process simple:
+
+```python
+from gradio_client import Client
+
+client = Client.duplicate("abidlabs/whisper")
+client.predict("audio_sample.wav")
+
+>> "This is a test of the whisper speech recognition model."
+```
+
+If you have previously duplicated a Space, re-running `duplicate()` will _not_ create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate()` method multiple times.
+
+**Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the `hardware` parameter of `duplicate()`.
+
+**Connecting a general Gradio app**
+
+If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
+
+```python
+from gradio_client import Client
+
+client = Client("https://bec81a83-5b5c-471e.gradio.live")
+```
+
+### Inspecting the API endpoints
+
+Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `.view_api()` method. For the Whisper Space, we see the following:
+
+```
+Client.predict() Usage Info
+---------------------------
+Named API endpoints: 1
+
+ - predict(input_audio, api_name="/predict") -> value_0
+ Parameters:
+ - [Audio] input_audio: str (filepath or URL)
+ Returns:
+ - [Textbox] value_0: str (value)
+```
+
+This shows us that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method, providing a parameter `input_audio` of type `str`, which is a `filepath or URL`.
+
+We should also provide the `api_name='/predict'` argument. Although this isn't necessary if a Gradio app has a single named endpoint, it does allow us to call different endpoints in a single app if they are available. If an app has unnamed API endpoints, these can also be displayed by running `.view_api(all_endpoints=True)`.
+
+### Making a prediction
+
+The simplest way to make a prediction is simply to call the `.predict()` function with the appropriate arguments:
+
+```python
+from gradio_client import Client
+
+client = Client("abidlabs/en2fr")
+client.predict("Hello")
+
+>> Bonjour
+```
+
+If there are multiple parameters, then you should pass them as separate arguments to `.predict()`, like this:
+
+```python
+from gradio_client import Client
+
+client = Client("gradio/calculator")
+client.predict(4, "add", 5)
+
+>> 9.0
+```
+
+For certain inputs, such as images, you should pass in the filepath or URL to the file. Likewise, for the corresponding output types, you will get a filepath or URL returned.
+
+```python
+from gradio_client import Client
+
+client = Client("abidlabs/whisper")
+client.predict("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3")
+
+>> "My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don't find simpus, and devoted abode, to at might in a r—"
+```
+
+## Advanced Usage
+
+For more ways to use the Gradio Python Client, check out our dedicated Guide on the Python client, available here: https://www.gradio.app/guides/getting-started-with-the-python-client
diff --git a/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..11dd54f712c90c8afd0e439260ad7da8b489fdfa
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/RECORD
@@ -0,0 +1,32 @@
+gradio_client-1.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+gradio_client-1.11.0.dist-info/METADATA,sha256=PI2I2ioeDZAIxmXCFtcSqJFjTdJSiK73Ez88iFQfQQI,7116
+gradio_client-1.11.0.dist-info/RECORD,,
+gradio_client-1.11.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+gradio_client-1.11.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
+gradio_client/CHANGELOG.md,sha256=Vj_GLwc_vQEQQ2nT5EKiWd2dvEX-gIkP1EYWguqkaCU,50734
+gradio_client/__init__.py,sha256=GtVHNFpTWZo0hL7CZTjwGiP3Ml2iHQyDof25LhmxSd0,246
+gradio_client/__pycache__/__init__.cpython-310.pyc,,
+gradio_client/__pycache__/client.cpython-310.pyc,,
+gradio_client/__pycache__/compatibility.cpython-310.pyc,,
+gradio_client/__pycache__/data_classes.cpython-310.pyc,,
+gradio_client/__pycache__/documentation.cpython-310.pyc,,
+gradio_client/__pycache__/exceptions.cpython-310.pyc,,
+gradio_client/__pycache__/media_data.cpython-310.pyc,,
+gradio_client/__pycache__/serializing.cpython-310.pyc,,
+gradio_client/__pycache__/utils.cpython-310.pyc,,
+gradio_client/cli/__init__.py,sha256=jW4mYjLdQ-UbPqKNMKmhkNLKu2lBU2pDn4gTKPX-0bg,75
+gradio_client/cli/__pycache__/__init__.cpython-310.pyc,,
+gradio_client/cli/__pycache__/deploy_discord.cpython-310.pyc,,
+gradio_client/cli/deploy_discord.py,sha256=1R6SkXMEO6MN-fqgXVNOsvRjz5prkObLuRFZv5d0vgg,1344
+gradio_client/client.py,sha256=1G7ttwSDyI-jSS_prhXIYKjn67-OsuUD1jiXHiE_CbQ,74153
+gradio_client/compatibility.py,sha256=fVh3kn6K1J3rhJdt50YJ1gR-gmL04maH4r_kCBn_vOM,13940
+gradio_client/data_classes.py,sha256=tMdBJBjvdqqwg4XSgXpSH7sVHnCfxQY48QuSGf8nYN4,735
+gradio_client/documentation.py,sha256=_SXy06fCcF9aRUo163exKoTz-KqwM3tpgqgiQSQnsy4,14046
+gradio_client/exceptions.py,sha256=rgHdrWypLWpxfJXuJue5lUwqUmIj9AVdSYAwNDdGvE0,1440
+gradio_client/media_data.py,sha256=GQZQJbrbj3dE3_TIUcmDOFmp8DbuBkP7DQTxYT6NN3Y,722623
+gradio_client/package.json,sha256=TKITSufjSZVCzSNf4i1hii8Mwe5fcLM6bXcu3oTZVpw,133
+gradio_client/serializing.py,sha256=gg-yd_DDGpreDYZwrmJqNBL8e8UCXD81wAsu4orAjDg,21045
+gradio_client/templates/__pycache__/discord_chat.cpython-310.pyc,,
+gradio_client/templates/discord_chat.py,sha256=8N28iG3VZNDTujd-OOBQoemqj5ibTjFMhTm-o4TWWc0,5641
+gradio_client/types.json,sha256=hTBJNs5ZyXC1-f-0UfzFezdhzNp3OnUhNs3Qv-muAQ0,4432
+gradio_client/utils.py,sha256=ztqNmC68UzMY4nnUvMy1KkbNZprQRl3thJSFmsxHCMk,44405
diff --git a/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/gradio_client-1.11.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.27.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ae3828669397e90260062082642f57cb75c6ffed
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/LICENSE
@@ -0,0 +1,23 @@
+Httplib2 Software License
+
+Copyright (c) 2006 by Joe Gregorio
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..933bfa0bda2cc032d975ce8ab5be357a840cb464
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/METADATA
@@ -0,0 +1,75 @@
+Metadata-Version: 2.1
+Name: httplib2
+Version: 0.22.0
+Summary: A comprehensive HTTP client library.
+Home-page: https://github.com/httplib2/httplib2
+Author: Joe Gregorio
+Author-email: joe@bitworking.org
+License: MIT
+Classifier: Development Status :: 4 - Beta
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Topic :: Internet :: WWW/HTTP
+Classifier: Topic :: Software Development :: Libraries
+Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*
+License-File: LICENSE
+Requires-Dist: pyparsing (<3,>=2.4.2) ; python_version < "3.0"
+Requires-Dist: pyparsing (!=3.0.0,!=3.0.1,!=3.0.2,!=3.0.3,<4,>=2.4.2) ; python_version > "3.0"
+
+
+
+A comprehensive HTTP client library, ``httplib2`` supports many features left out of other HTTP libraries.
+
+**HTTP and HTTPS**
+ HTTPS support is only available if the socket module was compiled with SSL support.
+
+
+**Keep-Alive**
+ Supports HTTP 1.1 Keep-Alive, keeping the socket open and performing multiple requests over the same connection if possible.
+
+
+**Authentication**
+ The following three types of HTTP Authentication are supported. These can be used over both HTTP and HTTPS.
+
+ * Digest
+ * Basic
+ * WSSE
+
+**Caching**
+ The module can optionally operate with a private cache that understands the Cache-Control:
+ header and uses both the ETag and Last-Modified cache validators. Both file system
+ and memcached based caches are supported.
+
+
+**All Methods**
+ The module can handle any HTTP request method, not just GET and POST.
+
+
+**Redirects**
+ Automatically follows 3XX redirects on GETs.
+
+
+**Compression**
+ Handles both 'deflate' and 'gzip' types of compression.
+
+
+**Lost update support**
+ Automatically adds back ETags into PUT requests to resources we have already cached. This implements Section 3.2 of Detecting the Lost Update Problem Using Unreserved Checkout
+
+
+**Unit Tested**
+ A large and growing set of unit tests.
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..c81c10487dcf32105f34c880b522df3d7ef443a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/RECORD
@@ -0,0 +1,19 @@
+httplib2-0.22.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+httplib2-0.22.0.dist-info/LICENSE,sha256=WJ7sOPct8r4gNxHTuMvs6bkIxef_ALw8q39juunjZrQ,1086
+httplib2-0.22.0.dist-info/METADATA,sha256=KKy58CVIaYnc6oBjD0upeaA1dgTbB6z7JK5I6FmDSEM,2618
+httplib2-0.22.0.dist-info/RECORD,,
+httplib2-0.22.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
+httplib2-0.22.0.dist-info/top_level.txt,sha256=BEY8ChKwagUWmu9x8yN9JObJpZKNeWCr1E-sIECb56I,9
+httplib2/__init__.py,sha256=UOzaxGwGweHiLsxKBc39_Ez0N8aDHwAu--TkTbYLWCw,69396
+httplib2/__pycache__/__init__.cpython-310.pyc,,
+httplib2/__pycache__/auth.cpython-310.pyc,,
+httplib2/__pycache__/certs.cpython-310.pyc,,
+httplib2/__pycache__/error.cpython-310.pyc,,
+httplib2/__pycache__/iri2uri.cpython-310.pyc,,
+httplib2/__pycache__/socks.cpython-310.pyc,,
+httplib2/auth.py,sha256=Fcb7KqrqRCpUaGD-5l84nT5F2aU6ore6ujWLk5idK0o,2158
+httplib2/cacerts.txt,sha256=AbmYP54iGeKRQ1APtfQvHlo9wul2jVmznmbTzy2fTV4,137365
+httplib2/certs.py,sha256=guhfjMNhDdKJEyYBb5ZyLxVO5q1I7Y_P-4BG8MniBk8,971
+httplib2/error.py,sha256=GyqPUvZeKdVLq0f3xg0uX4rjtv7jVGJuPerAdyc-jfk,954
+httplib2/iri2uri.py,sha256=PhIzEzeR6C73l7piwrNAJlVvlWgsqxtJTlFeXgznzQo,4153
+httplib2/socks.py,sha256=oaeEOnT2rkTNm6wnn0CSdhWzVaVshnnkAKiP4kxKzzc,19701
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..1f37c02f2eb2e26b306202feaccb31e522b8b169
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.40.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fb881ece05bf2f998d84be544449ac976da2897c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2-0.22.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+httplib2
diff --git a/venv/lib/python3.10/site-packages/httplib2/__init__.py b/venv/lib/python3.10/site-packages/httplib2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..723a63c5b80fba698e7dba7904e6f1d610a3dd14
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/__init__.py
@@ -0,0 +1,1799 @@
+# -*- coding: utf-8 -*-
+"""Small, fast HTTP client library for Python."""
+
+__author__ = "Joe Gregorio (joe@bitworking.org)"
+__copyright__ = "Copyright 2006, Joe Gregorio"
+__contributors__ = [
+ "Thomas Broyer (t.broyer@ltgt.net)",
+ "James Antill",
+ "Xavier Verges Farrero",
+ "Jonathan Feinberg",
+ "Blair Zajac",
+ "Sam Ruby",
+ "Louis Nyffenegger",
+ "Mark Pilgrim",
+ "Alex Yu",
+ "Lai Han",
+]
+__license__ = "MIT"
+__version__ = "0.22.0"
+
+import base64
+import calendar
+import copy
+import email
+import email.feedparser
+from email import header
+import email.message
+import email.utils
+import errno
+from gettext import gettext as _
+import gzip
+from hashlib import md5 as _md5
+from hashlib import sha1 as _sha
+import hmac
+import http.client
+import io
+import os
+import random
+import re
+import socket
+import ssl
+import sys
+import time
+import urllib.parse
+import zlib
+
+try:
+ import socks
+except ImportError:
+ # TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
+ # idea is to have soft-dependency on any compatible module called socks
+ from . import socks
+from . import auth
+from .error import *
+from .iri2uri import iri2uri
+
+
+def has_timeout(timeout):
+ if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
+ return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
+ return timeout is not None
+
+
+__all__ = [
+ "debuglevel",
+ "FailedToDecompressContent",
+ "Http",
+ "HttpLib2Error",
+ "ProxyInfo",
+ "RedirectLimit",
+ "RedirectMissingLocation",
+ "Response",
+ "RETRIES",
+ "UnimplementedDigestAuthOptionError",
+ "UnimplementedHmacDigestAuthOptionError",
+]
+
+# The httplib debug level, set to a non-zero value to get debug output
+debuglevel = 0
+
+# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
+RETRIES = 2
+
+
+# Open Items:
+# -----------
+
+# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
+
+# Pluggable cache storage (supports storing the cache in
+# flat files by default. We need a plug-in architecture
+# that can support Berkeley DB and Squid)
+
+# == Known Issues ==
+# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
+# Does not handle Cache-Control: max-stale
+# Does not use Age: headers when calculating cache freshness.
+
+# The number of redirections to follow before giving up.
+# Note that only GET redirects are automatically followed.
+# Will also honor 301 requests by saving that info and never
+# requesting that URI again.
+DEFAULT_MAX_REDIRECTS = 5
+
+# Which headers are hop-by-hop headers by default
+HOP_BY_HOP = [
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailers",
+ "transfer-encoding",
+ "upgrade",
+]
+
+# https://tools.ietf.org/html/rfc7231#section-8.1.3
+SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
+
+# To change, assign to `Http().redirect_codes`
+REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308))
+
+
+from httplib2 import certs
+
+CA_CERTS = certs.where()
+
+# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
+# Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means:
+# > Selects the highest protocol version that both the client and server support.
+# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
+# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_SSLv23
+
+# PROTOCOL_TLS_CLIENT is python 3.10.0+. PROTOCOL_TLS is deprecated.
+# > Auto-negotiate the highest protocol version that both the client and server support, and configure the context client-side connections.
+# > The protocol enables CERT_REQUIRED and check_hostname by default.
+# source: https://docs.python.org/3.10/library/ssl.html#ssl.PROTOCOL_TLS
+
+DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS_CLIENT", None) or getattr(ssl, "PROTOCOL_TLS", None) or getattr(ssl, "PROTOCOL_SSLv23")
+
+
+def _build_ssl_context(
+ disable_ssl_certificate_validation,
+ ca_certs,
+ cert_file=None,
+ key_file=None,
+ maximum_version=None,
+ minimum_version=None,
+ key_password=None,
+):
+ if not hasattr(ssl, "SSLContext"):
+ raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext")
+
+ context = ssl.SSLContext(DEFAULT_TLS_VERSION)
+ # check_hostname and verify_mode should be set in opposite order during disable
+ # https://bugs.python.org/issue31431
+ if disable_ssl_certificate_validation and hasattr(context, "check_hostname"):
+ context.check_hostname = not disable_ssl_certificate_validation
+ context.verify_mode = ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED
+
+ # SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+.
+ # source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version
+ if maximum_version is not None:
+ if hasattr(context, "maximum_version"):
+ if isinstance(maximum_version, str):
+ maximum_version = getattr(ssl.TLSVersion, maximum_version)
+ context.maximum_version = maximum_version
+ else:
+ raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer")
+ if minimum_version is not None:
+ if hasattr(context, "minimum_version"):
+ if isinstance(minimum_version, str):
+ minimum_version = getattr(ssl.TLSVersion, minimum_version)
+ context.minimum_version = minimum_version
+ else:
+ raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer")
+ # check_hostname requires python 3.4+
+ # we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname
+ # if check_hostname is not supported.
+ if hasattr(context, "check_hostname"):
+ context.check_hostname = not disable_ssl_certificate_validation
+
+ context.load_verify_locations(ca_certs)
+
+ if cert_file:
+ context.load_cert_chain(cert_file, key_file, key_password)
+
+ return context
+
+
+def _get_end2end_headers(response):
+ hopbyhop = list(HOP_BY_HOP)
+ hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
+ return [header for header in list(response.keys()) if header not in hopbyhop]
+
+
+_missing = object()
+
+
+def _errno_from_exception(e):
+ # TODO python 3.11+ cheap try: return e.errno except AttributeError: pass
+ errno = getattr(e, "errno", _missing)
+ if errno is not _missing:
+ return errno
+
+ # socket.error and common wrap in .args
+ args = getattr(e, "args", None)
+ if args:
+ return _errno_from_exception(args[0])
+
+ # pysocks.ProxyError wraps in .socket_err
+ # https://github.com/httplib2/httplib2/pull/202
+ socket_err = getattr(e, "socket_err", None)
+ if socket_err:
+ return _errno_from_exception(socket_err)
+
+ return None
+
+
+URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
+
+
+def parse_uri(uri):
+ """Parses a URI using the regex given in Appendix B of RFC 3986.
+
+ (scheme, authority, path, query, fragment) = parse_uri(uri)
+ """
+ groups = URI.match(uri).groups()
+ return (groups[1], groups[3], groups[4], groups[6], groups[8])
+
+
+def urlnorm(uri):
+ (scheme, authority, path, query, fragment) = parse_uri(uri)
+ if not scheme or not authority:
+ raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
+ authority = authority.lower()
+ scheme = scheme.lower()
+ if not path:
+ path = "/"
+ # Could do syntax based normalization of the URI before
+ # computing the digest. See Section 6.2.2 of Std 66.
+ request_uri = query and "?".join([path, query]) or path
+ scheme = scheme.lower()
+ defrag_uri = scheme + "://" + authority + request_uri
+ return scheme, authority, request_uri, defrag_uri
+
+
+# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
+re_url_scheme = re.compile(r"^\w+://")
+re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII)
+
+
+def safename(filename):
+ """Return a filename suitable for the cache.
+ Strips dangerous and common characters to create a filename we
+ can use to store the cache in.
+ """
+ if isinstance(filename, bytes):
+ filename_bytes = filename
+ filename = filename.decode("utf-8")
+ else:
+ filename_bytes = filename.encode("utf-8")
+ filemd5 = _md5(filename_bytes).hexdigest()
+ filename = re_url_scheme.sub("", filename)
+ filename = re_unsafe.sub("", filename)
+
+ # limit length of filename (vital for Windows)
+ # https://github.com/httplib2/httplib2/pull/74
+ # C:\Users\ \AppData\Local\Temp\ ,
+ # 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
+ # Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
+ filename = filename[:90]
+
+ return ",".join((filename, filemd5))
+
+
+NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
+
+
+def _normalize_headers(headers):
+ return dict(
+ [
+ (_convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),)
+ for (key, value) in headers.items()
+ ]
+ )
+
+
+def _convert_byte_str(s):
+ if not isinstance(s, str):
+ return str(s, "utf-8")
+ return s
+
+
+def _parse_cache_control(headers):
+ retval = {}
+ if "cache-control" in headers:
+ parts = headers["cache-control"].split(",")
+ parts_with_args = [
+ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")
+ ]
+ parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
+ retval = dict(parts_with_args + parts_wo_args)
+ return retval
+
+
+# Whether to use a strict mode to parse WWW-Authenticate headers
+# Might lead to bad results in case of ill-formed header value,
+# so disabled by default, falling back to relaxed parsing.
+# Set to true to turn on, useful for testing servers.
+USE_WWW_AUTH_STRICT_PARSING = 0
+
+
+def _entry_disposition(response_headers, request_headers):
+ """Determine freshness from the Date, Expires and Cache-Control headers.
+
+ We don't handle the following:
+
+ 1. Cache-Control: max-stale
+ 2. Age: headers are not used in the calculations.
+
+ Not that this algorithm is simpler than you might think
+ because we are operating as a private (non-shared) cache.
+ This lets us ignore 's-maxage'. We can also ignore
+ 'proxy-invalidate' since we aren't a proxy.
+ We will never return a stale document as
+ fresh as a design decision, and thus the non-implementation
+ of 'max-stale'. This also lets us safely ignore 'must-revalidate'
+ since we operate as if every server has sent 'must-revalidate'.
+ Since we are private we get to ignore both 'public' and
+ 'private' parameters. We also ignore 'no-transform' since
+ we don't do any transformations.
+ The 'no-store' parameter is handled at a higher level.
+ So the only Cache-Control parameters we look at are:
+
+ no-cache
+ only-if-cached
+ max-age
+ min-fresh
+ """
+
+ retval = "STALE"
+ cc = _parse_cache_control(request_headers)
+ cc_response = _parse_cache_control(response_headers)
+
+ if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1:
+ retval = "TRANSPARENT"
+ if "cache-control" not in request_headers:
+ request_headers["cache-control"] = "no-cache"
+ elif "no-cache" in cc:
+ retval = "TRANSPARENT"
+ elif "no-cache" in cc_response:
+ retval = "STALE"
+ elif "only-if-cached" in cc:
+ retval = "FRESH"
+ elif "date" in response_headers:
+ date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"]))
+ now = time.time()
+ current_age = max(0, now - date)
+ if "max-age" in cc_response:
+ try:
+ freshness_lifetime = int(cc_response["max-age"])
+ except ValueError:
+ freshness_lifetime = 0
+ elif "expires" in response_headers:
+ expires = email.utils.parsedate_tz(response_headers["expires"])
+ if None == expires:
+ freshness_lifetime = 0
+ else:
+ freshness_lifetime = max(0, calendar.timegm(expires) - date)
+ else:
+ freshness_lifetime = 0
+ if "max-age" in cc:
+ try:
+ freshness_lifetime = int(cc["max-age"])
+ except ValueError:
+ freshness_lifetime = 0
+ if "min-fresh" in cc:
+ try:
+ min_fresh = int(cc["min-fresh"])
+ except ValueError:
+ min_fresh = 0
+ current_age += min_fresh
+ if freshness_lifetime > current_age:
+ retval = "FRESH"
+ return retval
+
+
+def _decompressContent(response, new_content):
+ content = new_content
+ try:
+ encoding = response.get("content-encoding", None)
+ if encoding in ["gzip", "deflate"]:
+ if encoding == "gzip":
+ content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
+ if encoding == "deflate":
+ try:
+ content = zlib.decompress(content, zlib.MAX_WBITS)
+ except (IOError, zlib.error):
+ content = zlib.decompress(content, -zlib.MAX_WBITS)
+ response["content-length"] = str(len(content))
+ # Record the historical presence of the encoding in a way the won't interfere.
+ response["-content-encoding"] = response["content-encoding"]
+ del response["content-encoding"]
+ except (IOError, zlib.error):
+ content = ""
+ raise FailedToDecompressContent(
+ _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"),
+ response,
+ content,
+ )
+ return content
+
+
+def _bind_write_headers(msg):
+ def _write_headers(self):
+ # Self refers to the Generator object.
+ for h, v in msg.items():
+ print("%s:" % h, end=" ", file=self._fp)
+ if isinstance(v, header.Header):
+ print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
+ else:
+ # email.Header got lots of smarts, so use it.
+ headers = header.Header(v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h)
+ print(headers.encode(), file=self._fp)
+ # A blank line always separates headers from body.
+ print(file=self._fp)
+
+ return _write_headers
+
+
+def _updateCache(request_headers, response_headers, content, cache, cachekey):
+ if cachekey:
+ cc = _parse_cache_control(request_headers)
+ cc_response = _parse_cache_control(response_headers)
+ if "no-store" in cc or "no-store" in cc_response:
+ cache.delete(cachekey)
+ else:
+ info = email.message.Message()
+ for key, value in response_headers.items():
+ if key not in ["status", "content-encoding", "transfer-encoding"]:
+ info[key] = value
+
+ # Add annotations to the cache to indicate what headers
+ # are variant for this request.
+ vary = response_headers.get("vary", None)
+ if vary:
+ vary_headers = vary.lower().replace(" ", "").split(",")
+ for header in vary_headers:
+ key = "-varied-%s" % header
+ try:
+ info[key] = request_headers[header]
+ except KeyError:
+ pass
+
+ status = response_headers.status
+ if status == 304:
+ status = 200
+
+ status_header = "status: %d\r\n" % status
+
+ try:
+ header_str = info.as_string()
+ except UnicodeEncodeError:
+ setattr(info, "_write_headers", _bind_write_headers(info))
+ header_str = info.as_string()
+
+ header_str = re.sub("\r(?!\n)|(? 0:
+ service = "cl"
+ # No point in guessing Base or Spreadsheet
+ # elif request_uri.find("spreadsheets") > 0:
+ # service = "wise"
+
+ auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],)
+ resp, content = self.http.request(
+ "https://www.google.com/accounts/ClientLogin",
+ method="POST",
+ body=urlencode(auth),
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ lines = content.split("\n")
+ d = dict([tuple(line.split("=", 1)) for line in lines if line])
+ if resp.status == 403:
+ self.Auth = ""
+ else:
+ self.Auth = d["Auth"]
+
+ def request(self, method, request_uri, headers, content):
+ """Modify the request headers to add the appropriate
+ Authorization header."""
+ headers["authorization"] = "GoogleLogin Auth=" + self.Auth
+
+
+AUTH_SCHEME_CLASSES = {
+ "basic": BasicAuthentication,
+ "wsse": WsseAuthentication,
+ "digest": DigestAuthentication,
+ "hmacdigest": HmacDigestAuthentication,
+ "googlelogin": GoogleLoginAuthentication,
+}
+
+AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
+
+
+class FileCache(object):
+ """Uses a local directory as a store for cached files.
+ Not really safe to use if multiple threads or processes are going to
+ be running on the same cache.
+ """
+
+ def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
+ self.cache = cache
+ self.safe = safe
+ if not os.path.exists(cache):
+ os.makedirs(self.cache)
+
+ def get(self, key):
+ retval = None
+ cacheFullPath = os.path.join(self.cache, self.safe(key))
+ try:
+ f = open(cacheFullPath, "rb")
+ retval = f.read()
+ f.close()
+ except IOError:
+ pass
+ return retval
+
+ def set(self, key, value):
+ cacheFullPath = os.path.join(self.cache, self.safe(key))
+ f = open(cacheFullPath, "wb")
+ f.write(value)
+ f.close()
+
+ def delete(self, key):
+ cacheFullPath = os.path.join(self.cache, self.safe(key))
+ if os.path.exists(cacheFullPath):
+ os.remove(cacheFullPath)
+
+
+class Credentials(object):
+ def __init__(self):
+ self.credentials = []
+
+ def add(self, name, password, domain=""):
+ self.credentials.append((domain.lower(), name, password))
+
+ def clear(self):
+ self.credentials = []
+
+ def iter(self, domain):
+ for (cdomain, name, password) in self.credentials:
+ if cdomain == "" or domain == cdomain:
+ yield (name, password)
+
+
+class KeyCerts(Credentials):
+ """Identical to Credentials except that
+ name/password are mapped to key/cert."""
+
+ def add(self, key, cert, domain, password):
+ self.credentials.append((domain.lower(), key, cert, password))
+
+ def iter(self, domain):
+ for (cdomain, key, cert, password) in self.credentials:
+ if cdomain == "" or domain == cdomain:
+ yield (key, cert, password)
+
+
+class AllHosts(object):
+ pass
+
+
+class ProxyInfo(object):
+ """Collect information required to use a proxy."""
+
+ bypass_hosts = ()
+
+ def __init__(
+ self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
+ ):
+ """Args:
+
+ proxy_type: The type of proxy server. This must be set to one of
+ socks.PROXY_TYPE_XXX constants. For example: p =
+ ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
+ proxy_port=8000)
+ proxy_host: The hostname or IP address of the proxy server.
+ proxy_port: The port that the proxy server is running on.
+ proxy_rdns: If True (default), DNS queries will not be performed
+ locally, and instead, handed to the proxy to resolve. This is useful
+ if the network does not allow resolution of non-local names. In
+ httplib2 0.9 and earlier, this defaulted to False.
+ proxy_user: The username used to authenticate with the proxy server.
+ proxy_pass: The password used to authenticate with the proxy server.
+ proxy_headers: Additional or modified headers for the proxy connect
+ request.
+ """
+ if isinstance(proxy_user, bytes):
+ proxy_user = proxy_user.decode()
+ if isinstance(proxy_pass, bytes):
+ proxy_pass = proxy_pass.decode()
+ (
+ self.proxy_type,
+ self.proxy_host,
+ self.proxy_port,
+ self.proxy_rdns,
+ self.proxy_user,
+ self.proxy_pass,
+ self.proxy_headers,
+ ) = (
+ proxy_type,
+ proxy_host,
+ proxy_port,
+ proxy_rdns,
+ proxy_user,
+ proxy_pass,
+ proxy_headers,
+ )
+
+ def astuple(self):
+ return (
+ self.proxy_type,
+ self.proxy_host,
+ self.proxy_port,
+ self.proxy_rdns,
+ self.proxy_user,
+ self.proxy_pass,
+ self.proxy_headers,
+ )
+
+ def isgood(self):
+ return socks and (self.proxy_host != None) and (self.proxy_port != None)
+
+ def applies_to(self, hostname):
+ return not self.bypass_host(hostname)
+
+ def bypass_host(self, hostname):
+ """Has this host been excluded from the proxy config"""
+ if self.bypass_hosts is AllHosts:
+ return True
+
+ hostname = "." + hostname.lstrip(".")
+ for skip_name in self.bypass_hosts:
+ # *.suffix
+ if skip_name.startswith(".") and hostname.endswith(skip_name):
+ return True
+ # exact match
+ if hostname == "." + skip_name:
+ return True
+ return False
+
+ def __repr__(self):
+ return (
+ ""
+ ).format(p=self)
+
+
+def proxy_info_from_environment(method="http"):
+ """Read proxy info from the environment variables.
+ """
+ if method not in ("http", "https"):
+ return
+
+ env_var = method + "_proxy"
+ url = os.environ.get(env_var, os.environ.get(env_var.upper()))
+ if not url:
+ return
+ return proxy_info_from_url(url, method, noproxy=None)
+
+
+def proxy_info_from_url(url, method="http", noproxy=None):
+ """Construct a ProxyInfo from a URL (such as http_proxy env var)
+ """
+ url = urllib.parse.urlparse(url)
+
+ proxy_type = 3 # socks.PROXY_TYPE_HTTP
+ pi = ProxyInfo(
+ proxy_type=proxy_type,
+ proxy_host=url.hostname,
+ proxy_port=url.port or dict(https=443, http=80)[method],
+ proxy_user=url.username or None,
+ proxy_pass=url.password or None,
+ proxy_headers=None,
+ )
+
+ bypass_hosts = []
+ # If not given an explicit noproxy value, respect values in env vars.
+ if noproxy is None:
+ noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
+ # Special case: A single '*' character means all hosts should be bypassed.
+ if noproxy == "*":
+ bypass_hosts = AllHosts
+ elif noproxy.strip():
+ bypass_hosts = noproxy.split(",")
+ bypass_hosts = tuple(filter(bool, bypass_hosts)) # To exclude empty string.
+
+ pi.bypass_hosts = bypass_hosts
+ return pi
+
+
+class HTTPConnectionWithTimeout(http.client.HTTPConnection):
+ """HTTPConnection subclass that supports timeouts
+
+ HTTPConnection subclass that supports timeouts
+
+ All timeouts are in seconds. If None is passed for timeout then
+ Python's default timeout for sockets will be used. See for example
+ the docs of socket.setdefaulttimeout():
+ http://docs.python.org/library/socket.html#socket.setdefaulttimeout
+ """
+
+ def __init__(self, host, port=None, timeout=None, proxy_info=None):
+ http.client.HTTPConnection.__init__(self, host, port=port, timeout=timeout)
+
+ self.proxy_info = proxy_info
+ if proxy_info and not isinstance(proxy_info, ProxyInfo):
+ self.proxy_info = proxy_info("http")
+
+ def connect(self):
+ """Connect to the host and port specified in __init__."""
+ if self.proxy_info and socks is None:
+ raise ProxiesUnavailableError("Proxy support missing but proxy use was requested!")
+ if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
+ use_proxy = True
+ (
+ proxy_type,
+ proxy_host,
+ proxy_port,
+ proxy_rdns,
+ proxy_user,
+ proxy_pass,
+ proxy_headers,
+ ) = self.proxy_info.astuple()
+
+ host = proxy_host
+ port = proxy_port
+ else:
+ use_proxy = False
+
+ host = self.host
+ port = self.port
+ proxy_type = None
+
+ socket_err = None
+
+ for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
+ af, socktype, proto, canonname, sa = res
+ try:
+ if use_proxy:
+ self.sock = socks.socksocket(af, socktype, proto)
+ self.sock.setproxy(
+ proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass,
+ )
+ else:
+ self.sock = socket.socket(af, socktype, proto)
+ self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ if has_timeout(self.timeout):
+ self.sock.settimeout(self.timeout)
+ if self.debuglevel > 0:
+ print("connect: ({0}, {1}) ************".format(self.host, self.port))
+ if use_proxy:
+ print(
+ "proxy: {0} ************".format(
+ str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
+ )
+ )
+
+ self.sock.connect((self.host, self.port) + sa[2:])
+ except socket.error as e:
+ socket_err = e
+ if self.debuglevel > 0:
+ print("connect fail: ({0}, {1})".format(self.host, self.port))
+ if use_proxy:
+ print(
+ "proxy: {0}".format(
+ str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
+ )
+ )
+ if self.sock:
+ self.sock.close()
+ self.sock = None
+ continue
+ break
+ if not self.sock:
+ raise socket_err
+
+
+class HTTPSConnectionWithTimeout(http.client.HTTPSConnection):
+ """This class allows communication via SSL.
+
+ All timeouts are in seconds. If None is passed for timeout then
+ Python's default timeout for sockets will be used. See for example
+ the docs of socket.setdefaulttimeout():
+ http://docs.python.org/library/socket.html#socket.setdefaulttimeout
+ """
+
+ def __init__(
+ self,
+ host,
+ port=None,
+ key_file=None,
+ cert_file=None,
+ timeout=None,
+ proxy_info=None,
+ ca_certs=None,
+ disable_ssl_certificate_validation=False,
+ tls_maximum_version=None,
+ tls_minimum_version=None,
+ key_password=None,
+ ):
+
+ self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
+ self.ca_certs = ca_certs if ca_certs else CA_CERTS
+
+ self.proxy_info = proxy_info
+ if proxy_info and not isinstance(proxy_info, ProxyInfo):
+ self.proxy_info = proxy_info("https")
+
+ context = _build_ssl_context(
+ self.disable_ssl_certificate_validation,
+ self.ca_certs,
+ cert_file,
+ key_file,
+ maximum_version=tls_maximum_version,
+ minimum_version=tls_minimum_version,
+ key_password=key_password,
+ )
+ super(HTTPSConnectionWithTimeout, self).__init__(
+ host, port=port, timeout=timeout, context=context,
+ )
+ self.key_file = key_file
+ self.cert_file = cert_file
+ self.key_password = key_password
+
+ def connect(self):
+ """Connect to a host on a given (SSL) port."""
+ if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
+ use_proxy = True
+ (
+ proxy_type,
+ proxy_host,
+ proxy_port,
+ proxy_rdns,
+ proxy_user,
+ proxy_pass,
+ proxy_headers,
+ ) = self.proxy_info.astuple()
+
+ host = proxy_host
+ port = proxy_port
+ else:
+ use_proxy = False
+
+ host = self.host
+ port = self.port
+ proxy_type = None
+ proxy_headers = None
+
+ socket_err = None
+
+ address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+ for family, socktype, proto, canonname, sockaddr in address_info:
+ try:
+ if use_proxy:
+ sock = socks.socksocket(family, socktype, proto)
+
+ sock.setproxy(
+ proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass,
+ )
+ else:
+ sock = socket.socket(family, socktype, proto)
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ if has_timeout(self.timeout):
+ sock.settimeout(self.timeout)
+ sock.connect((self.host, self.port))
+
+ self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
+
+ # Python 3.3 compatibility: emulate the check_hostname behavior
+ if not hasattr(self._context, "check_hostname") and not self.disable_ssl_certificate_validation:
+ try:
+ ssl.match_hostname(self.sock.getpeercert(), self.host)
+ except Exception:
+ self.sock.shutdown(socket.SHUT_RDWR)
+ self.sock.close()
+ raise
+
+ if self.debuglevel > 0:
+ print("connect: ({0}, {1})".format(self.host, self.port))
+ if use_proxy:
+ print(
+ "proxy: {0}".format(
+ str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
+ )
+ )
+ except (ssl.SSLError, ssl.CertificateError) as e:
+ if sock:
+ sock.close()
+ if self.sock:
+ self.sock.close()
+ self.sock = None
+ raise
+ except (socket.timeout, socket.gaierror):
+ raise
+ except socket.error as e:
+ socket_err = e
+ if self.debuglevel > 0:
+ print("connect fail: ({0}, {1})".format(self.host, self.port))
+ if use_proxy:
+ print(
+ "proxy: {0}".format(
+ str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,))
+ )
+ )
+ if self.sock:
+ self.sock.close()
+ self.sock = None
+ continue
+ break
+ if not self.sock:
+ raise socket_err
+
+
+SCHEME_TO_CONNECTION = {
+ "http": HTTPConnectionWithTimeout,
+ "https": HTTPSConnectionWithTimeout,
+}
+
+
+class Http(object):
+ """An HTTP client that handles:
+
+ - all methods
+ - caching
+ - ETags
+ - compression,
+ - HTTPS
+ - Basic
+ - Digest
+ - WSSE
+
+ and more.
+ """
+
+ def __init__(
+ self,
+ cache=None,
+ timeout=None,
+ proxy_info=proxy_info_from_environment,
+ ca_certs=None,
+ disable_ssl_certificate_validation=False,
+ tls_maximum_version=None,
+ tls_minimum_version=None,
+ ):
+ """If 'cache' is a string then it is used as a directory name for
+ a disk cache. Otherwise it must be an object that supports the
+ same interface as FileCache.
+
+ All timeouts are in seconds. If None is passed for timeout
+ then Python's default timeout for sockets will be used. See
+ for example the docs of socket.setdefaulttimeout():
+ http://docs.python.org/library/socket.html#socket.setdefaulttimeout
+
+ `proxy_info` may be:
+ - a callable that takes the http scheme ('http' or 'https') and
+ returns a ProxyInfo instance per request. By default, uses
+ proxy_info_from_environment.
+ - a ProxyInfo instance (static proxy config).
+ - None (proxy disabled).
+
+ ca_certs is the path of a file containing root CA certificates for SSL
+ server certificate validation. By default, a CA cert file bundled with
+ httplib2 is used.
+
+ If disable_ssl_certificate_validation is true, SSL cert validation will
+ not be performed.
+
+ tls_maximum_version / tls_minimum_version require Python 3.7+ /
+ OpenSSL 1.1.0g+. A value of "TLSv1_3" requires OpenSSL 1.1.1+.
+ """
+ self.proxy_info = proxy_info
+ self.ca_certs = ca_certs
+ self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
+ self.tls_maximum_version = tls_maximum_version
+ self.tls_minimum_version = tls_minimum_version
+ # Map domain name to an httplib connection
+ self.connections = {}
+ # The location of the cache, for now a directory
+ # where cached responses are held.
+ if cache and isinstance(cache, str):
+ self.cache = FileCache(cache)
+ else:
+ self.cache = cache
+
+ # Name/password
+ self.credentials = Credentials()
+
+ # Key/cert
+ self.certificates = KeyCerts()
+
+ # authorization objects
+ self.authorizations = []
+
+ # If set to False then no redirects are followed, even safe ones.
+ self.follow_redirects = True
+
+ self.redirect_codes = REDIRECT_CODES
+
+ # Which HTTP methods do we apply optimistic concurrency to, i.e.
+ # which methods get an "if-match:" etag header added to them.
+ self.optimistic_concurrency_methods = ["PUT", "PATCH"]
+
+ self.safe_methods = list(SAFE_METHODS)
+
+ # If 'follow_redirects' is True, and this is set to True then
+ # all redirecs are followed, including unsafe ones.
+ self.follow_all_redirects = False
+
+ self.ignore_etag = False
+
+ self.force_exception_to_status_code = False
+
+ self.timeout = timeout
+
+ # Keep Authorization: headers on a redirect.
+ self.forward_authorization_headers = False
+
+ def close(self):
+ """Close persistent connections, clear sensitive data.
+ Not thread-safe, requires external synchronization against concurrent requests.
+ """
+ existing, self.connections = self.connections, {}
+ for _, c in existing.items():
+ c.close()
+ self.certificates.clear()
+ self.clear_credentials()
+
+ def __getstate__(self):
+ state_dict = copy.copy(self.__dict__)
+ # In case request is augmented by some foreign object such as
+ # credentials which handle auth
+ if "request" in state_dict:
+ del state_dict["request"]
+ if "connections" in state_dict:
+ del state_dict["connections"]
+ return state_dict
+
+ def __setstate__(self, state):
+ self.__dict__.update(state)
+ self.connections = {}
+
+ def _auth_from_challenge(self, host, request_uri, headers, response, content):
+ """A generator that creates Authorization objects
+ that can be applied to requests.
+ """
+ challenges = auth._parse_www_authenticate(response, "www-authenticate")
+ for cred in self.credentials.iter(host):
+ for scheme in AUTH_SCHEME_ORDER:
+ if scheme in challenges:
+ yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
+
+ def add_credentials(self, name, password, domain=""):
+ """Add a name and password that will be used
+ any time a request requires authentication."""
+ self.credentials.add(name, password, domain)
+
+ def add_certificate(self, key, cert, domain, password=None):
+ """Add a key and cert that will be used
+ any time a request requires authentication."""
+ self.certificates.add(key, cert, domain, password)
+
+ def clear_credentials(self):
+ """Remove all the names and passwords
+ that are used for authentication"""
+ self.credentials.clear()
+ self.authorizations = []
+
+ def _conn_request(self, conn, request_uri, method, body, headers):
+ i = 0
+ seen_bad_status_line = False
+ while i < RETRIES:
+ i += 1
+ try:
+ if conn.sock is None:
+ conn.connect()
+ conn.request(method, request_uri, body, headers)
+ except socket.timeout:
+ conn.close()
+ raise
+ except socket.gaierror:
+ conn.close()
+ raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
+ except socket.error as e:
+ errno_ = _errno_from_exception(e)
+ if errno_ in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
+ continue # retry on potentially transient errors
+ raise
+ except http.client.HTTPException:
+ if conn.sock is None:
+ if i < RETRIES - 1:
+ conn.close()
+ conn.connect()
+ continue
+ else:
+ conn.close()
+ raise
+ if i < RETRIES - 1:
+ conn.close()
+ conn.connect()
+ continue
+ # Just because the server closed the connection doesn't apparently mean
+ # that the server didn't send a response.
+ pass
+ try:
+ response = conn.getresponse()
+ except (http.client.BadStatusLine, http.client.ResponseNotReady):
+ # If we get a BadStatusLine on the first try then that means
+ # the connection just went stale, so retry regardless of the
+ # number of RETRIES set.
+ if not seen_bad_status_line and i == 1:
+ i = 0
+ seen_bad_status_line = True
+ conn.close()
+ conn.connect()
+ continue
+ else:
+ conn.close()
+ raise
+ except socket.timeout:
+ raise
+ except (socket.error, http.client.HTTPException):
+ conn.close()
+ if i == 0:
+ conn.close()
+ conn.connect()
+ continue
+ else:
+ raise
+ else:
+ content = b""
+ if method == "HEAD":
+ conn.close()
+ else:
+ content = response.read()
+ response = Response(response)
+ if method != "HEAD":
+ content = _decompressContent(response, content)
+
+ break
+ return (response, content)
+
+ def _request(
+ self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey,
+ ):
+ """Do the actual request using the connection object
+ and also follow one level of redirects if necessary"""
+
+ auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
+ auth = auths and sorted(auths)[0][1] or None
+ if auth:
+ auth.request(method, request_uri, headers, body)
+
+ (response, content) = self._conn_request(conn, request_uri, method, body, headers)
+
+ if auth:
+ if auth.response(response, body):
+ auth.request(method, request_uri, headers, body)
+ (response, content) = self._conn_request(conn, request_uri, method, body, headers)
+ response._stale_digest = 1
+
+ if response.status == 401:
+ for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
+ authorization.request(method, request_uri, headers, body)
+ (response, content) = self._conn_request(conn, request_uri, method, body, headers)
+ if response.status != 401:
+ self.authorizations.append(authorization)
+ authorization.response(response, body)
+ break
+
+ if self.follow_all_redirects or method in self.safe_methods or response.status in (303, 308):
+ if self.follow_redirects and response.status in self.redirect_codes:
+ # Pick out the location header and basically start from the beginning
+ # remembering first to strip the ETag header and decrement our 'depth'
+ if redirections:
+ if "location" not in response and response.status != 300:
+ raise RedirectMissingLocation(
+ _("Redirected but the response is missing a Location: header."), response, content,
+ )
+ # Fix-up relative redirects (which violate an RFC 2616 MUST)
+ if "location" in response:
+ location = response["location"]
+ (scheme, authority, path, query, fragment) = parse_uri(location)
+ if authority == None:
+ response["location"] = urllib.parse.urljoin(absolute_uri, location)
+ if response.status == 308 or (response.status == 301 and (method in self.safe_methods)):
+ response["-x-permanent-redirect-url"] = response["location"]
+ if "content-location" not in response:
+ response["content-location"] = absolute_uri
+ _updateCache(headers, response, content, self.cache, cachekey)
+ if "if-none-match" in headers:
+ del headers["if-none-match"]
+ if "if-modified-since" in headers:
+ del headers["if-modified-since"]
+ if "authorization" in headers and not self.forward_authorization_headers:
+ del headers["authorization"]
+ if "location" in response:
+ location = response["location"]
+ old_response = copy.deepcopy(response)
+ if "content-location" not in old_response:
+ old_response["content-location"] = absolute_uri
+ redirect_method = method
+ if response.status in [302, 303]:
+ redirect_method = "GET"
+ body = None
+ (response, content) = self.request(
+ location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1,
+ )
+ response.previous = old_response
+ else:
+ raise RedirectLimit(
+ "Redirected more times than redirection_limit allows.", response, content,
+ )
+ elif response.status in [200, 203] and method in self.safe_methods:
+ # Don't cache 206's since we aren't going to handle byte range requests
+ if "content-location" not in response:
+ response["content-location"] = absolute_uri
+ _updateCache(headers, response, content, self.cache, cachekey)
+
+ return (response, content)
+
+ def _normalize_headers(self, headers):
+ return _normalize_headers(headers)
+
+ # Need to catch and rebrand some exceptions
+ # Then need to optionally turn all exceptions into status codes
+ # including all socket.* and httplib.* exceptions.
+
+ def request(
+ self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
+ ):
+ """ Performs a single HTTP request.
+The 'uri' is the URI of the HTTP resource and can begin
+with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
+
+The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
+There is no restriction on the methods allowed.
+
+The 'body' is the entity body to be sent with the request. It is a string
+object.
+
+Any extra headers that are to be sent with the request should be provided in the
+'headers' dictionary.
+
+The maximum number of redirect to follow before raising an
+exception is 'redirections. The default is 5.
+
+The return value is a tuple of (response, content), the first
+being and instance of the 'Response' class, the second being
+a string that contains the response entity body.
+ """
+ conn_key = ""
+
+ try:
+ if headers is None:
+ headers = {}
+ else:
+ headers = self._normalize_headers(headers)
+
+ if "user-agent" not in headers:
+ headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
+
+ uri = iri2uri(uri)
+ # Prevent CWE-75 space injection to manipulate request via part of uri.
+ # Prevent CWE-93 CRLF injection to modify headers via part of uri.
+ uri = uri.replace(" ", "%20").replace("\r", "%0D").replace("\n", "%0A")
+
+ (scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
+
+ conn_key = scheme + ":" + authority
+ conn = self.connections.get(conn_key)
+ if conn is None:
+ if not connection_type:
+ connection_type = SCHEME_TO_CONNECTION[scheme]
+ certs = list(self.certificates.iter(authority))
+ if issubclass(connection_type, HTTPSConnectionWithTimeout):
+ if certs:
+ conn = self.connections[conn_key] = connection_type(
+ authority,
+ key_file=certs[0][0],
+ cert_file=certs[0][1],
+ timeout=self.timeout,
+ proxy_info=self.proxy_info,
+ ca_certs=self.ca_certs,
+ disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
+ tls_maximum_version=self.tls_maximum_version,
+ tls_minimum_version=self.tls_minimum_version,
+ key_password=certs[0][2],
+ )
+ else:
+ conn = self.connections[conn_key] = connection_type(
+ authority,
+ timeout=self.timeout,
+ proxy_info=self.proxy_info,
+ ca_certs=self.ca_certs,
+ disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
+ tls_maximum_version=self.tls_maximum_version,
+ tls_minimum_version=self.tls_minimum_version,
+ )
+ else:
+ conn = self.connections[conn_key] = connection_type(
+ authority, timeout=self.timeout, proxy_info=self.proxy_info
+ )
+ conn.set_debuglevel(debuglevel)
+
+ if "range" not in headers and "accept-encoding" not in headers:
+ headers["accept-encoding"] = "gzip, deflate"
+
+ info = email.message.Message()
+ cachekey = None
+ cached_value = None
+ if self.cache:
+ cachekey = defrag_uri
+ cached_value = self.cache.get(cachekey)
+ if cached_value:
+ try:
+ info, content = cached_value.split(b"\r\n\r\n", 1)
+ info = email.message_from_bytes(info)
+ for k, v in info.items():
+ if v.startswith("=?") and v.endswith("?="):
+ info.replace_header(k, str(*email.header.decode_header(v)[0]))
+ except (IndexError, ValueError):
+ self.cache.delete(cachekey)
+ cachekey = None
+ cached_value = None
+
+ if (
+ method in self.optimistic_concurrency_methods
+ and self.cache
+ and "etag" in info
+ and not self.ignore_etag
+ and "if-match" not in headers
+ ):
+ # http://www.w3.org/1999/04/Editing/
+ headers["if-match"] = info["etag"]
+
+ # https://tools.ietf.org/html/rfc7234
+ # A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location
+ # when a non-error status code is received in response to an unsafe request method.
+ if self.cache and cachekey and method not in self.safe_methods:
+ self.cache.delete(cachekey)
+
+ # Check the vary header in the cache to see if this request
+ # matches what varies in the cache.
+ if method in self.safe_methods and "vary" in info:
+ vary = info["vary"]
+ vary_headers = vary.lower().replace(" ", "").split(",")
+ for header in vary_headers:
+ key = "-varied-%s" % header
+ value = info[key]
+ if headers.get(header, None) != value:
+ cached_value = None
+ break
+
+ if (
+ self.cache
+ and cached_value
+ and (method in self.safe_methods or info["status"] == "308")
+ and "range" not in headers
+ ):
+ redirect_method = method
+ if info["status"] not in ("307", "308"):
+ redirect_method = "GET"
+ if "-x-permanent-redirect-url" in info:
+ # Should cached permanent redirects be counted in our redirection count? For now, yes.
+ if redirections <= 0:
+ raise RedirectLimit(
+ "Redirected more times than redirection_limit allows.", {}, "",
+ )
+ (response, new_content) = self.request(
+ info["-x-permanent-redirect-url"],
+ method=redirect_method,
+ headers=headers,
+ redirections=redirections - 1,
+ )
+ response.previous = Response(info)
+ response.previous.fromcache = True
+ else:
+ # Determine our course of action:
+ # Is the cached entry fresh or stale?
+ # Has the client requested a non-cached response?
+ #
+ # There seems to be three possible answers:
+ # 1. [FRESH] Return the cache entry w/o doing a GET
+ # 2. [STALE] Do the GET (but add in cache validators if available)
+ # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
+ entry_disposition = _entry_disposition(info, headers)
+
+ if entry_disposition == "FRESH":
+ response = Response(info)
+ response.fromcache = True
+ return (response, content)
+
+ if entry_disposition == "STALE":
+ if "etag" in info and not self.ignore_etag and not "if-none-match" in headers:
+ headers["if-none-match"] = info["etag"]
+ if "last-modified" in info and not "last-modified" in headers:
+ headers["if-modified-since"] = info["last-modified"]
+ elif entry_disposition == "TRANSPARENT":
+ pass
+
+ (response, new_content) = self._request(
+ conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
+ )
+
+ if response.status == 304 and method == "GET":
+ # Rewrite the cache entry with the new end-to-end headers
+ # Take all headers that are in response
+ # and overwrite their values in info.
+ # unless they are hop-by-hop, or are listed in the connection header.
+
+ for key in _get_end2end_headers(response):
+ info[key] = response[key]
+ merged_response = Response(info)
+ if hasattr(response, "_stale_digest"):
+ merged_response._stale_digest = response._stale_digest
+ _updateCache(headers, merged_response, content, self.cache, cachekey)
+ response = merged_response
+ response.status = 200
+ response.fromcache = True
+
+ elif response.status == 200:
+ content = new_content
+ else:
+ self.cache.delete(cachekey)
+ content = new_content
+ else:
+ cc = _parse_cache_control(headers)
+ if "only-if-cached" in cc:
+ info["status"] = "504"
+ response = Response(info)
+ content = b""
+ else:
+ (response, content) = self._request(
+ conn, authority, uri, request_uri, method, body, headers, redirections, cachekey,
+ )
+ except Exception as e:
+ is_timeout = isinstance(e, socket.timeout)
+ if is_timeout:
+ conn = self.connections.pop(conn_key, None)
+ if conn:
+ conn.close()
+
+ if self.force_exception_to_status_code:
+ if isinstance(e, HttpLib2ErrorWithResponse):
+ response = e.response
+ content = e.content
+ response.status = 500
+ response.reason = str(e)
+ elif isinstance(e, socket.timeout):
+ content = b"Request Timeout"
+ response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),})
+ response.reason = "Request Timeout"
+ else:
+ content = str(e).encode("utf-8")
+ response = Response({"content-type": "text/plain", "status": "400", "content-length": len(content),})
+ response.reason = "Bad Request"
+ else:
+ raise
+
+ return (response, content)
+
+
+class Response(dict):
+ """An object more like email.message than httplib.HTTPResponse."""
+
+ """Is this response from our local cache"""
+ fromcache = False
+ """HTTP protocol version used by server.
+
+ 10 for HTTP/1.0, 11 for HTTP/1.1.
+ """
+ version = 11
+
+ "Status code returned by server. "
+ status = 200
+ """Reason phrase returned by server."""
+ reason = "Ok"
+
+ previous = None
+
+ def __init__(self, info):
+ # info is either an email.message or
+ # an httplib.HTTPResponse object.
+ if isinstance(info, http.client.HTTPResponse):
+ for key, value in info.getheaders():
+ key = key.lower()
+ prev = self.get(key)
+ if prev is not None:
+ value = ", ".join((prev, value))
+ self[key] = value
+ self.status = info.status
+ self["status"] = str(self.status)
+ self.reason = info.reason
+ self.version = info.version
+ elif isinstance(info, email.message.Message):
+ for key, value in list(info.items()):
+ self[key.lower()] = value
+ self.status = int(self["status"])
+ else:
+ for key, value in info.items():
+ self[key.lower()] = value
+ self.status = int(self.get("status", self.status))
+
+ def __getattr__(self, name):
+ if name == "dict":
+ return self
+ else:
+ raise AttributeError(name)
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2de57555b8700dced688c97487b15d35968413ec
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/auth.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/auth.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cfbc1eb421fd32895c6e2bb87351a1e88539a93
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/auth.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/certs.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/certs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e96f38d77b5a303ac718a0ff185f21f9a086a64f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/certs.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06a7b17cfaf911623f4567c4ee144f5fb3e41b05
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/error.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/iri2uri.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/iri2uri.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d232f540cc666cff4458cb2975c7d9c17036198
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/iri2uri.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/__pycache__/socks.cpython-310.pyc b/venv/lib/python3.10/site-packages/httplib2/__pycache__/socks.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8be1da6a4831c2a0fee6224565cdcc37f83e3973
Binary files /dev/null and b/venv/lib/python3.10/site-packages/httplib2/__pycache__/socks.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/httplib2/auth.py b/venv/lib/python3.10/site-packages/httplib2/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8028ae2a75f3ff6e744deb01171414c1ffc4db7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/auth.py
@@ -0,0 +1,69 @@
+import base64
+import re
+
+import pyparsing as pp
+
+from .error import *
+
+
+try: # pyparsing>=3.0.0
+ downcaseTokens = pp.common.downcaseTokens
+except AttributeError:
+ downcaseTokens = pp.downcaseTokens
+
+UNQUOTE_PAIRS = re.compile(r"\\(.)")
+unquote = lambda s, l, t: UNQUOTE_PAIRS.sub(r"\1", t[0][1:-1])
+
+# https://tools.ietf.org/html/rfc7235#section-1.2
+# https://tools.ietf.org/html/rfc7235#appendix-B
+tchar = "!#$%&'*+-.^_`|~" + pp.nums + pp.alphas
+token = pp.Word(tchar).setName("token")
+token68 = pp.Combine(pp.Word("-._~+/" + pp.nums + pp.alphas) + pp.Optional(pp.Word("=").leaveWhitespace())).setName(
+ "token68"
+)
+
+quoted_string = pp.dblQuotedString.copy().setName("quoted-string").setParseAction(unquote)
+auth_param_name = token.copy().setName("auth-param-name").addParseAction(downcaseTokens)
+auth_param = auth_param_name + pp.Suppress("=") + (quoted_string | token)
+params = pp.Dict(pp.delimitedList(pp.Group(auth_param)))
+
+scheme = token("scheme")
+challenge = scheme + (params("params") | token68("token"))
+
+authentication_info = params.copy()
+www_authenticate = pp.delimitedList(pp.Group(challenge))
+
+
+def _parse_authentication_info(headers, headername="authentication-info"):
+ """https://tools.ietf.org/html/rfc7615
+ """
+ header = headers.get(headername, "").strip()
+ if not header:
+ return {}
+ try:
+ parsed = authentication_info.parseString(header)
+ except pp.ParseException as ex:
+ # print(ex.explain(ex))
+ raise MalformedHeader(headername)
+
+ return parsed.asDict()
+
+
+def _parse_www_authenticate(headers, headername="www-authenticate"):
+ """Returns a dictionary of dictionaries, one dict per auth_scheme."""
+ header = headers.get(headername, "").strip()
+ if not header:
+ return {}
+ try:
+ parsed = www_authenticate.parseString(header)
+ except pp.ParseException as ex:
+ # print(ex.explain(ex))
+ raise MalformedHeader(headername)
+
+ retval = {
+ challenge["scheme"].lower(): challenge["params"].asDict()
+ if "params" in challenge
+ else {"token": challenge.get("token")}
+ for challenge in parsed
+ }
+ return retval
diff --git a/venv/lib/python3.10/site-packages/httplib2/cacerts.txt b/venv/lib/python3.10/site-packages/httplib2/cacerts.txt
new file mode 100644
index 0000000000000000000000000000000000000000..78a444c43af0a2ed7e0e69438c2ce6cc88ff6e93
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/cacerts.txt
@@ -0,0 +1,2225 @@
+# Issuer: CN=GTE CyberTrust Global Root O=GTE Corporation OU=GTE CyberTrust Solutions, Inc.
+# Subject: CN=GTE CyberTrust Global Root O=GTE Corporation OU=GTE CyberTrust Solutions, Inc.
+# Label: "GTE CyberTrust Global Root"
+# Serial: 421
+# MD5 Fingerprint: ca:3d:d3:68:f1:03:5c:d0:32:fa:b8:2b:59:e8:5a:db
+# SHA1 Fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74
+# SHA256 Fingerprint: a5:31:25:18:8d:21:10:aa:96:4b:02:c7:b7:c6:da:32:03:17:08:94:e5:fb:71:ff:fb:66:67:d5:e6:81:0a:36
+-----BEGIN CERTIFICATE-----
+MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD
+VQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv
+bHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv
+b3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV
+UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU
+cnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds
+b2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH
+iM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS
+r41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4
+04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r
+GwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9
+3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P
+lZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/
+-----END CERTIFICATE-----
+
+# Issuer: CN=Thawte Server CA O=Thawte Consulting cc OU=Certification Services Division
+# Subject: CN=Thawte Server CA O=Thawte Consulting cc OU=Certification Services Division
+# Label: "Thawte Server CA"
+# Serial: 1
+# MD5 Fingerprint: c5:70:c4:a2:ed:53:78:0c:c8:10:53:81:64:cb:d0:1d
+# SHA1 Fingerprint: 23:e5:94:94:51:95:f2:41:48:03:b4:d5:64:d2:a3:a3:f5:d8:8b:8c
+# SHA256 Fingerprint: b4:41:0b:73:e2:e6:ea:ca:47:fb:c4:2f:8f:a4:01:8a:f4:38:1d:c5:4c:fa:a8:44:50:46:1e:ed:09:45:4d:e9
+-----BEGIN CERTIFICATE-----
+MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkEx
+FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD
+VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv
+biBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEm
+MCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wHhcNOTYwODAx
+MDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT
+DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3
+dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNl
+cyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3
+DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQAD
+gY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl/Kj0R1HahbUgdJSGHg91
+yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg71CcEJRCX
+L+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGj
+EzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG
+7oWDTSEwjsrZqG9JGubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6e
+QNuozDJ0uW8NxuOzRAvZim+aKZuZGCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZ
+qdq5snUb9kLy78fyGPmJvKP/iiMucEc=
+-----END CERTIFICATE-----
+
+# Issuer: CN=Thawte Premium Server CA O=Thawte Consulting cc OU=Certification Services Division
+# Subject: CN=Thawte Premium Server CA O=Thawte Consulting cc OU=Certification Services Division
+# Label: "Thawte Premium Server CA"
+# Serial: 1
+# MD5 Fingerprint: 06:9f:69:79:16:66:90:02:1b:8c:8c:a2:c3:07:6f:3a
+# SHA1 Fingerprint: 62:7f:8d:78:27:65:63:99:d2:7d:7f:90:44:c9:fe:b3:f3:3e:fa:9a
+# SHA256 Fingerprint: ab:70:36:36:5c:71:54:aa:29:c2:c2:9f:5d:41:91:16:3b:16:2a:22:25:01:13:57:d5:6d:07:ff:a7:bc:1f:72
+-----BEGIN CERTIFICATE-----
+MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkEx
+FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD
+VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv
+biBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UEAxMYVGhhd3RlIFByZW1pdW0gU2Vy
+dmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZlckB0aGF3dGUuY29t
+MB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYTAlpB
+MRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsG
+A1UEChMUVGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRp
+b24gU2VydmljZXMgRGl2aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNl
+cnZlciBDQTEoMCYGCSqGSIb3DQEJARYZcHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNv
+bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2aovXwlue2oFBYo847kkE
+VdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIhUdib0GfQ
+ug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMR
+uHM/qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG
+9w0BAQQFAAOBgQAmSCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUI
+hfzJATj/Tb7yFkJD57taRvvBxhEf8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JM
+pAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7tUCemDaYj+bvLpgcUQg==
+-----END CERTIFICATE-----
+
+# Issuer: O=Equifax OU=Equifax Secure Certificate Authority
+# Subject: O=Equifax OU=Equifax Secure Certificate Authority
+# Label: "Equifax Secure CA"
+# Serial: 903804111
+# MD5 Fingerprint: 67:cb:9d:c0:13:24:8a:82:9b:b2:17:1e:d1:1b:ec:d4
+# SHA1 Fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a
+# SHA256 Fingerprint: 08:29:7a:40:47:db:a2:36:80:c7:31:db:6e:31:76:53:ca:78:48:e1:be:bd:3a:0b:01:79:a7:07:f9:2c:f1:78
+-----BEGIN CERTIFICATE-----
+MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV
+UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy
+dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1
+MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx
+dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B
+AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f
+BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A
+cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC
+AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ
+MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm
+aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw
+ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj
+IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF
+MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA
+A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y
+7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh
+1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4
+-----END CERTIFICATE-----
+
+# Issuer: O=VeriSign, Inc. OU=Class 3 Public Primary Certification Authority - G2/(c) 1998 VeriSign, Inc. - For authorized use only/VeriSign Trust Network
+# Subject: O=VeriSign, Inc. OU=Class 3 Public Primary Certification Authority - G2/(c) 1998 VeriSign, Inc. - For authorized use only/VeriSign Trust Network
+# Label: "Verisign Class 3 Public Primary Certification Authority - G2"
+# Serial: 167285380242319648451154478808036881606
+# MD5 Fingerprint: a2:33:9b:4c:74:78:73:d4:6c:e7:c1:f3:8d:cb:5c:e9
+# SHA1 Fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f
+# SHA256 Fingerprint: 83:ce:3c:12:29:68:8a:59:3d:48:5f:81:97:3c:0f:91:95:43:1e:da:37:cc:5e:36:43:0e:79:c7:a8:88:63:8b
+-----BEGIN CERTIFICATE-----
+MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJ
+BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xh
+c3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcy
+MTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp
+emVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMB4X
+DTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVTMRcw
+FQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMg
+UHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEo
+YykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5
+MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEB
+AQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCOFoUgRm1HP9SFIIThbbP4
+pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71lSk8UOg0
+13gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwID
+AQABMA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSk
+U01UbSuvDV1Ai2TT1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7i
+F6YM40AIOw7n60RzKprxaZLvcRTDOaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpY
+oJ2daZH9
+-----END CERTIFICATE-----
+
+# Issuer: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA
+# Subject: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA
+# Label: "GlobalSign Root CA"
+# Serial: 4835703278459707669005204
+# MD5 Fingerprint: 3e:45:52:15:09:51:92:e1:b7:5d:37:9f:b1:87:29:8a
+# SHA1 Fingerprint: b1:bc:96:8b:d4:f4:9d:62:2a:a8:9a:81:f2:15:01:52:a4:1d:82:9c
+# SHA256 Fingerprint: eb:d4:10:40:e4:bb:3e:c7:42:c9:e3:81:d3:1e:f2:a4:1a:48:b6:68:5c:96:e7:ce:f3:c1:df:6c:d4:33:1c:99
+-----BEGIN CERTIFICATE-----
+MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG
+A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv
+b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw
+MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i
+YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT
+aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ
+jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp
+xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp
+1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG
+snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ
+U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8
+9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E
+BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B
+AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz
+yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE
+38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP
+AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad
+DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME
+HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
+-----END CERTIFICATE-----
+
+# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R2
+# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R2
+# Label: "GlobalSign Root CA - R2"
+# Serial: 4835703278459682885658125
+# MD5 Fingerprint: 94:14:77:7e:3e:5e:fd:8f:30:bd:41:b0:cf:e7:d0:30
+# SHA1 Fingerprint: 75:e0:ab:b6:13:85:12:27:1c:04:f8:5f:dd:de:38:e4:b7:24:2e:fe
+# SHA256 Fingerprint: ca:42:dd:41:74:5f:d0:b8:1e:b9:02:36:2c:f9:d8:bf:71:9d:a1:bd:1b:1e:fc:94:6f:5b:4c:99:f4:2c:1b:9e
+-----BEGIN CERTIFICATE-----
+MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G
+A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp
+Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1
+MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG
+A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
+hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL
+v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8
+eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq
+tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd
+C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa
+zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB
+mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH
+V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n
+bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG
+3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs
+J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO
+291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS
+ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd
+AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
+TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
+-----END CERTIFICATE-----
+
+# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 1 Policy Validation Authority
+# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 1 Policy Validation Authority
+# Label: "ValiCert Class 1 VA"
+# Serial: 1
+# MD5 Fingerprint: 65:58:ab:15:ad:57:6c:1e:a8:a7:b5:69:ac:bf:ff:eb
+# SHA1 Fingerprint: e5:df:74:3c:b6:01:c4:9b:98:43:dc:ab:8c:e8:6a:81:10:9f:e4:8e
+# SHA256 Fingerprint: f4:c1:49:55:1a:30:13:a3:5b:c7:bf:fe:17:a7:f3:44:9b:c1:ab:5b:5a:0a:e7:4b:06:c2:3b:90:00:4c:01:04
+-----BEGIN CERTIFICATE-----
+MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0
+IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz
+BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y
+aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG
+9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIyMjM0OFoXDTE5MDYy
+NTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y
+azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
+YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw
+Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl
+cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9Y
+LqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIiGQj4/xEjm84H9b9pGib+
+TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCmDuJWBQ8Y
+TfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0
+LBwGlN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLW
+I8sogTLDAHkY7FkXicnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPw
+nXS3qT6gpf+2SQMT2iLM7XGCK5nPOrf1LXLI
+-----END CERTIFICATE-----
+
+# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 2 Policy Validation Authority
+# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 2 Policy Validation Authority
+# Label: "ValiCert Class 2 VA"
+# Serial: 1
+# MD5 Fingerprint: a9:23:75:9b:ba:49:36:6e:31:c2:db:f2:e7:66:ba:87
+# SHA1 Fingerprint: 31:7a:2a:d0:7f:2b:33:5e:f5:a1:c3:4e:4b:57:e8:b7:d8:f1:fc:a6
+# SHA256 Fingerprint: 58:d0:17:27:9c:d4:dc:63:ab:dd:b1:96:a6:c9:90:6c:30:c4:e0:87:83:ea:e8:c1:60:99:54:d6:93:55:59:6b
+-----BEGIN CERTIFICATE-----
+MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0
+IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz
+BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y
+aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG
+9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMTk1NFoXDTE5MDYy
+NjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y
+azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
+YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw
+Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl
+cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOOnHK5avIWZJV16vY
+dA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVCCSRrCl6zfN1SLUzm1NZ9
+WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7RfZHM047QS
+v4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9v
+UJSZSWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTu
+IYEZoDJJKPTEjlbVUjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwC
+W/POuZ6lcg5Ktz885hZo+L7tdEy8W9ViH0Pd
+-----END CERTIFICATE-----
+
+# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 3 Policy Validation Authority
+# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 3 Policy Validation Authority
+# Label: "RSA Root Certificate 1"
+# Serial: 1
+# MD5 Fingerprint: a2:6f:53:b7:ee:40:db:4a:68:e7:fa:18:d9:10:4b:72
+# SHA1 Fingerprint: 69:bd:8c:f4:9c:d3:00:fb:59:2e:17:93:ca:55:6a:f3:ec:aa:35:fb
+# SHA256 Fingerprint: bc:23:f9:8a:31:3c:b9:2d:e3:bb:fc:3a:5a:9f:44:61:ac:39:49:4c:4a:e1:5a:9e:9d:f1:31:e9:9b:73:01:9a
+-----BEGIN CERTIFICATE-----
+MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0
+IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz
+BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y
+aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG
+9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMjIzM1oXDTE5MDYy
+NjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y
+azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
+YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw
+Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl
+cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjmFGWHOjVsQaBalfD
+cnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td3zZxFJmP3MKS8edgkpfs
+2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89HBFx1cQqY
+JJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliE
+Zwgs3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJ
+n0WuPIqpsHEzXcjFV9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/A
+PhmcGcwTTYJBtYze4D1gCCAPRX5ron+jjBXu
+-----END CERTIFICATE-----
+
+# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only
+# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only
+# Label: "Verisign Class 3 Public Primary Certification Authority - G3"
+# Serial: 206684696279472310254277870180966723415
+# MD5 Fingerprint: cd:68:b6:a7:c7:c4:ce:75:e0:1d:4f:57:44:61:92:09
+# SHA1 Fingerprint: 13:2d:0d:45:53:4b:69:97:cd:b2:d5:c3:39:e2:55:76:60:9b:5c:c6
+# SHA256 Fingerprint: eb:04:cf:5e:b1:f3:9a:fa:76:2f:2b:b1:20:f2:96:cb:a5:20:c1:b9:7d:b1:58:95:65:b8:1c:b9:a1:7b:72:44
+-----BEGIN CERTIFICATE-----
+MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQsw
+CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZl
+cmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWdu
+LCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlT
+aWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
+dHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQswCQYD
+VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlT
+aWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJ
+bmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu
+IENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg
+LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMu6nFL8eB8aHm8b
+N3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1EUGO+i2t
+KmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGu
+kxUccLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBm
+CC+Vk7+qRy+oRpfwEuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJ
+Xwzw3sJ2zq/3avL6QaaiMxTJ5Xpj055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWu
+imi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAERSWwauSCPc/L8my/uRan2Te
+2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5fj267Cz3qWhMe
+DGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC
+/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565p
+F4ErWjfJXir0xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGt
+TxzhT5yvDwyd93gN2PQ1VoDat20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=VeriSign Class 4 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only
+# Subject: CN=VeriSign Class 4 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only
+# Label: "Verisign Class 4 Public Primary Certification Authority - G3"
+# Serial: 314531972711909413743075096039378935511
+# MD5 Fingerprint: db:c8:f2:27:2e:b1:ea:6a:29:23:5d:fe:56:3e:33:df
+# SHA1 Fingerprint: c8:ec:8c:87:92:69:cb:4b:ab:39:e9:8d:7e:57:67:f3:14:95:73:9d
+# SHA256 Fingerprint: e3:89:36:0d:0f:db:ae:b3:d2:50:58:4b:47:30:31:4e:22:2f:39:c1:56:a0:20:14:4e:8d:96:05:61:79:15:06
+-----BEGIN CERTIFICATE-----
+MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQsw
+CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZl
+cmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWdu
+LCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlT
+aWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
+dHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQswCQYD
+VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlT
+aWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJ
+bmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu
+IENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg
+LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK3LpRFpxlmr8Y+1
+GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaStBO3IFsJ
++mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0Gbd
+U6LM8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLm
+NxdLMEYH5IBtptiWLugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XY
+ufTsgsbSPZUd5cBPhMnZo0QoBmrXRazwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/
+ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAj/ola09b5KROJ1WrIhVZPMq1
+CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXttmhwwjIDLk5Mq
+g6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm
+fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c
+2NU8Qh0XwRJdRTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/
+bLvSHgCwIe34QWKCudiyxLtGUPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg==
+-----END CERTIFICATE-----
+
+# Issuer: CN=Entrust.net Secure Server Certification Authority O=Entrust.net OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited
+# Subject: CN=Entrust.net Secure Server Certification Authority O=Entrust.net OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited
+# Label: "Entrust.net Secure Server CA"
+# Serial: 927650371
+# MD5 Fingerprint: df:f2:80:73:cc:f1:e6:61:73:fc:f5:42:e9:c5:7c:ee
+# SHA1 Fingerprint: 99:a6:9b:e6:1a:fe:88:6b:4d:2b:82:00:7c:b8:54:fc:31:7e:15:39
+# SHA256 Fingerprint: 62:f2:40:27:8c:56:4c:4d:d8:bf:7d:9d:4f:6f:36:6e:a8:94:d2:2f:5f:34:d9:89:a9:83:ac:ec:2f:ff:ed:50
+-----BEGIN CERTIFICATE-----
+MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMC
+VVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5u
+ZXQvQ1BTIGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMc
+KGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDE6MDgGA1UEAxMxRW50cnVzdC5u
+ZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05OTA1
+MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIGA1UE
+ChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5j
+b3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF
+bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUg
+U2VydmVyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUA
+A4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQaO2f55M28Qpku0f1BBc/
+I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5gXpa0zf3
+wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OC
+AdcwggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHb
+oIHYpIHVMIHSMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5
+BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1p
+dHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1pdGVk
+MTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRp
+b24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu
+dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0
+MFqBDzIwMTkwNTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8Bdi
+E1U9s/8KAGv7UISX8+1i0BowHQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAa
+MAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI
+hvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyNEwr75Ji174z4xRAN
+95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9n9cd
+2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI=
+-----END CERTIFICATE-----
+
+# Issuer: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited
+# Subject: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited
+# Label: "Entrust.net Premium 2048 Secure Server CA"
+# Serial: 946059622
+# MD5 Fingerprint: ba:21:ea:20:d6:dd:db:8f:c1:57:8b:40:ad:a1:fc:fc
+# SHA1 Fingerprint: 80:1d:62:d0:7b:44:9d:5c:5c:03:5c:98:ea:61:fa:44:3c:2a:58:fe
+# SHA256 Fingerprint: d1:c3:39:ea:27:84:eb:87:0f:93:4f:c5:63:4e:4a:a9:ad:55:05:01:64:01:f2:64:65:d3:7a:57:46:63:35:9f
+-----BEGIN CERTIFICATE-----
+MIIEXDCCA0SgAwIBAgIEOGO5ZjANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML
+RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp
+bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5
+IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp
+ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0xOTEy
+MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
+LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
+YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
+A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
+K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe
+sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX
+MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT
+XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/
+HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH
+4QIDAQABo3QwcjARBglghkgBhvhCAQEEBAMCAAcwHwYDVR0jBBgwFoAUVeSB0RGA
+vtiJuQijMfmhJAkWuXAwHQYDVR0OBBYEFFXkgdERgL7YibkIozH5oSQJFrlwMB0G
+CSqGSIb2fQdBAAQQMA4bCFY1LjA6NC4wAwIEkDANBgkqhkiG9w0BAQUFAAOCAQEA
+WUesIYSKF8mciVMeuoCFGsY8Tj6xnLZ8xpJdGGQC49MGCBFhfGPjK50xA3B20qMo
+oPS7mmNz7W3lKtvtFKkrxjYR0CvrB4ul2p5cGZ1WEvVUKcgF7bISKo30Axv/55IQ
+h7A6tcOdBTcSo8f0FbnVpDkWm1M6I5HxqIKiaohowXkCIryqptau37AUX7iH0N18
+f3v/rxzP5tsHrV7bhZ3QKw0z2wTR5klAEyt2+z7pnIkPFc4YsIV4IU9rTw76NmfN
+B/L/CNDi3tm/Kq+4h4YhPATKt5Rof8886ZjXOP/swNlQ8C5LWK5Gb9Auw2DaclVy
+vUxFnmG6v4SBkgPR0ml8xQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust
+# Subject: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust
+# Label: "Baltimore CyberTrust Root"
+# Serial: 33554617
+# MD5 Fingerprint: ac:b6:94:a5:9c:17:e0:d7:91:52:9b:b1:97:06:a6:e4
+# SHA1 Fingerprint: d4:de:20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74
+# SHA256 Fingerprint: 16:af:57:a9:f6:76:b0:ab:12:60:95:aa:5e:ba:de:f2:2a:b3:11:19:d6:44:ac:95:cd:4b:93:db:f3:f2:6a:eb
+-----BEGIN CERTIFICATE-----
+MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ
+RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD
+VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX
+DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y
+ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy
+VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr
+mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr
+IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK
+mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu
+XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy
+dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye
+jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1
+BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3
+DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92
+9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx
+jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0
+Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz
+ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS
+R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp
+-----END CERTIFICATE-----
+
+# Issuer: CN=Equifax Secure Global eBusiness CA-1 O=Equifax Secure Inc.
+# Subject: CN=Equifax Secure Global eBusiness CA-1 O=Equifax Secure Inc.
+# Label: "Equifax Secure Global eBusiness CA"
+# Serial: 1
+# MD5 Fingerprint: 8f:5d:77:06:27:c4:98:3c:5b:93:78:e7:d7:7d:9b:cc
+# SHA1 Fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45
+# SHA256 Fingerprint: 5f:0b:62:ea:b5:e3:53:ea:65:21:65:16:58:fb:b6:53:59:f4:43:28:0a:4a:fb:d1:04:d7:7d:10:f9:f0:4c:07
+-----BEGIN CERTIFICATE-----
+MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEc
+MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBT
+ZWN1cmUgR2xvYmFsIGVCdXNpbmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIw
+MDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0VxdWlmYXggU2Vj
+dXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEdsb2JhbCBlQnVzaW5l
+c3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRVPEnC
+UdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc
+58O/gGzNqfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/
+o5brhTMhHD4ePmBudpxnhcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAH
+MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUvqigdHJQa0S3ySPY+6j/s1dr
+aGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hsMA0GCSqGSIb3DQEBBAUA
+A4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okENI7SS+RkA
+Z70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv
+8qIYNMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV
+-----END CERTIFICATE-----
+
+# Issuer: CN=Equifax Secure eBusiness CA-1 O=Equifax Secure Inc.
+# Subject: CN=Equifax Secure eBusiness CA-1 O=Equifax Secure Inc.
+# Label: "Equifax Secure eBusiness CA 1"
+# Serial: 4
+# MD5 Fingerprint: 64:9c:ef:2e:44:fc:c6:8f:52:07:d0:51:73:8f:cb:3d
+# SHA1 Fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41
+# SHA256 Fingerprint: cf:56:ff:46:a4:a1:86:10:9d:d9:65:84:b5:ee:b5:8a:51:0c:42:75:b0:e5:f9:4f:40:bb:ae:86:5e:19:f6:73
+-----BEGIN CERTIFICATE-----
+MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEc
+MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBT
+ZWN1cmUgZUJ1c2luZXNzIENBLTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQw
+MDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5j
+LjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENBLTEwgZ8wDQYJ
+KoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ1MRo
+RvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBu
+WqDZQu4aIZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKw
+Env+j6YDAgMBAAGjZjBkMBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTAD
+AQH/MB8GA1UdIwQYMBaAFEp4MlIR21kWNl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRK
+eDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQFAAOBgQB1W6ibAxHm6VZM
+zfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5lSE/9dR+
+WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN
+/Bf+KpYrtWKmpj29f5JZzVoqgrI3eQ==
+-----END CERTIFICATE-----
+
+# Issuer: O=Equifax Secure OU=Equifax Secure eBusiness CA-2
+# Subject: O=Equifax Secure OU=Equifax Secure eBusiness CA-2
+# Label: "Equifax Secure eBusiness CA 2"
+# Serial: 930140085
+# MD5 Fingerprint: aa:bf:bf:64:97:da:98:1d:6f:c6:08:3a:95:70:33:ca
+# SHA1 Fingerprint: 39:4f:f6:85:0b:06:be:52:e5:18:56:cc:10:e1:80:e8:82:b3:85:cc
+# SHA256 Fingerprint: 2f:27:4e:48:ab:a4:ac:7b:76:59:33:10:17:75:50:6d:c3:0e:e3:8e:f6:ac:d5:c0:49:32:cf:e0:41:23:42:20
+-----BEGIN CERTIFICATE-----
+MIIDIDCCAomgAwIBAgIEN3DPtTANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV
+UzEXMBUGA1UEChMORXF1aWZheCBTZWN1cmUxJjAkBgNVBAsTHUVxdWlmYXggU2Vj
+dXJlIGVCdXNpbmVzcyBDQS0yMB4XDTk5MDYyMzEyMTQ0NVoXDTE5MDYyMzEyMTQ0
+NVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkVxdWlmYXggU2VjdXJlMSYwJAYD
+VQQLEx1FcXVpZmF4IFNlY3VyZSBlQnVzaW5lc3MgQ0EtMjCBnzANBgkqhkiG9w0B
+AQEFAAOBjQAwgYkCgYEA5Dk5kx5SBhsoNviyoynF7Y6yEb3+6+e0dMKP/wXn2Z0G
+vxLIPw7y1tEkshHe0XMJitSxLJgJDR5QRrKDpkWNYmi7hRsgcDKqQM2mll/EcTc/
+BPO3QSQ5BxoeLmFYoBIL5aXfxavqN3HMHMg3OrmXUqesxWoklE6ce8/AatbfIb0C
+AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEX
+MBUGA1UEChMORXF1aWZheCBTZWN1cmUxJjAkBgNVBAsTHUVxdWlmYXggU2VjdXJl
+IGVCdXNpbmVzcyBDQS0yMQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTkw
+NjIzMTIxNDQ1WjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUUJ4L6q9euSBIplBq
+y/3YIHqngnYwHQYDVR0OBBYEFFCeC+qvXrkgSKZQasv92CB6p4J2MAwGA1UdEwQF
+MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA
+A4GBAAyGgq3oThr1jokn4jVYPSm0B482UJW/bsGe68SQsoWou7dC4A8HOd/7npCy
+0cE+U58DRLB+S/Rv5Hwf5+Kx5Lia78O9zt4LMjTZ3ijtM2vE1Nc9ElirfQkty3D1
+E4qUoSek1nDFbZS1yX2doNLGCEnZZpum0/QL3MUmV+GRMOrN
+-----END CERTIFICATE-----
+
+# Issuer: CN=AddTrust Class 1 CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Subject: CN=AddTrust Class 1 CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Label: "AddTrust Low-Value Services Root"
+# Serial: 1
+# MD5 Fingerprint: 1e:42:95:02:33:92:6b:b9:5f:c0:7f:da:d6:b2:4b:fc
+# SHA1 Fingerprint: cc:ab:0e:a0:4c:23:01:d6:69:7b:dd:37:9f:cd:12:eb:24:e3:94:9d
+# SHA256 Fingerprint: 8c:72:09:27:9a:c0:4e:27:5e:16:d0:7f:d3:b7:75:e8:01:54:b5:96:80:46:e3:1f:52:dd:25:76:63:24:e9:a7
+-----BEGIN CERTIFICATE-----
+MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEU
+MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3
+b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMw
+MTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
+QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYD
+VQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUA
+A4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ul
+CDtbKRY654eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6n
+tGO0/7Gcrjyvd7ZWxbWroulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyl
+dI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1Zmne3yzxbrww2ywkEtvrNTVokMsAsJch
+PXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJuiGMx1I4S+6+JNM3GOGvDC
++Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8wHQYDVR0O
+BBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8E
+BTADAQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBl
+MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFk
+ZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENB
+IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxtZBsfzQ3duQH6lmM0MkhHma6X
+7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0PhiVYrqW9yTkkz
+43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY
+eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJl
+pz/+0WatC7xrmYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOA
+WiFeIc9TVPC6b4nbqKqVz4vjccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AddTrust External CA Root O=AddTrust AB OU=AddTrust External TTP Network
+# Subject: CN=AddTrust External CA Root O=AddTrust AB OU=AddTrust External TTP Network
+# Label: "AddTrust External Root"
+# Serial: 1
+# MD5 Fingerprint: 1d:35:54:04:85:78:b0:3f:42:42:4d:bf:20:73:0a:3f
+# SHA1 Fingerprint: 02:fa:f3:e2:91:43:54:68:60:78:57:69:4d:f5:e4:5b:68:85:18:68
+# SHA256 Fingerprint: 68:7f:a4:51:38:22:78:ff:f0:c8:b1:1f:8d:43:d5:76:67:1c:6e:b2:bc:ea:b4:13:fb:83:d9:65:d0:6d:2f:f2
+-----BEGIN CERTIFICATE-----
+MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU
+MBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFs
+IFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290
+MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFowbzELMAkGA1UEBhMCU0Ux
+FDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRUcnVzdCBFeHRlcm5h
+bCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0EgUm9v
+dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvt
+H7xsD821+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9
+uMq/NzgtHj6RQa1wVsfwTz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzX
+mk6vBbOmcZSccbNQYArHE504B4YCqOmoaSYYkKtMsE8jqzpPhNjfzp/haW+710LX
+a0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy2xSoRcRdKn23tNbE7qzN
+E0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv77+ldU9U0
+WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYD
+VR0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0
+Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU
+cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx
+IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN
+AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH
+YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5
+6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC
+Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX
+c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a
+mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AddTrust Public CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Subject: CN=AddTrust Public CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Label: "AddTrust Public Services Root"
+# Serial: 1
+# MD5 Fingerprint: c1:62:3e:23:c5:82:73:9c:03:59:4b:2b:e9:77:49:7f
+# SHA1 Fingerprint: 2a:b6:28:48:5e:78:fb:f3:ad:9e:79:10:dd:6b:df:99:72:2c:96:e5
+# SHA256 Fingerprint: 07:91:ca:07:49:b2:07:82:aa:d3:c7:d7:bd:0c:df:c9:48:58:35:84:3e:b2:d7:99:60:09:ce:43:ab:6c:69:27
+-----BEGIN CERTIFICATE-----
+MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEU
+MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3
+b3JrMSAwHgYDVQQDExdBZGRUcnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAx
+MDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtB
+ZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIDAeBgNV
+BAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOC
+AQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV
+6tsfSlbunyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nX
+GCwwfQ56HmIexkvA/X1id9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnP
+dzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSGAa2Il+tmzV7R/9x98oTaunet3IAIx6eH
+1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAwHM+A+WD+eeSI8t0A65RF
+62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0GA1UdDgQW
+BBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUw
+AwEB/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDEL
+MAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRU
+cnVzdCBUVFAgTmV0d29yazEgMB4GA1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJv
+b3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4JNojVhaTdt02KLmuG7jD8WS6
+IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL+YPoRNWyQSW/
+iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao
+GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh
+4SINhwBk/ox9Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQm
+XiLsks3/QppEIW1cxeMiHV9HEufOX1362KqxMy3ZdvJOOjMMK7MtkAY=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AddTrust Qualified CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Subject: CN=AddTrust Qualified CA Root O=AddTrust AB OU=AddTrust TTP Network
+# Label: "AddTrust Qualified Certificates Root"
+# Serial: 1
+# MD5 Fingerprint: 27:ec:39:47:cd:da:5a:af:e2:9a:01:65:21:a9:4c:bb
+# SHA1 Fingerprint: 4d:23:78:ec:91:95:39:b5:00:7f:75:8f:03:3b:21:1e:c5:4d:8b:cf
+# SHA256 Fingerprint: 80:95:21:08:05:db:4b:bc:35:5e:44:28:d8:fd:6e:c2:cd:e3:ab:5f:b9:7a:99:42:98:8e:b8:f4:dc:d0:60:16
+-----BEGIN CERTIFICATE-----
+MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEU
+MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3
+b3JrMSMwIQYDVQQDExpBZGRUcnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1
+MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcxCzAJBgNVBAYTAlNFMRQwEgYDVQQK
+EwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIzAh
+BgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG9w0B
+AQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwq
+xBb/4Oxx64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G
+87B4pfYOQnrjfxvM0PC3KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i
+2O+tCBGaKZnhqkRFmhJePp1tUvznoD1oL/BLcHwTOK28FSXx1s6rosAx1i+f4P8U
+WfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GRwVY18BTcZTYJbqukB8c1
+0cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HUMIHRMB0G
+A1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0T
+AQH/BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6Fr
+pGkwZzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQL
+ExRBZGRUcnVzdCBUVFAgTmV0d29yazEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlm
+aWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBABmrder4i2VhlRO6aQTv
+hsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxGGuoYQ992zPlm
+hpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X
+dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3
+P6CxB9bpT9zeRXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9Y
+iQBCYz95OdBEsIJuQRno3eDBiFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5no
+xqE=
+-----END CERTIFICATE-----
+
+# Issuer: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc.
+# Subject: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc.
+# Label: "Entrust Root Certification Authority"
+# Serial: 1164660820
+# MD5 Fingerprint: d6:a5:c3:ed:5d:dd:3e:00:c1:3d:87:92:1f:1d:3f:e4
+# SHA1 Fingerprint: b3:1e:b1:b7:40:e3:6c:84:02:da:dc:37:d4:4d:f5:d4:67:49:52:f9
+# SHA256 Fingerprint: 73:c1:76:43:4f:1b:c6:d5:ad:f4:5b:0e:76:e7:27:28:7c:8d:e5:76:16:c1:e6:e6:14:1a:2b:2c:bc:7d:8e:4c
+-----BEGIN CERTIFICATE-----
+MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC
+VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0
+Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW
+KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl
+cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw
+NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw
+NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy
+ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV
+BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ
+KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo
+Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4
+4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9
+KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI
+rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi
+94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB
+sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi
+gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo
+kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE
+vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA
+A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t
+O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua
+AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP
+9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/
+eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m
+0vdXcDazv/wor3ElhVsT/h5/WrQ8
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Global CA O=GeoTrust Inc.
+# Subject: CN=GeoTrust Global CA O=GeoTrust Inc.
+# Label: "GeoTrust Global CA"
+# Serial: 144470
+# MD5 Fingerprint: f7:75:ab:29:fb:51:4e:b7:77:5e:ff:05:3c:99:8e:f5
+# SHA1 Fingerprint: de:28:f4:a4:ff:e5:b9:2f:a3:c5:03:d1:a3:49:a7:f9:96:2a:82:12
+# SHA256 Fingerprint: ff:85:6a:2d:25:1d:cd:88:d3:66:56:f4:50:12:67:98:cf:ab:aa:de:40:79:9c:72:2d:e4:d2:b5:db:36:a7:3a
+-----BEGIN CERTIFICATE-----
+MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
+MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
+YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG
+EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg
+R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9
+9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq
+fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv
+iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU
+1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+
+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW
+MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA
+ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l
+uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn
+Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS
+tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF
+PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un
+hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV
+5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw==
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Global CA 2 O=GeoTrust Inc.
+# Subject: CN=GeoTrust Global CA 2 O=GeoTrust Inc.
+# Label: "GeoTrust Global CA 2"
+# Serial: 1
+# MD5 Fingerprint: 0e:40:a7:6c:de:03:5d:8f:d1:0f:e4:d1:8d:f9:6c:a9
+# SHA1 Fingerprint: a9:e9:78:08:14:37:58:88:f2:05:19:b0:6d:2b:0d:2b:60:16:90:7d
+# SHA256 Fingerprint: ca:2d:82:a0:86:77:07:2f:8a:b6:76:4f:f0:35:67:6c:fe:3e:5e:32:5e:01:21:72:df:3f:92:09:6d:b7:9b:85
+-----BEGIN CERTIFICATE-----
+MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEW
+MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFs
+IENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQG
+EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3Qg
+R2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDvPE1A
+PRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/NTL8
+Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hL
+TytCOb1kLUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL
+5mkWRxHCJ1kDs6ZgwiFAVvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7
+S4wMcoKK+xfNAGw6EzywhIdLFnopsk/bHdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe
+2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE
+FHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNHK266ZUap
+EBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6td
+EPx7srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv
+/NgdRN3ggX+d6YvhZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywN
+A0ZF66D0f0hExghAzN4bcLUprbqLOzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0
+abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkCx1YAzUm5s2x7UwQa4qjJqhIF
+I8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqFH4z1Ir+rzoPz
+4iIprn2DQKi6bA==
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Universal CA O=GeoTrust Inc.
+# Subject: CN=GeoTrust Universal CA O=GeoTrust Inc.
+# Label: "GeoTrust Universal CA"
+# Serial: 1
+# MD5 Fingerprint: 92:65:58:8b:a2:1a:31:72:73:68:5c:b4:a5:7a:07:48
+# SHA1 Fingerprint: e6:21:f3:35:43:79:05:9a:4b:68:30:9d:8a:2f:74:22:15:87:ec:79
+# SHA256 Fingerprint: a0:45:9b:9f:63:b2:25:59:f5:fa:5d:4c:6d:b3:f9:f7:2f:f1:93:42:03:35:78:f0:73:bf:1d:1b:46:cb:b9:12
+-----BEGIN CERTIFICATE-----
+MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEW
+MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVy
+c2FsIENBMB4XDTA0MDMwNDA1MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UE
+BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xHjAcBgNVBAMTFUdlb1RydXN0
+IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKYV
+VaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9tJPi8
+cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTT
+QjOgNB0eRXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFh
+F7em6fgemdtzbvQKoiFs7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2v
+c7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d8Lsrlh/eezJS/R27tQahsiFepdaVaH/w
+mZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7VqnJNk22CDtucvc+081xd
+VHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3CgaRr0BHdCX
+teGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZ
+f9hBZ3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfRe
+Bi9Fi1jUIxaS5BZuKGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+
+nhutxx9z3SxPGWX9f5NAEC7S8O08ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB
+/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0XG0D08DYj3rWMB8GA1UdIwQY
+MBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
+9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc
+aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fX
+IwjhmF7DWgh2qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzyn
+ANXH/KttgCJwpQzgXQQpAvvLoJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0z
+uzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsKxr2EoyNB3tZ3b4XUhRxQ4K5RirqN
+Pnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxFKyDuSN/n3QmOGKja
+QI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2DFKW
+koRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9
+ER/frslKxfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQt
+DF4JbAiXfKM9fJP/P6EUp8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/Sfuvm
+bJxPgWp6ZKy7PtXny3YuxadIwVyQD8vIP/rmMuGNG2+k5o7Y+SlIis5z/iw=
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Universal CA 2 O=GeoTrust Inc.
+# Subject: CN=GeoTrust Universal CA 2 O=GeoTrust Inc.
+# Label: "GeoTrust Universal CA 2"
+# Serial: 1
+# MD5 Fingerprint: 34:fc:b8:d0:36:db:9e:14:b3:c2:f2:db:8f:e4:94:c7
+# SHA1 Fingerprint: 37:9a:19:7b:41:85:45:35:0c:a6:03:69:f3:3c:2e:af:47:4f:20:79
+# SHA256 Fingerprint: a0:23:4f:3b:c8:52:7c:a5:62:8e:ec:81:ad:5d:69:89:5d:a5:68:0d:c9:1d:1c:b8:47:7f:33:f8:78:b9:5b:0b
+-----BEGIN CERTIFICATE-----
+MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEW
+MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVy
+c2FsIENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYD
+VQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1
+c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
+AQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0DE81
+WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUG
+FF+3Qs17j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdq
+XbboW0W63MOhBW9Wjo8QJqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxL
+se4YuU6W3Nx2/zu+z18DwPw76L5GG//aQMJS9/7jOvdqdzXQ2o3rXhhqMcceujwb
+KNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2WP0+GfPtDCapkzj4T8Fd
+IgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP20gaXT73
+y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRt
+hAAnZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgoc
+QIgfksILAAX/8sgCSqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4
+Lt1ZrtmhN79UNdxzMk+MBB4zsslG8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNV
+HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAfBgNV
+HSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8EBAMCAYYwDQYJ
+KoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z
+dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQ
+L1EuxBRa3ugZ4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgr
+Fg5fNuH8KrUwJM/gYwx7WBr+mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSo
+ag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpqA1Ihn0CoZ1Dy81of398j9tx4TuaY
+T1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpgY+RdM4kX2TGq2tbz
+GDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiPpm8m
+1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJV
+OCiNUW7dFGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH
+6aLcr34YEoP9VhdBLtUpgn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwX
+QMAJKOSLakhT2+zNVVXxxvjpoixMptEmX36vWkzaH6byHCx+rgIW0lbQL1dTR+iS
+-----END CERTIFICATE-----
+
+# Issuer: CN=America Online Root Certification Authority 1 O=America Online Inc.
+# Subject: CN=America Online Root Certification Authority 1 O=America Online Inc.
+# Label: "America Online Root Certification Authority 1"
+# Serial: 1
+# MD5 Fingerprint: 14:f1:08:ad:9d:fa:64:e2:89:e7:1c:cf:a8:ad:7d:5e
+# SHA1 Fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a
+# SHA256 Fingerprint: 77:40:73:12:c6:3a:15:3d:5b:c0:0b:4e:51:75:9c:df:da:c2:37:dc:2a:33:b6:79:46:e9:8e:9b:fa:68:0a:e3
+-----BEGIN CERTIFICATE-----
+MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEc
+MBoGA1UEChMTQW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBP
+bmxpbmUgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2
+MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0Ft
+ZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2EgT25saW5lIFJvb3Qg
+Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQADggEP
+ADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lk
+hsmj76CGv2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym
+1BW32J/X3HGrfpq/m44zDyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsW
+OqMFf6Dch9Wc/HKpoH145LcxVR5lu9RhsCFg7RAycsWSJR74kEoYeEfffjA3PlAb
+2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP8c9GsEsPPt2IYriMqQko
+O3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0TAQH/BAUw
+AwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAU
+AK3Zo/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB
+BQUAA4IBAQB8itEfGDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkF
+Zu90821fnZmv9ov761KyBZiibyrFVL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAb
+LjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft3OJvx8Fi8eNy1gTIdGcL+oir
+oQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43gKd8hdIaC2y+C
+MMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds
+sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7
+-----END CERTIFICATE-----
+
+# Issuer: CN=America Online Root Certification Authority 2 O=America Online Inc.
+# Subject: CN=America Online Root Certification Authority 2 O=America Online Inc.
+# Label: "America Online Root Certification Authority 2"
+# Serial: 1
+# MD5 Fingerprint: d6:ed:3c:ca:e2:66:0f:af:10:43:0d:77:9b:04:09:bf
+# SHA1 Fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84
+# SHA256 Fingerprint: 7d:3b:46:5a:60:14:e5:26:c0:af:fc:ee:21:27:d2:31:17:27:ad:81:1c:26:84:2d:00:6a:f3:73:06:cc:80:bd
+-----BEGIN CERTIFICATE-----
+MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEc
+MBoGA1UEChMTQW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBP
+bmxpbmUgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2
+MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0Ft
+ZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2EgT25saW5lIFJvb3Qg
+Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIP
+ADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC
+206B89enfHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFci
+KtZHgVdEglZTvYYUAQv8f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2
+JxhP7JsowtS013wMPgwr38oE18aO6lhOqKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9
+BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JNRvCAOVIyD+OEsnpD8l7e
+Xz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0gBe4lL8B
+PeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67
+Xnfn6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEq
+Z8A9W6Wa6897GqidFEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZ
+o2C7HK2JNDJiuEMhBnIMoVxtRsX6Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3
++L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnjB453cMor9H124HhnAgMBAAGj
+YzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3OpaaEg5+31IqEj
+FNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE
+AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmn
+xPBUlgtk87FYT15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2
+LHo1YGwRgJfMqZJS5ivmae2p+DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzccc
+obGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXgJXUjhx5c3LqdsKyzadsXg8n33gy8
+CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//ZoyzH1kUQ7rVyZ2OuMe
+IjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgOZtMA
+DjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2F
+AjgQ5ANh1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUX
+Om/9riW99XJZZLF0KjhfGEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPb
+AZO1XB4Y3WRayhgoPmMEEf0cjQAPuDffZ4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQl
+Zvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuPcX/9XhmgD0uRuMRUvAaw
+RY8mkaKO/qk=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AAA Certificate Services O=Comodo CA Limited
+# Subject: CN=AAA Certificate Services O=Comodo CA Limited
+# Label: "Comodo AAA Services root"
+# Serial: 1
+# MD5 Fingerprint: 49:79:04:b0:eb:87:19:ac:47:b0:bc:11:51:9b:74:d0
+# SHA1 Fingerprint: d1:eb:23:a4:6d:17:d6:8f:d9:25:64:c2:f1:f1:60:17:64:d8:e3:49
+# SHA256 Fingerprint: d7:a7:a0:fb:5d:7e:27:31:d7:71:e9:48:4e:bc:de:f7:1d:5f:0c:3e:0a:29:48:78:2b:c8:3e:e0:ea:69:9e:f4
+-----BEGIN CERTIFICATE-----
+MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb
+MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow
+GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj
+YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL
+MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE
+BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM
+GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP
+ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua
+BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe
+3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4
+YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR
+rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm
+ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU
+oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF
+MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v
+QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t
+b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF
+AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q
+GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz
+Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2
+G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi
+l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3
+smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==
+-----END CERTIFICATE-----
+
+# Issuer: CN=Secure Certificate Services O=Comodo CA Limited
+# Subject: CN=Secure Certificate Services O=Comodo CA Limited
+# Label: "Comodo Secure Services root"
+# Serial: 1
+# MD5 Fingerprint: d3:d9:bd:ae:9f:ac:67:24:b3:c8:1b:52:e1:b9:a9:bd
+# SHA1 Fingerprint: 4a:65:d5:f4:1d:ef:39:b8:b8:90:4a:4a:d3:64:81:33:cf:c7:a1:d1
+# SHA256 Fingerprint: bd:81:ce:3b:4f:65:91:d1:1a:67:b5:fc:7a:47:fd:ef:25:52:1b:f9:aa:4e:18:b9:e3:df:2e:34:a7:80:3b:e8
+-----BEGIN CERTIFICATE-----
+MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEb
+MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow
+GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRp
+ZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVow
+fjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
+A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAiBgNV
+BAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEB
+BQADggEPADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPM
+cm3ye5drswfxdySRXyWP9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3S
+HpR7LZQdqnXXs5jLrLxkU0C8j6ysNstcrbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996
+CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rCoznl2yY4rYsK7hljxxwk
+3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3Vp6ea5EQz
+6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNV
+HQ4EFgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud
+EwEB/wQFMAMBAf8wgYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2Rv
+Y2EuY29tL1NlY3VyZUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRw
+Oi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmww
+DQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm4J4oqF7Tt/Q0
+5qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj
+Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtI
+gKvcnDe4IRRLDXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJ
+aD61JlfutuC23bkpgHl9j6PwpCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDl
+izeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1HRR3B7Hzs/Sk=
+-----END CERTIFICATE-----
+
+# Issuer: CN=Trusted Certificate Services O=Comodo CA Limited
+# Subject: CN=Trusted Certificate Services O=Comodo CA Limited
+# Label: "Comodo Trusted Services root"
+# Serial: 1
+# MD5 Fingerprint: 91:1b:3f:6e:cd:9e:ab:ee:07:fe:1f:71:d2:b3:61:27
+# SHA1 Fingerprint: e1:9f:e3:0e:8b:84:60:9e:80:9b:17:0d:72:a8:c5:ba:6e:14:09:bd
+# SHA256 Fingerprint: 3f:06:e5:56:81:d4:96:f5:be:16:9e:b5:38:9f:9f:2b:8f:f6:1e:17:08:df:68:81:72:48:49:cd:5d:27:cb:69
+-----BEGIN CERTIFICATE-----
+MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEb
+MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow
+GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0
+aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEwMDAwMDBaFw0yODEyMzEyMzU5NTla
+MH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO
+BgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUwIwYD
+VQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0B
+AQEFAAOCAQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWW
+fnJSoBVC21ndZHoa0Lh73TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMt
+TGo87IvDktJTdyR0nAducPy9C1t2ul/y/9c3S0pgePfw+spwtOpZqqPOSC+pw7IL
+fhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6juljatEPmsbS9Is6FARW
+1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsSivnkBbA7
+kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0G
+A1UdDgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYD
+VR0TAQH/BAUwAwEB/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21v
+ZG9jYS5jb20vVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRo
+dHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMu
+Y3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8NtwuleGFTQQuS9/
+HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32
+pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxIS
+jBc/lDb+XbDABHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+
+xqFx7D+gIIxmOom0jtTYsU0lR+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/Atyjcn
+dBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O9y5Xt5hwXsjEeLBi
+-----END CERTIFICATE-----
+
+# Issuer: CN=UTN - DATACorp SGC O=The USERTRUST Network OU=http://www.usertrust.com
+# Subject: CN=UTN - DATACorp SGC O=The USERTRUST Network OU=http://www.usertrust.com
+# Label: "UTN DATACorp SGC Root CA"
+# Serial: 91374294542884689855167577680241077609
+# MD5 Fingerprint: b3:a5:3e:77:21:6d:ac:4a:c0:c9:fb:d5:41:3d:ca:06
+# SHA1 Fingerprint: 58:11:9f:0e:12:82:87:ea:50:fd:d9:87:45:6f:4f:78:dc:fa:d6:d4
+# SHA256 Fingerprint: 85:fb:2f:91:dd:12:27:5a:01:45:b6:36:53:4f:84:02:4a:d6:8b:69:b8:ee:88:68:4f:f7:11:37:58:05:b3:48
+-----BEGIN CERTIFICATE-----
+MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCB
+kzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
+Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
+dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZBgNVBAMTElVUTiAtIERBVEFDb3Jw
+IFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBaMIGTMQswCQYDVQQG
+EwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4wHAYD
+VQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cu
+dXNlcnRydXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjAN
+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6
+E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ysraP6LnD43m77VkIVni5c7yPeIbkFdicZ
+D0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlowHDyUwDAXlCCpVZvNvlK
+4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA9P4yPykq
+lXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulW
+bfXv33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQAB
+o4GrMIGoMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRT
+MtGzz3/64PGgXYVOktKeRR20TzA9BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3Js
+LnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dDLmNybDAqBgNVHSUEIzAhBggr
+BgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3DQEBBQUAA4IB
+AQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft
+Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyj
+j98C5OBxOvG0I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVH
+KWss5nbZqSl9Mt3JNjy9rjXxEZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv
+2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwPDPafepE39peC4N1xaf92P2BNPM/3
+mfnGV/TJVTl4uix5yaaIK/QI
+-----END CERTIFICATE-----
+
+# Issuer: CN=UTN-USERFirst-Hardware O=The USERTRUST Network OU=http://www.usertrust.com
+# Subject: CN=UTN-USERFirst-Hardware O=The USERTRUST Network OU=http://www.usertrust.com
+# Label: "UTN USERFirst Hardware Root CA"
+# Serial: 91374294542884704022267039221184531197
+# MD5 Fingerprint: 4c:56:41:e5:0d:bb:2b:e8:ca:a3:ed:18:08:ad:43:39
+# SHA1 Fingerprint: 04:83:ed:33:99:ac:36:08:05:87:22:ed:bc:5e:46:00:e3:be:f9:d7
+# SHA256 Fingerprint: 6e:a5:47:41:d0:04:66:7e:ed:1b:48:16:63:4a:a3:a7:9e:6e:4b:96:95:0f:82:79:da:fc:8d:9b:d8:81:21:37
+-----BEGIN CERTIFICATE-----
+MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCB
+lzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
+Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
+dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3Qt
+SGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgxOTIyWjCBlzELMAkG
+A1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEe
+MBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8v
+d3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdh
+cmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn
+0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlIwrthdBKWHTxqctU8EGc6Oe0rE81m65UJ
+M6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFdtqdt++BxF2uiiPsA3/4a
+MXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8i4fDidNd
+oI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqI
+DsjfPe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9Ksy
+oUhbAgMBAAGjgbkwgbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYD
+VR0OBBYEFKFyXyYbKJhDlV0HN9WFlp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0
+dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNFUkZpcnN0LUhhcmR3YXJlLmNy
+bDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEF
+BQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM
+//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28Gpgoiskli
+CE7/yMgUsogWXecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gE
+CJChicsZUN/KHAG8HQQZexB2lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t
+3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kniCrVWFCVH/A7HFe7fRQ5YiuayZSS
+KqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67nfhmqA==
+-----END CERTIFICATE-----
+
+# Issuer: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com
+# Subject: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com
+# Label: "XRamp Global CA Root"
+# Serial: 107108908803651509692980124233745014957
+# MD5 Fingerprint: a1:0b:44:b3:ca:10:d8:00:6e:9d:0f:d8:0f:92:0a:d1
+# SHA1 Fingerprint: b8:01:86:d1:eb:9c:86:a5:41:04:cf:30:54:f3:4c:52:b7:e5:58:c6
+# SHA256 Fingerprint: ce:cd:dc:90:50:99:d8:da:df:c5:b1:d2:09:b7:37:cb:e2:c1:8c:fb:2c:10:c0:ff:0b:cf:0d:32:86:fc:1a:a2
+-----BEGIN CERTIFICATE-----
+MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB
+gjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk
+MCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY
+UmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx
+NDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3
+dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy
+dmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB
+dXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6
+38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP
+KZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q
+DxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4
+qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa
+JSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi
+PvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P
+BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs
+jVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0
+eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD
+ggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR
+vbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt
+qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa
+IR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy
+i6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ
+O+7ETPTsJ3xCwnR8gooJybQDJbw=
+-----END CERTIFICATE-----
+
+# Issuer: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority
+# Subject: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority
+# Label: "Go Daddy Class 2 CA"
+# Serial: 0
+# MD5 Fingerprint: 91:de:06:25:ab:da:fd:32:17:0c:bb:25:17:2a:84:67
+# SHA1 Fingerprint: 27:96:ba:e6:3f:18:01:e2:77:26:1b:a0:d7:77:70:02:8f:20:ee:e4
+# SHA256 Fingerprint: c3:84:6b:f2:4b:9e:93:ca:64:27:4c:0e:c6:7c:1e:cc:5e:02:4f:fc:ac:d2:d7:40:19:35:0e:81:fe:54:6a:e4
+-----BEGIN CERTIFICATE-----
+MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh
+MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE
+YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3
+MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo
+ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg
+MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN
+ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA
+PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w
+wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi
+EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY
+avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+
+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE
+sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h
+/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5
+IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj
+YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD
+ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy
+OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P
+TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ
+HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER
+dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf
+ReYNnyicsbkqWletNw+vHX/bvZ8=
+-----END CERTIFICATE-----
+
+# Issuer: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority
+# Subject: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority
+# Label: "Starfield Class 2 CA"
+# Serial: 0
+# MD5 Fingerprint: 32:4a:4b:bb:c8:63:69:9b:be:74:9a:c6:dd:1d:46:24
+# SHA1 Fingerprint: ad:7e:1c:28:b0:64:ef:8f:60:03:40:20:14:c3:d0:e3:37:0e:b5:8a
+# SHA256 Fingerprint: 14:65:fa:20:53:97:b8:76:fa:a6:f0:a9:95:8e:55:90:e4:0f:cc:7f:aa:4f:b7:c2:c8:67:75:21:fb:5f:b6:58
+-----BEGIN CERTIFICATE-----
+MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl
+MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp
+U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw
+NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE
+ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp
+ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3
+DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf
+8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN
++lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0
+X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa
+K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA
+1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G
+A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR
+zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0
+YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD
+bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w
+DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3
+L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D
+eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl
+xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp
+VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY
+WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=
+-----END CERTIFICATE-----
+
+# Issuer: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing
+# Subject: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing
+# Label: "StartCom Certification Authority"
+# Serial: 1
+# MD5 Fingerprint: 22:4d:8f:8a:fc:f7:35:c2:bb:57:34:90:7b:8b:22:16
+# SHA1 Fingerprint: 3e:2b:f7:f2:03:1b:96:f3:8c:e6:c4:d8:a8:5d:3e:2d:58:47:6a:0f
+# SHA256 Fingerprint: c7:66:a9:be:f2:d4:07:1c:86:3a:31:aa:49:20:e8:13:b2:d1:98:60:8c:b7:b7:cf:e2:11:43:b8:36:df:09:ea
+-----BEGIN CERTIFICATE-----
+MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW
+MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg
+Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh
+dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9
+MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi
+U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh
+cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA
+A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk
+pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf
+OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C
+Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT
+Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi
+HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM
+Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w
++2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+
+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3
+Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B
+26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID
+AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE
+FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j
+ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js
+LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM
+BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0
+Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy
+dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh
+cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh
+YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg
+dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp
+bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ
+YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT
+TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ
+9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8
+jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW
+FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz
+ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1
+ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L
+EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu
+L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq
+yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC
+O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V
+um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh
+NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14=
+-----END CERTIFICATE-----
+
+# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com
+# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com
+# Label: "DigiCert Assured ID Root CA"
+# Serial: 17154717934120587862167794914071425081
+# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72
+# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43
+# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c
+-----BEGIN CERTIFICATE-----
+MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv
+b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG
+EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl
+cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi
+MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c
+JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP
+mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+
+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4
+VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/
+AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB
+AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW
+BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun
+pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC
+dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf
+fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm
+NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx
+H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe
++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==
+-----END CERTIFICATE-----
+
+# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com
+# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com
+# Label: "DigiCert Global Root CA"
+# Serial: 10944719598952040374951832963794454346
+# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e
+# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36
+# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61
+-----BEGIN CERTIFICATE-----
+MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
+QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
+MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
+b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
+9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
+CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
+nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
+43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
+T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
+gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
+BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
+TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
+DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
+hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
+06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
+PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
+YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
+CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
+-----END CERTIFICATE-----
+
+# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com
+# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com
+# Label: "DigiCert High Assurance EV Root CA"
+# Serial: 3553400076410547919724730734378100087
+# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a
+# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25
+# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf
+-----BEGIN CERTIFICATE-----
+MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
+ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL
+MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
+LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug
+RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm
++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW
+PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM
+xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB
+Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3
+hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg
+EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF
+MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA
+FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec
+nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z
+eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF
+hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2
+Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
+vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep
++OkuE6N36B9K
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Primary Certification Authority O=GeoTrust Inc.
+# Subject: CN=GeoTrust Primary Certification Authority O=GeoTrust Inc.
+# Label: "GeoTrust Primary Certification Authority"
+# Serial: 32798226551256963324313806436981982369
+# MD5 Fingerprint: 02:26:c3:01:5e:08:30:37:43:a9:d0:7d:cf:37:e6:bf
+# SHA1 Fingerprint: 32:3c:11:8e:1b:f7:b8:b6:52:54:e2:e2:10:0d:d6:02:90:37:f0:96
+# SHA256 Fingerprint: 37:d5:10:06:c5:12:ea:ab:62:64:21:f1:ec:8c:92:01:3f:c5:f8:2a:e9:8e:e5:33:eb:46:19:b8:de:b4:d0:6c
+-----BEGIN CERTIFICATE-----
+MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY
+MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMo
+R2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEx
+MjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQK
+Ew1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQcmltYXJ5IENlcnRp
+ZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
+AQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9
+AWbK7hWNb6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjA
+ZIVcFU2Ix7e64HXprQU9nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE0
+7e9GceBrAqg1cmuXm2bgyxx5X9gaBGgeRwLmnWDiNpcB3841kt++Z8dtd1k7j53W
+kBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGttm/81w7a4DSwDRp35+MI
+mO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G
+A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJ
+KoZIhvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ1
+6CePbJC/kRYkRj5KTs4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl
+4b7UVXGYNTq+k+qurUKykG/g/CFNNWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6K
+oKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHaFloxt/m0cYASSJlyc1pZU8Fj
+UjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG1riR/aYNKxoU
+AT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk=
+-----END CERTIFICATE-----
+
+# Issuer: CN=thawte Primary Root CA O=thawte, Inc. OU=Certification Services Division/(c) 2006 thawte, Inc. - For authorized use only
+# Subject: CN=thawte Primary Root CA O=thawte, Inc. OU=Certification Services Division/(c) 2006 thawte, Inc. - For authorized use only
+# Label: "thawte Primary Root CA"
+# Serial: 69529181992039203566298953787712940909
+# MD5 Fingerprint: 8c:ca:dc:0b:22:ce:f5:be:72:ac:41:1a:11:a8:d8:12
+# SHA1 Fingerprint: 91:c6:d6:ee:3e:8a:c8:63:84:e5:48:c2:99:29:5c:75:6c:81:7b:81
+# SHA256 Fingerprint: 8d:72:2f:81:a9:c1:13:c0:79:1d:f1:36:a2:96:6d:b2:6c:95:0a:97:1d:b4:6b:41:99:f4:ea:54:b7:8b:fb:9f
+-----BEGIN CERTIFICATE-----
+MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB
+qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf
+Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw
+MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV
+BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw
+NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j
+LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG
+A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
+IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG
+SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs
+W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta
+3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk
+6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6
+Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J
+NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA
+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP
+r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU
+DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz
+YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX
+xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2
+/qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/
+LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7
+jVaMaA==
+-----END CERTIFICATE-----
+
+# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G5 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2006 VeriSign, Inc. - For authorized use only
+# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G5 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2006 VeriSign, Inc. - For authorized use only
+# Label: "VeriSign Class 3 Public Primary Certification Authority - G5"
+# Serial: 33037644167568058970164719475676101450
+# MD5 Fingerprint: cb:17:e4:31:67:3e:e2:09:fe:45:57:93:f3:0a:fa:1c
+# SHA1 Fingerprint: 4e:b6:d5:78:49:9b:1c:cf:5f:58:1e:ad:56:be:3d:9b:67:44:a5:e5
+# SHA256 Fingerprint: 9a:cf:ab:7e:43:c8:d8:80:d0:6b:26:2a:94:de:ee:e4:b4:65:99:89:c3:d0:ca:f1:9b:af:64:05:e4:1a:b7:df
+-----BEGIN CERTIFICATE-----
+MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
+yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
+ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
+U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
+ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
+aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
+MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
+ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
+biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
+U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
+aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
+nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
+t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
+SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
+BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
+rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
+NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
+BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
+BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
+aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
+MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
+p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
+5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
+WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
+4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
+hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
+-----END CERTIFICATE-----
+
+# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited
+# Subject: CN=COMODO Certification Authority O=COMODO CA Limited
+# Label: "COMODO Certification Authority"
+# Serial: 104350513648249232941998508985834464573
+# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75
+# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b
+# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66
+-----BEGIN CERTIFICATE-----
+MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB
+gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
+A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV
+BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw
+MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl
+YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P
+RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0
+aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3
+UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI
+2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8
+Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp
++2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+
+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O
+nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW
+/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g
+PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u
+QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY
+SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv
+IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/
+RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4
+zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd
+BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB
+ZQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C.
+# Subject: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C.
+# Label: "Network Solutions Certificate Authority"
+# Serial: 116697915152937497490437556386812487904
+# MD5 Fingerprint: d3:f3:a6:16:c0:fa:6b:1d:59:b1:2d:96:4d:0e:11:2e
+# SHA1 Fingerprint: 74:f8:a3:c3:ef:e7:b3:90:06:4b:83:90:3c:21:64:60:20:e5:df:ce
+# SHA256 Fingerprint: 15:f0:ba:00:a3:ac:7a:f3:ac:88:4c:07:2b:10:11:a0:77:bd:77:c0:97:f4:01:64:b2:f8:59:8a:bd:83:86:0c
+-----BEGIN CERTIFICATE-----
+MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBi
+MQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu
+MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3Jp
+dHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJV
+UzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydO
+ZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqG
+SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwz
+c7MEL7xxjOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPP
+OCwGJgl6cvf6UDL4wpPTaaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rl
+mGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXTcrA/vGp97Eh/jcOrqnErU2lBUzS1sLnF
+BgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc/Qzpf14Dl847ABSHJ3A4
+qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMBAAGjgZcw
+gZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIB
+BjAPBgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwu
+bmV0c29sc3NsLmNvbS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3Jp
+dHkuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc8
+6fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q4LqILPxFzBiwmZVRDuwduIj/
+h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/GGUsyfJj4akH
+/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv
+wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHN
+pGxlaKFJdlxDydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey
+-----END CERTIFICATE-----
+
+# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited
+# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited
+# Label: "COMODO ECC Certification Authority"
+# Serial: 41578283867086692638256921589707938090
+# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23
+# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11
+# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7
+-----BEGIN CERTIFICATE-----
+MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL
+MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE
+BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT
+IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw
+MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy
+ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N
+T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv
+biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR
+FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J
+cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW
+BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
+BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm
+fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv
+GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=
+-----END CERTIFICATE-----
+
+# Issuer: CN=TC TrustCenter Class 2 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 2 CA
+# Subject: CN=TC TrustCenter Class 2 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 2 CA
+# Label: "TC TrustCenter Class 2 CA II"
+# Serial: 941389028203453866782103406992443
+# MD5 Fingerprint: ce:78:33:5c:59:78:01:6e:18:ea:b9:36:a0:b9:2e:23
+# SHA1 Fingerprint: ae:50:83:ed:7c:f4:5c:bc:8f:61:c6:21:fe:68:5d:79:42:21:15:6e
+# SHA256 Fingerprint: e6:b8:f8:76:64:85:f8:07:ae:7f:8d:ac:16:70:46:1f:07:c0:a1:3e:ef:3a:1f:f7:17:53:8d:7a:ba:d3:91:b4
+-----BEGIN CERTIFICATE-----
+MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjEL
+MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNV
+BAsTGVRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0
+Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYwMTEyMTQzODQzWhcNMjUxMjMxMjI1
+OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIgR21i
+SDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UEAxMc
+VEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQAD
+ggEPADCCAQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jf
+tMjWQ+nEdVl//OEd+DFwIxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKg
+uNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2J
+XjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQXa7pIXSSTYtZgo+U4+lK
+8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7uSNQZu+99
+5OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1Ud
+EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3
+kUrL84J6E1wIqzCB7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRy
+dXN0Y2VudGVyLmRlL2NybC92Mi90Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6
+Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBUcnVzdENlbnRlciUyMENsYXNz
+JTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21iSCxPVT1yb290
+Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
+TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iS
+GNn3Bzn1LL4GdXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprt
+ZjluS5TmVfwLG4t3wVMTZonZKNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8
+au0WOB9/WIFaGusyiC2y8zl3gK9etmF1KdsjTYjKUCjLhdLTEKJZbtOTVAB6okaV
+hgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kPJOzHdiEoZa5X6AeI
+dUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfkvQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=TC TrustCenter Class 3 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 3 CA
+# Subject: CN=TC TrustCenter Class 3 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 3 CA
+# Label: "TC TrustCenter Class 3 CA II"
+# Serial: 1506523511417715638772220530020799
+# MD5 Fingerprint: 56:5f:aa:80:61:12:17:f6:67:21:e6:2b:6d:61:56:8e
+# SHA1 Fingerprint: 80:25:ef:f4:6e:70:c8:d4:72:24:65:84:fe:40:3b:8a:8d:6a:db:f5
+# SHA256 Fingerprint: 8d:a0:84:fc:f9:9c:e0:77:22:f8:9b:32:05:93:98:06:fa:5c:b8:11:e1:c8:13:f6:a1:08:c7:d3:36:b3:40:8e
+-----BEGIN CERTIFICATE-----
+MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjEL
+MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNV
+BAsTGVRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0
+Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYwMTEyMTQ0MTU3WhcNMjUxMjMxMjI1
+OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIgR21i
+SDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UEAxMc
+VEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQAD
+ggEPADCCAQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJW
+Ht4bNwcwIi9v8Qbxq63WyKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+Q
+Vl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo6SI7dYnWRBpl8huXJh0obazovVkdKyT2
+1oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZuV3bOx4a+9P/FRQI2Alq
+ukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk2ZyqBwi1
+Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1Ud
+EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NX
+XAek0CSnwPIA1DCB7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRy
+dXN0Y2VudGVyLmRlL2NybC92Mi90Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6
+Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBUcnVzdENlbnRlciUyMENsYXNz
+JTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21iSCxPVT1yb290
+Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
+TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlN
+irTzwppVMXzEO2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8
+TtXqluJucsG7Kv5sbviRmEb8yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6
+g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9IJqDnxrcOfHFcqMRA/07QlIp2+gB
+95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal092Y+tTmBvTwtiBj
+S+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc5A==
+-----END CERTIFICATE-----
+
+# Issuer: CN=TC TrustCenter Universal CA I O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA
+# Subject: CN=TC TrustCenter Universal CA I O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA
+# Label: "TC TrustCenter Universal CA I"
+# Serial: 601024842042189035295619584734726
+# MD5 Fingerprint: 45:e1:a5:72:c5:a9:36:64:40:9e:f5:e4:58:84:67:8c
+# SHA1 Fingerprint: 6b:2f:34:ad:89:58:be:62:fd:b0:6b:5c:ce:bb:9d:d9:4f:4e:39:f3
+# SHA256 Fingerprint: eb:f3:c0:2a:87:89:b1:fb:7d:51:19:95:d6:63:b7:29:06:d9:13:ce:0d:5e:10:56:8a:8a:77:e2:58:61:67:e7
+-----BEGIN CERTIFICATE-----
+MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTEL
+MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNV
+BAsTG1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1
+c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcNMDYwMzIyMTU1NDI4WhcNMjUxMjMx
+MjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIg
+R21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYwJAYD
+VQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcN
+AQEBBQADggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSR
+JJZ4Hgmgm5qVSkr1YnwCqMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3T
+fCZdzHd55yx4Oagmcw6iXSVphU9VDprvxrlE4Vc93x9UIuVvZaozhDrzznq+VZeu
+jRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtwag+1m7Z3W0hZneTvWq3z
+wZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9OgdwZu5GQ
+fezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYD
+VR0jBBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAO
+BgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0G
+CSqGSIb3DQEBBQUAA4IBAQAo0uCG1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X1
+7caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/CyvwbZ71q+s2IhtNerNXxTPqYn
+8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3ghUJGooWMNjs
+ydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT
+ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/
+2TYcuiUaUj0a7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY
+-----END CERTIFICATE-----
+
+# Issuer: CN=Cybertrust Global Root O=Cybertrust, Inc
+# Subject: CN=Cybertrust Global Root O=Cybertrust, Inc
+# Label: "Cybertrust Global Root"
+# Serial: 4835703278459682877484360
+# MD5 Fingerprint: 72:e4:4a:87:e3:69:40:80:77:ea:bc:e3:f4:ff:f0:e1
+# SHA1 Fingerprint: 5f:43:e5:b1:bf:f8:78:8c:ac:1c:c7:ca:4a:9a:c6:22:2b:cc:34:c6
+# SHA256 Fingerprint: 96:0a:df:00:63:e9:63:56:75:0c:29:65:dd:0a:08:67:da:0b:9c:bd:6e:77:71:4a:ea:fb:23:49:ab:39:3d:a3
+-----BEGIN CERTIFICATE-----
+MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYG
+A1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2Jh
+bCBSb290MB4XDTA2MTIxNTA4MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UE
+ChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBS
+b290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+Mi8vRRQZhP/8NN5
+7CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW0ozS
+J8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2y
+HLtgwEZLAfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iP
+t3sMpTjr3kfb1V05/Iin89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNz
+FtApD0mpSPCzqrdsxacwOUBdrsTiXSZT8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAY
+XSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/
+MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2MDSgMqAw
+hi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3Js
+MB8GA1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUA
+A4IBAQBW7wojoFROlZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMj
+Wqd8BfP9IjsO0QbE2zZMcwSO5bAi5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUx
+XOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2hO0j9n0Hq0V+09+zv+mKts2o
+omcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+TX3EJIrduPuoc
+A06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW
+WL1WMRJOEcgh4LMRkWXbtKaIOM5V
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Primary Certification Authority - G3 O=GeoTrust Inc. OU=(c) 2008 GeoTrust Inc. - For authorized use only
+# Subject: CN=GeoTrust Primary Certification Authority - G3 O=GeoTrust Inc. OU=(c) 2008 GeoTrust Inc. - For authorized use only
+# Label: "GeoTrust Primary Certification Authority - G3"
+# Serial: 28809105769928564313984085209975885599
+# MD5 Fingerprint: b5:e8:34:36:c9:10:44:58:48:70:6d:2e:83:d4:b8:05
+# SHA1 Fingerprint: 03:9e:ed:b8:0b:e7:a0:3c:69:53:89:3b:20:d2:d9:32:3a:4c:2a:fd
+# SHA256 Fingerprint: b4:78:b8:12:25:0d:f8:78:63:5c:2a:a7:ec:7d:15:5e:aa:62:5e:e8:29:16:e2:cd:29:43:61:88:6c:d1:fb:d4
+-----BEGIN CERTIFICATE-----
+MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCB
+mDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsT
+MChjKSAyMDA4IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25s
+eTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhv
+cml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIzNTk1OVowgZgxCzAJ
+BgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg
+MjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0
+BgNVBAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg
+LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz
++uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5jK/BGvESyiaHAKAxJcCGVn2TAppMSAmUm
+hsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdEc5IiaacDiGydY8hS2pgn
+5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3CIShwiP/W
+JmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exAL
+DmKudlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZC
+huOl1UcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw
+HQYDVR0OBBYEFMR5yo6hTgMdHNxr2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IB
+AQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9cr5HqQ6XErhK8WTTOd8lNNTB
+zU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbEAp7aDHdlDkQN
+kv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD
+AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUH
+SJsMC8tJP33st/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2G
+spki4cErx5z481+oghLrGREt
+-----END CERTIFICATE-----
+
+# Issuer: CN=thawte Primary Root CA - G2 O=thawte, Inc. OU=(c) 2007 thawte, Inc. - For authorized use only
+# Subject: CN=thawte Primary Root CA - G2 O=thawte, Inc. OU=(c) 2007 thawte, Inc. - For authorized use only
+# Label: "thawte Primary Root CA - G2"
+# Serial: 71758320672825410020661621085256472406
+# MD5 Fingerprint: 74:9d:ea:60:24:c4:fd:22:53:3e:cc:3a:72:d9:29:4f
+# SHA1 Fingerprint: aa:db:bc:22:23:8f:c4:01:a1:27:bb:38:dd:f4:1d:db:08:9e:f0:12
+# SHA256 Fingerprint: a4:31:0d:50:af:18:a6:44:71:90:37:2a:86:af:af:8b:95:1f:fb:43:1d:83:7f:1e:56:88:b4:59:71:ed:15:57
+-----BEGIN CERTIFICATE-----
+MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDEL
+MAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMp
+IDIwMDcgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAi
+BgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMjAeFw0wNzExMDUwMDAw
+MDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh
+d3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBGb3Ig
+YXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9v
+dCBDQSAtIEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/
+BebfowJPDQfGAFG6DAJSLSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6
+papu+7qzcMBniKI11KOasf2twu8x+qi58/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8E
+BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUmtgAMADna3+FGO6Lts6K
+DPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUNG4k8VIZ3
+KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41ox
+XZ3Krr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg==
+-----END CERTIFICATE-----
+
+# Issuer: CN=thawte Primary Root CA - G3 O=thawte, Inc. OU=Certification Services Division/(c) 2008 thawte, Inc. - For authorized use only
+# Subject: CN=thawte Primary Root CA - G3 O=thawte, Inc. OU=Certification Services Division/(c) 2008 thawte, Inc. - For authorized use only
+# Label: "thawte Primary Root CA - G3"
+# Serial: 127614157056681299805556476275995414779
+# MD5 Fingerprint: fb:1b:5d:43:8a:94:cd:44:c6:76:f2:43:4b:47:e7:31
+# SHA1 Fingerprint: f1:8b:53:8d:1b:e9:03:b6:a6:f0:56:43:5b:17:15:89:ca:f3:6b:f2
+# SHA256 Fingerprint: 4b:03:f4:58:07:ad:70:f2:1b:fc:2c:ae:71:c9:fd:e4:60:4c:06:4c:f5:ff:b6:86:ba:e5:db:aa:d7:fd:d3:4c
+-----BEGIN CERTIFICATE-----
+MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCB
+rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf
+Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw
+MDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNV
+BAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0wODA0MDIwMDAwMDBa
+Fw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3Rl
+LCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9u
+MTgwNgYDVQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXpl
+ZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEcz
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsr8nLPvb2FvdeHsbnndm
+gcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2AtP0LMqmsywCPLLEHd5N/8
+YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC+BsUa0Lf
+b1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS9
+9irY7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2S
+zhkGcuYMXDhpxwTWvGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUk
+OQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV
+HQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJKoZIhvcNAQELBQADggEBABpA
+2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweKA3rD6z8KLFIW
+oCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu
+t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7c
+KUGRIjxpp7sC8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fM
+m7v/OeZWYdMKp8RcTGB7BXcmer/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZu
+MdRAGmI0Nj81Aa6sY6A=
+-----END CERTIFICATE-----
+
+# Issuer: CN=GeoTrust Primary Certification Authority - G2 O=GeoTrust Inc. OU=(c) 2007 GeoTrust Inc. - For authorized use only
+# Subject: CN=GeoTrust Primary Certification Authority - G2 O=GeoTrust Inc. OU=(c) 2007 GeoTrust Inc. - For authorized use only
+# Label: "GeoTrust Primary Certification Authority - G2"
+# Serial: 80682863203381065782177908751794619243
+# MD5 Fingerprint: 01:5e:d8:6b:bd:6f:3d:8e:a1:31:f8:12:e0:98:73:6a
+# SHA1 Fingerprint: 8d:17:84:d5:37:f3:03:7d:ec:70:fe:57:8b:51:9a:99:e6:10:d7:b0
+# SHA256 Fingerprint: 5e:db:7a:c4:3b:82:a0:6a:87:61:e8:d7:be:49:79:eb:f2:61:1f:7d:d7:9b:f9:1c:1c:6b:56:6a:21:9e:d7:66
+-----BEGIN CERTIFICATE-----
+MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDEL
+MAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChj
+KSAyMDA3IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2
+MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0
+eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1OVowgZgxCzAJBgNV
+BAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykgMjAw
+NyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNV
+BAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBH
+MjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcL
+So17VDs6bl8VAsBQps8lL33KSLjHUGMcKiEIfJo22Av+0SbFWDEwKCXzXV2juLal
+tJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO
+BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+EVXVMAoG
+CCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGT
+qQ7mndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBucz
+rD6ogRLQy7rQkgu2npaqBA+K
+-----END CERTIFICATE-----
+
+# Issuer: CN=VeriSign Universal Root Certification Authority O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2008 VeriSign, Inc. - For authorized use only
+# Subject: CN=VeriSign Universal Root Certification Authority O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2008 VeriSign, Inc. - For authorized use only
+# Label: "VeriSign Universal Root Certification Authority"
+# Serial: 85209574734084581917763752644031726877
+# MD5 Fingerprint: 8e:ad:b5:01:aa:4d:81:e4:8c:1d:d1:e1:14:00:95:19
+# SHA1 Fingerprint: 36:79:ca:35:66:87:72:30:4d:30:a5:fb:87:3b:0f:a7:7b:b7:0d:54
+# SHA256 Fingerprint: 23:99:56:11:27:a5:71:25:de:8c:ef:ea:61:0d:df:2f:a0:78:b5:c8:06:7f:4e:82:82:90:bf:b8:60:e8:4b:3c
+-----BEGIN CERTIFICATE-----
+MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCB
+vTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
+ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJp
+U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MTgwNgYDVQQDEy9W
+ZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe
+Fw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJVUzEX
+MBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0
+IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9y
+IGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNh
+bCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF
+AAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj1mCOkdeQmIN65lgZOIzF
+9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGPMiJhgsWH
+H26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+H
+LL729fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN
+/BMReYTtXlT2NJ8IAfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPT
+rJ9VAMf2CGqUuV/c4DPxhGD5WycRtPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1Ud
+EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0GCCsGAQUFBwEMBGEwX6FdoFsw
+WTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2Oa8PPgGrUSBgs
+exkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud
+DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4
+sAPmLGd75JR3Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+
+seQxIcaBlVZaDrHC1LGmWazxY8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz
+4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTxP/jgdFcrGJ2BtMQo2pSXpXDrrB2+
+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+PwGZsY6rp2aQW9IHR
+lRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4mJO3
+7M2CYfE45k+XmCpajQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G4 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2007 VeriSign, Inc. - For authorized use only
+# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G4 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2007 VeriSign, Inc. - For authorized use only
+# Label: "VeriSign Class 3 Public Primary Certification Authority - G4"
+# Serial: 63143484348153506665311985501458640051
+# MD5 Fingerprint: 3a:52:e1:e7:fd:6f:3a:e3:6f:f3:6f:99:1b:f9:22:41
+# SHA1 Fingerprint: 22:d5:d8:df:8f:02:31:d1:8d:f7:9d:b7:cf:8a:2d:64:c9:3f:6c:3a
+# SHA256 Fingerprint: 69:dd:d7:ea:90:bb:57:c9:3e:13:5d:c8:5e:a6:fc:d5:48:0b:60:32:39:bd:c4:54:fc:75:8b:2a:26:cf:7f:79
+-----BEGIN CERTIFICATE-----
+MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjEL
+MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
+ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2ln
+biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
+U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
+aXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjELMAkG
+A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJp
+U2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwg
+SW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2ln
+biBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5
+IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8Utpkmw4tXNherJI9/gHm
+GUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGzrl0Bp3ve
+fLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUw
+AwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJ
+aW1hZ2UvZ2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYj
+aHR0cDovL2xvZ28udmVyaXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMW
+kf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMDA2gAMGUCMGYhDBgmYFo4e1ZC
+4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIxAJw9SDkjOVga
+FRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA==
+-----END CERTIFICATE-----
+
+# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3
+# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3
+# Label: "GlobalSign Root CA - R3"
+# Serial: 4835703278459759426209954
+# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28
+# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad
+# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b
+-----BEGIN CERTIFICATE-----
+MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G
+A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp
+Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4
+MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG
+A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
+hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8
+RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT
+gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm
+KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd
+QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ
+XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw
+DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o
+LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU
+RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp
+jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
+6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX
+mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
+Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
+WD9f
+-----END CERTIFICATE-----
+
+# Issuer: CN=TC TrustCenter Universal CA III O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA
+# Subject: CN=TC TrustCenter Universal CA III O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA
+# Label: "TC TrustCenter Universal CA III"
+# Serial: 2010889993983507346460533407902964
+# MD5 Fingerprint: 9f:dd:db:ab:ff:8e:ff:45:21:5f:f0:6c:9d:8f:fe:2b
+# SHA1 Fingerprint: 96:56:cd:7b:57:96:98:95:d0:e1:41:46:68:06:fb:b8:c6:11:06:87
+# SHA256 Fingerprint: 30:9b:4a:87:f6:ca:56:c9:31:69:aa:a9:9c:6d:98:88:54:d7:89:2b:d5:43:7e:2d:07:b2:9c:be:da:55:d3:5d
+-----BEGIN CERTIFICATE-----
+MIID4TCCAsmgAwIBAgIOYyUAAQACFI0zFQLkbPQwDQYJKoZIhvcNAQEFBQAwezEL
+MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNV
+BAsTG1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQTEoMCYGA1UEAxMfVEMgVHJ1
+c3RDZW50ZXIgVW5pdmVyc2FsIENBIElJSTAeFw0wOTA5MDkwODE1MjdaFw0yOTEy
+MzEyMzU5NTlaMHsxCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNUQyBUcnVzdENlbnRl
+ciBHbWJIMSQwIgYDVQQLExtUQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0ExKDAm
+BgNVBAMTH1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQSBJSUkwggEiMA0GCSqG
+SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDC2pxisLlxErALyBpXsq6DFJmzNEubkKLF
+5+cvAqBNLaT6hdqbJYUtQCggbergvbFIgyIpRJ9Og+41URNzdNW88jBmlFPAQDYv
+DIRlzg9uwliT6CwLOunBjvvya8o84pxOjuT5fdMnnxvVZ3iHLX8LR7PH6MlIfK8v
+zArZQe+f/prhsq75U7Xl6UafYOPfjdN/+5Z+s7Vy+EutCHnNaYlAJ/Uqwa1D7KRT
+yGG299J5KmcYdkhtWyUB0SbFt1dpIxVbYYqt8Bst2a9c8SaQaanVDED1M4BDj5yj
+dipFtK+/fz6HP3bFzSreIMUWWMv5G/UPyw0RUmS40nZid4PxWJ//AgMBAAGjYzBh
+MB8GA1UdIwQYMBaAFFbn4VslQ4Dg9ozhcbyO5YAvxEjiMA8GA1UdEwEB/wQFMAMB
+Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRW5+FbJUOA4PaM4XG8juWAL8RI
+4jANBgkqhkiG9w0BAQUFAAOCAQEAg8ev6n9NCjw5sWi+e22JLumzCecYV42Fmhfz
+dkJQEw/HkG8zrcVJYCtsSVgZ1OK+t7+rSbyUyKu+KGwWaODIl0YgoGhnYIg5IFHY
+aAERzqf2EQf27OysGh+yZm5WZ2B6dF7AbZc2rrUNXWZzwCUyRdhKBgePxLcHsU0G
+DeGl6/R1yrqc0L2z0zIkTO5+4nYES0lT2PLpVDP85XEfPRRclkvxOvIAu2y0+pZV
+CIgJwcyRGSmwIC3/yzikQOEXvnlhgP8HA4ZMTnsGnxGGjYnuJ8Tb4rwZjgvDwxPH
+LQNjO9Po5KIqwoIIlBZU8O8fJ5AluA0OKBtHd0e9HKgl8ZS0Zg==
+-----END CERTIFICATE-----
+
+# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.
+# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.
+# Label: "Go Daddy Root Certificate Authority - G2"
+# Serial: 0
+# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01
+# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b
+# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da
+-----BEGIN CERTIFICATE-----
+MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx
+EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT
+EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp
+ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz
+NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH
+EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE
+AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw
+DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD
+E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH
+/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy
+DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh
+GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR
+tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA
+AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
+FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX
+WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu
+9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr
+gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo
+2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO
+LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI
+4uJEvlz36hz1
+-----END CERTIFICATE-----
+
+# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.
+# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.
+# Label: "Starfield Root Certificate Authority - G2"
+# Serial: 0
+# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96
+# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e
+# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5
+-----BEGIN CERTIFICATE-----
+MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx
+EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT
+HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs
+ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw
+MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6
+b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj
+aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp
+Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
+ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg
+nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1
+HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N
+Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN
+dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0
+HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO
+BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G
+CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU
+sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3
+4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg
+8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K
+pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1
+mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0
+-----END CERTIFICATE-----
+
+# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.
+# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.
+# Label: "Starfield Services Root Certificate Authority - G2"
+# Serial: 0
+# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2
+# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f
+# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5
+-----BEGIN CERTIFICATE-----
+MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx
+EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT
+HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs
+ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5
+MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD
+VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy
+ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy
+dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI
+hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p
+OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2
+8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K
+Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe
+hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk
+6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw
+DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q
+AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI
+bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB
+ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z
+qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd
+iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn
+0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN
+sSi6
+-----END CERTIFICATE-----
+
+# Issuer: CN=AffirmTrust Commercial O=AffirmTrust
+# Subject: CN=AffirmTrust Commercial O=AffirmTrust
+# Label: "AffirmTrust Commercial"
+# Serial: 8608355977964138876
+# MD5 Fingerprint: 82:92:ba:5b:ef:cd:8a:6f:a6:3d:55:f9:84:f6:d6:b7
+# SHA1 Fingerprint: f9:b5:b6:32:45:5f:9c:be:ec:57:5f:80:dc:e9:6e:2c:c7:b2:78:b7
+# SHA256 Fingerprint: 03:76:ab:1d:54:c5:f9:80:3c:e4:b2:e2:01:a0:ee:7e:ef:7b:57:b6:36:e8:a9:3c:9b:8d:48:60:c9:6f:5f:a7
+-----BEGIN CERTIFICATE-----
+MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE
+BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz
+dCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL
+MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp
+cm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
+AQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP
+Hx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr
+ba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL
+MeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1
+yHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr
+VwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/
+nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ
+KoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG
+XUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj
+vbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt
+Z8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g
+N53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC
+nlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AffirmTrust Networking O=AffirmTrust
+# Subject: CN=AffirmTrust Networking O=AffirmTrust
+# Label: "AffirmTrust Networking"
+# Serial: 8957382827206547757
+# MD5 Fingerprint: 42:65:ca:be:01:9a:9a:4c:a9:8c:41:49:cd:c0:d5:7f
+# SHA1 Fingerprint: 29:36:21:02:8b:20:ed:02:f5:66:c5:32:d1:d6:ed:90:9f:45:00:2f
+# SHA256 Fingerprint: 0a:81:ec:5a:92:97:77:f1:45:90:4a:f3:8d:5d:50:9f:66:b5:e2:c5:8f:cd:b5:31:05:8b:0e:17:f3:f0:b4:1b
+-----BEGIN CERTIFICATE-----
+MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE
+BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz
+dCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL
+MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp
+cm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
+AQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y
+YJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua
+kCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL
+QESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp
+6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG
+yH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i
+QLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ
+KoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO
+tDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu
+QY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ
+Lgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u
+olu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48
+x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s=
+-----END CERTIFICATE-----
+
+# Issuer: CN=AffirmTrust Premium O=AffirmTrust
+# Subject: CN=AffirmTrust Premium O=AffirmTrust
+# Label: "AffirmTrust Premium"
+# Serial: 7893706540734352110
+# MD5 Fingerprint: c4:5d:0e:48:b6:ac:28:30:4e:0a:bc:f9:38:16:87:57
+# SHA1 Fingerprint: d8:a6:33:2c:e0:03:6f:b1:85:f6:63:4f:7d:6a:06:65:26:32:28:27
+# SHA256 Fingerprint: 70:a7:3f:7f:37:6b:60:07:42:48:90:45:34:b1:14:82:d5:bf:0e:69:8e:cc:49:8d:f5:25:77:eb:f2:e9:3b:9a
+-----BEGIN CERTIFICATE-----
+MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE
+BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz
+dCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG
+A1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U
+cnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf
+qV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ
+JG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ
++jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS
+s8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5
+HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7
+70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG
+V+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S
+qHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S
+5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia
+C1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX
+OwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE
+FJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/
+BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2
+KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg
+Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B
+8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ
+MKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc
+0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ
+u4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF
+u+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH
+YoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8
+GKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO
+RtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e
+KeC2uAloGRwYQw==
+-----END CERTIFICATE-----
+
+# Issuer: CN=AffirmTrust Premium ECC O=AffirmTrust
+# Subject: CN=AffirmTrust Premium ECC O=AffirmTrust
+# Label: "AffirmTrust Premium ECC"
+# Serial: 8401224907861490260
+# MD5 Fingerprint: 64:b0:09:55:cf:b1:d5:99:e2:be:13:ab:a6:5d:ea:4d
+# SHA1 Fingerprint: b8:23:6b:00:2f:1d:16:86:53:01:55:6c:11:a4:37:ca:eb:ff:c3:bb
+# SHA256 Fingerprint: bd:71:fd:f6:da:97:e4:cf:62:d1:64:7a:dd:25:81:b0:7d:79:ad:f8:39:7e:b4:ec:ba:9c:5e:84:88:82:14:23
+-----BEGIN CERTIFICATE-----
+MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC
+VVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ
+cmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ
+BgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt
+VHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D
+0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9
+ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G
+A1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G
+A1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs
+aobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I
+flc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ==
+-----END CERTIFICATE-----
+
+# Issuer: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing
+# Subject: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing
+# Label: "StartCom Certification Authority"
+# Serial: 45
+# MD5 Fingerprint: c9:3b:0d:84:41:fc:a4:76:79:23:08:57:de:10:19:16
+# SHA1 Fingerprint: a3:f1:33:3f:e2:42:bf:cf:c5:d1:4e:8f:39:42:98:40:68:10:d1:a0
+# SHA256 Fingerprint: e1:78:90:ee:09:a3:fb:f4:f4:8b:9c:41:4a:17:d6:37:b7:a5:06:47:e9:bc:75:23:22:72:7f:cc:17:42:a9:11
+-----BEGIN CERTIFICATE-----
+MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEW
+MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg
+Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh
+dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM3WhcNMzYwOTE3MTk0NjM2WjB9
+MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi
+U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh
+cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA
+A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk
+pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf
+OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C
+Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT
+Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi
+HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM
+Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w
++2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+
+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3
+Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B
+26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID
+AQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD
+VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFul
+F2mHMMo0aEPQQa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCC
+ATgwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5w
+ZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVk
+aWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENvbW1lcmNpYWwgKFN0
+YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0aGUg
+c2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0
+aWZpY2F0aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93
+d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgG
+CWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1
+dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5fPGFf59Jb2vKXfuM/gTF
+wWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWmN3PH/UvS
+Ta0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst
+0OcNOrg+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNc
+pRJvkrKTlMeIFw6Ttn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKl
+CcWw0bdT82AUuoVpaiF8H3VhFyAXe2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVF
+P0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA2MFrLH9ZXF2RsXAiV+uKa0hK
+1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBsHvUwyKMQ5bLm
+KhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE
+JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ
+8dCAWZvLMdibD4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnm
+fyWl8kgAwKQB2j8=
+-----END CERTIFICATE-----
+
+# Issuer: CN=StartCom Certification Authority G2 O=StartCom Ltd.
+# Subject: CN=StartCom Certification Authority G2 O=StartCom Ltd.
+# Label: "StartCom Certification Authority G2"
+# Serial: 59
+# MD5 Fingerprint: 78:4b:fb:9e:64:82:0a:d3:b8:4c:62:f3:64:f2:90:64
+# SHA1 Fingerprint: 31:f1:fd:68:22:63:20:ee:c6:3b:3f:9d:ea:4a:3e:53:7c:7c:39:17
+# SHA256 Fingerprint: c7:ba:65:67:de:93:a7:98:ae:1f:aa:79:1e:71:2d:37:8f:ae:1f:93:c4:39:7f:ea:44:1b:b7:cb:e6:fd:59:95
+-----BEGIN CERTIFICATE-----
+MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEW
+MBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlm
+aWNhdGlvbiBBdXRob3JpdHkgRzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1
+OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoG
+A1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgRzIwggIiMA0G
+CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8Oo1XJ
+JZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsD
+vfOpL9HG4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnoo
+D/Uefyf3lLE3PbfHkffiAez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/
+Q0kGi4xDuFby2X8hQxfqp0iVAXV16iulQ5XqFYSdCI0mblWbq9zSOdIxHWDirMxW
+RST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbsO+wmETRIjfaAKxojAuuK
+HDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8HvKTlXcxN
+nw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM
+0D4LnMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/i
+UUjXuG+v+E5+M5iSFGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9
+Ha90OrInwMEePnWjFqmveiJdnxMaz6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHg
+TuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE
+AwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJKoZIhvcNAQEL
+BQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K
+2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfX
+UfEpY9Z1zRbkJ4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl
+6/2o1PXWT6RbdejF0mCy2wl+JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK
+9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG/+gyRr61M3Z3qAFdlsHB1b6uJcDJ
+HgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTcnIhT76IxW1hPkWLI
+wpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/XldblhY
+XzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5l
+IxKVCCIcl85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoo
+hdVddLHRDiBYmxOlsGOm7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulr
+so8uBtjRkcfGEvRM/TAXw8HaOFvjqermobp573PYtlNXLfbQ4ddI
+-----END CERTIFICATE-----
+
+# Issuer: CN=DigiCert Global Root G2, OU=www.digicert.com, O=DigiCert Inc, C=US
+# Subject: CN=DigiCert Global Root G2, OU=www.digicert.com, O=DigiCert Inc, C=US
+# Serial: 33af1e6a711a9a0bb2864b11d09fae5
+# MD5 Fingerprint: E4:A6:8A:C8:54:AC:52:42:46:0A:FD:72:48:1B:2A:44
+# SHA1 Fingerprint: DF:3C:24:F9:BF:D6:66:76:1B:26:80:73:FE:06:D1:CC:8D:4F:82:A4
+# SHA256 Fingerprint: CB:3C:CB:B7:60:31:E5:E0:13:8F:8D:D3:9A:23:F9:DE:47:FF:C3:5E:43:C1:14:4C:EA:27:D4:6A:5A:B1:CB:5F
+-----BEGIN CERTIFICATE-----
+MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
+MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT
+MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
+b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG
+9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI
+2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx
+1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ
+q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz
+tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ
+vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP
+BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV
+5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY
+1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4
+NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG
+Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91
+8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe
+pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl
+MrY=
+-----END CERTIFICATE-----
+
+# Issuer: /C=US/O=Internet Security Research Group/CN=ISRG Root X1
+# Subject: /C=US/O=Internet Security Research Group/CN=ISRG Root X1
+# Serial: 8210CFB0D240E3594463E0BB63828B00
+# SHA1 Fingerprint: CA:BD:2A:79:A1:07:6A:31:F2:1D:25:36:35:CB:03:9D:43:29:A5:E8
+# SHA256 Fingerprint: 96:BC:EC:06:26:49:76:F3:74:60:77:9A:CF:28:C5:A7:CF:E8:A3:C0:AA:E1:1A:8F:FC:EE:05:C0:BD:DF:08:C6
+-----BEGIN CERTIFICATE-----
+MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
+TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
+cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
+WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
+ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
+MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
+h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
+A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
+T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
+B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
+B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
+KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
+OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
+jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
+qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
+rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
+HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
+hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
+ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
+3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
+NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
+ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
+TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
+jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
+oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
+4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
+mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
+emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
+-----END CERTIFICATE-----
+
+# Issuer: /C=US/O=Internet Security Research Group/CN=ISRG Root X2
+# Subject: /C=US/O=Internet Security Research Group/CN=ISRG Root X2
+# Serial: 41D29DD172EAEEA780C12C6CE92F8752
+# SHA1 Fingerprint: BD:B1:B9:3C:D5:97:8D:45:C6:26:14:55:F8:DB:95:C7:5A:D1:53:AF
+# SHA256 Fingerprint: 69:72:9B:8E:15:A8:6E:FC:17:7A:57:AF:B7:17:1D:FC:64:AD:D2:8C:2F:CA:8C:F1:50:7E:34:45:3C:CB:14:70
+-----BEGIN CERTIFICATE-----
+MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw
+CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg
+R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00
+MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT
+ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw
+EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW
++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9
+ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T
+AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI
+zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW
+tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1
+/q4AaOeMSQ+2b1tbFfLn
+-----END CERTIFICATE-----
diff --git a/venv/lib/python3.10/site-packages/httplib2/certs.py b/venv/lib/python3.10/site-packages/httplib2/certs.py
new file mode 100644
index 0000000000000000000000000000000000000000..59d1ffc7027352415ebf522eb55e7ce4dd9833b4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/certs.py
@@ -0,0 +1,42 @@
+"""Utilities for certificate management."""
+
+import os
+
+certifi_available = False
+certifi_where = None
+try:
+ from certifi import where as certifi_where
+ certifi_available = True
+except ImportError:
+ pass
+
+custom_ca_locater_available = False
+custom_ca_locater_where = None
+try:
+ from ca_certs_locater import get as custom_ca_locater_where
+ custom_ca_locater_available = True
+except ImportError:
+ pass
+
+
+BUILTIN_CA_CERTS = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "cacerts.txt"
+)
+
+
+def where():
+ env = os.environ.get("HTTPLIB2_CA_CERTS")
+ if env is not None:
+ if os.path.isfile(env):
+ return env
+ else:
+ raise RuntimeError("Environment variable HTTPLIB2_CA_CERTS not a valid file")
+ if custom_ca_locater_available:
+ return custom_ca_locater_where()
+ if certifi_available:
+ return certifi_where()
+ return BUILTIN_CA_CERTS
+
+
+if __name__ == "__main__":
+ print(where())
diff --git a/venv/lib/python3.10/site-packages/httplib2/error.py b/venv/lib/python3.10/site-packages/httplib2/error.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e68c12a852c88cace86d476b5cb9a8151196a6c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/error.py
@@ -0,0 +1,48 @@
+# All exceptions raised here derive from HttpLib2Error
+class HttpLib2Error(Exception):
+ pass
+
+
+# Some exceptions can be caught and optionally
+# be turned back into responses.
+class HttpLib2ErrorWithResponse(HttpLib2Error):
+ def __init__(self, desc, response, content):
+ self.response = response
+ self.content = content
+ HttpLib2Error.__init__(self, desc)
+
+
+class RedirectMissingLocation(HttpLib2ErrorWithResponse):
+ pass
+
+
+class RedirectLimit(HttpLib2ErrorWithResponse):
+ pass
+
+
+class FailedToDecompressContent(HttpLib2ErrorWithResponse):
+ pass
+
+
+class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
+ pass
+
+
+class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
+ pass
+
+
+class MalformedHeader(HttpLib2Error):
+ pass
+
+
+class RelativeURIError(HttpLib2Error):
+ pass
+
+
+class ServerNotFoundError(HttpLib2Error):
+ pass
+
+
+class ProxiesUnavailableError(HttpLib2Error):
+ pass
diff --git a/venv/lib/python3.10/site-packages/httplib2/iri2uri.py b/venv/lib/python3.10/site-packages/httplib2/iri2uri.py
new file mode 100644
index 0000000000000000000000000000000000000000..86e361e62ae8dd603d2a982b22bd79ee8653a726
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/iri2uri.py
@@ -0,0 +1,124 @@
+# -*- coding: utf-8 -*-
+"""Converts an IRI to a URI."""
+
+__author__ = "Joe Gregorio (joe@bitworking.org)"
+__copyright__ = "Copyright 2006, Joe Gregorio"
+__contributors__ = []
+__version__ = "1.0.0"
+__license__ = "MIT"
+
+import urllib.parse
+
+# Convert an IRI to a URI following the rules in RFC 3987
+#
+# The characters we need to enocde and escape are defined in the spec:
+#
+# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
+# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
+# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
+# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
+# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
+# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
+# / %xD0000-DFFFD / %xE1000-EFFFD
+
+escape_range = [
+ (0xA0, 0xD7FF),
+ (0xE000, 0xF8FF),
+ (0xF900, 0xFDCF),
+ (0xFDF0, 0xFFEF),
+ (0x10000, 0x1FFFD),
+ (0x20000, 0x2FFFD),
+ (0x30000, 0x3FFFD),
+ (0x40000, 0x4FFFD),
+ (0x50000, 0x5FFFD),
+ (0x60000, 0x6FFFD),
+ (0x70000, 0x7FFFD),
+ (0x80000, 0x8FFFD),
+ (0x90000, 0x9FFFD),
+ (0xA0000, 0xAFFFD),
+ (0xB0000, 0xBFFFD),
+ (0xC0000, 0xCFFFD),
+ (0xD0000, 0xDFFFD),
+ (0xE1000, 0xEFFFD),
+ (0xF0000, 0xFFFFD),
+ (0x100000, 0x10FFFD),
+]
+
+
+def encode(c):
+ retval = c
+ i = ord(c)
+ for low, high in escape_range:
+ if i < low:
+ break
+ if i >= low and i <= high:
+ retval = "".join(["%%%2X" % o for o in c.encode("utf-8")])
+ break
+ return retval
+
+
+def iri2uri(uri):
+ """Convert an IRI to a URI. Note that IRIs must be
+ passed in a unicode strings. That is, do not utf-8 encode
+ the IRI before passing it into the function."""
+ if isinstance(uri, str):
+ (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri)
+ authority = authority.encode("idna").decode("utf-8")
+ # For each character in 'ucschar' or 'iprivate'
+ # 1. encode as utf-8
+ # 2. then %-encode each octet of that utf-8
+ uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment))
+ uri = "".join([encode(c) for c in uri])
+ return uri
+
+
+if __name__ == "__main__":
+ import unittest
+
+ class Test(unittest.TestCase):
+ def test_uris(self):
+ """Test that URIs are invariant under the transformation."""
+ invariant = [
+ "ftp://ftp.is.co.za/rfc/rfc1808.txt",
+ "http://www.ietf.org/rfc/rfc2396.txt",
+ "ldap://[2001:db8::7]/c=GB?objectClass?one",
+ "mailto:John.Doe@example.com",
+ "news:comp.infosystems.www.servers.unix",
+ "tel:+1-816-555-1212",
+ "telnet://192.0.2.16:80/",
+ "urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
+ ]
+ for uri in invariant:
+ self.assertEqual(uri, iri2uri(uri))
+
+ def test_iri(self):
+ """Test that the right type of escaping is done for each part of the URI."""
+ self.assertEqual(
+ "http://xn--o3h.com/%E2%98%84",
+ iri2uri("http://\N{COMET}.com/\N{COMET}"),
+ )
+ self.assertEqual(
+ "http://bitworking.org/?fred=%E2%98%84",
+ iri2uri("http://bitworking.org/?fred=\N{COMET}"),
+ )
+ self.assertEqual(
+ "http://bitworking.org/#%E2%98%84",
+ iri2uri("http://bitworking.org/#\N{COMET}"),
+ )
+ self.assertEqual("#%E2%98%84", iri2uri("#\N{COMET}"))
+ self.assertEqual(
+ "/fred?bar=%E2%98%9A#%E2%98%84",
+ iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"),
+ )
+ self.assertEqual(
+ "/fred?bar=%E2%98%9A#%E2%98%84",
+ iri2uri(iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")),
+ )
+ self.assertNotEqual(
+ "/fred?bar=%E2%98%9A#%E2%98%84",
+ iri2uri(
+ "/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode("utf-8")
+ ),
+ )
+
+ unittest.main()
diff --git a/venv/lib/python3.10/site-packages/httplib2/socks.py b/venv/lib/python3.10/site-packages/httplib2/socks.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc68e634c7def34dbf2dd0be8b0cca17970a73f9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/httplib2/socks.py
@@ -0,0 +1,518 @@
+"""SocksiPy - Python SOCKS module.
+
+Version 1.00
+
+Copyright 2006 Dan-Haim. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+3. Neither the name of Dan Haim nor the names of his contributors may be used
+ to endorse or promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
+
+This module provides a standard socket-like interface for Python
+for tunneling connections through SOCKS proxies.
+
+Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for
+use in PyLoris (http://pyloris.sourceforge.net/).
+
+Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
+mainly to merge bug fixes found in Sourceforge.
+"""
+
+import base64
+import socket
+import struct
+import sys
+
+if getattr(socket, "socket", None) is None:
+ raise ImportError("socket.socket missing, proxy support unusable")
+
+PROXY_TYPE_SOCKS4 = 1
+PROXY_TYPE_SOCKS5 = 2
+PROXY_TYPE_HTTP = 3
+PROXY_TYPE_HTTP_NO_TUNNEL = 4
+
+_defaultproxy = None
+_orgsocket = socket.socket
+
+
+class ProxyError(Exception):
+ pass
+
+
+class GeneralProxyError(ProxyError):
+ pass
+
+
+class Socks5AuthError(ProxyError):
+ pass
+
+
+class Socks5Error(ProxyError):
+ pass
+
+
+class Socks4Error(ProxyError):
+ pass
+
+
+class HTTPError(ProxyError):
+ pass
+
+
+_generalerrors = (
+ "success",
+ "invalid data",
+ "not connected",
+ "not available",
+ "bad proxy type",
+ "bad input",
+)
+
+_socks5errors = (
+ "succeeded",
+ "general SOCKS server failure",
+ "connection not allowed by ruleset",
+ "Network unreachable",
+ "Host unreachable",
+ "Connection refused",
+ "TTL expired",
+ "Command not supported",
+ "Address type not supported",
+ "Unknown error",
+)
+
+_socks5autherrors = (
+ "succeeded",
+ "authentication is required",
+ "all offered authentication methods were rejected",
+ "unknown username or invalid password",
+ "unknown error",
+)
+
+_socks4errors = (
+ "request granted",
+ "request rejected or failed",
+ "request rejected because SOCKS server cannot connect to identd on the client",
+ "request rejected because the client program and identd report different "
+ "user-ids",
+ "unknown error",
+)
+
+
+def setdefaultproxy(
+ proxytype=None, addr=None, port=None, rdns=True, username=None, password=None
+):
+ """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
+ Sets a default proxy which all further socksocket objects will use,
+ unless explicitly changed.
+ """
+ global _defaultproxy
+ _defaultproxy = (proxytype, addr, port, rdns, username, password)
+
+
+def wrapmodule(module):
+ """wrapmodule(module)
+
+ Attempts to replace a module's socket library with a SOCKS socket. Must set
+ a default proxy using setdefaultproxy(...) first.
+ This will only work on modules that import socket directly into the
+ namespace;
+ most of the Python Standard Library falls into this category.
+ """
+ if _defaultproxy != None:
+ module.socket.socket = socksocket
+ else:
+ raise GeneralProxyError((4, "no proxy specified"))
+
+
+class socksocket(socket.socket):
+ """socksocket([family[, type[, proto]]]) -> socket object
+ Open a SOCKS enabled socket. The parameters are the same as
+ those of the standard socket init. In order for SOCKS to work,
+ you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
+ """
+
+ def __init__(
+ self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None
+ ):
+ _orgsocket.__init__(self, family, type, proto, _sock)
+ if _defaultproxy != None:
+ self.__proxy = _defaultproxy
+ else:
+ self.__proxy = (None, None, None, None, None, None)
+ self.__proxysockname = None
+ self.__proxypeername = None
+ self.__httptunnel = True
+
+ def __recvall(self, count):
+ """__recvall(count) -> data
+ Receive EXACTLY the number of bytes requested from the socket.
+ Blocks until the required number of bytes have been received.
+ """
+ data = self.recv(count)
+ while len(data) < count:
+ d = self.recv(count - len(data))
+ if not d:
+ raise GeneralProxyError((0, "connection closed unexpectedly"))
+ data = data + d
+ return data
+
+ def sendall(self, content, *args):
+ """ override socket.socket.sendall method to rewrite the header
+ for non-tunneling proxies if needed
+ """
+ if not self.__httptunnel:
+ content = self.__rewriteproxy(content)
+ return super(socksocket, self).sendall(content, *args)
+
+ def __rewriteproxy(self, header):
+ """ rewrite HTTP request headers to support non-tunneling proxies
+ (i.e. those which do not support the CONNECT method).
+ This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
+ """
+ host, endpt = None, None
+ hdrs = header.split("\r\n")
+ for hdr in hdrs:
+ if hdr.lower().startswith("host:"):
+ host = hdr
+ elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
+ endpt = hdr
+ if host and endpt:
+ hdrs.remove(host)
+ hdrs.remove(endpt)
+ host = host.split(" ")[1]
+ endpt = endpt.split(" ")
+ if self.__proxy[4] != None and self.__proxy[5] != None:
+ hdrs.insert(0, self.__getauthheader())
+ hdrs.insert(0, "Host: %s" % host)
+ hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
+ return "\r\n".join(hdrs)
+
+ def __getauthheader(self):
+ auth = self.__proxy[4] + b":" + self.__proxy[5]
+ return "Proxy-Authorization: Basic " + base64.b64encode(auth).decode()
+
+ def setproxy(
+ self,
+ proxytype=None,
+ addr=None,
+ port=None,
+ rdns=True,
+ username=None,
+ password=None,
+ headers=None,
+ ):
+ """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
+
+ Sets the proxy to be used.
+ proxytype - The type of the proxy to be used. Three types
+ are supported: PROXY_TYPE_SOCKS4 (including socks4a),
+ PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
+ addr - The address of the server (IP or DNS).
+ port - The port of the server. Defaults to 1080 for SOCKS
+ servers and 8080 for HTTP proxy servers.
+ rdns - Should DNS queries be preformed on the remote side
+ (rather than the local side). The default is True.
+ Note: This has no effect with SOCKS4 servers.
+ username - Username to authenticate with to the server.
+ The default is no authentication.
+ password - Password to authenticate with to the server.
+ Only relevant when username is also provided.
+ headers - Additional or modified headers for the proxy connect
+ request.
+ """
+ self.__proxy = (
+ proxytype,
+ addr,
+ port,
+ rdns,
+ username.encode() if username else None,
+ password.encode() if password else None,
+ headers,
+ )
+
+ def __negotiatesocks5(self, destaddr, destport):
+ """__negotiatesocks5(self,destaddr,destport)
+ Negotiates a connection through a SOCKS5 server.
+ """
+ # First we'll send the authentication packages we support.
+ if (self.__proxy[4] != None) and (self.__proxy[5] != None):
+ # The username/password details were supplied to the
+ # setproxy method so we support the USERNAME/PASSWORD
+ # authentication (in addition to the standard none).
+ self.sendall(struct.pack("BBBB", 0x05, 0x02, 0x00, 0x02))
+ else:
+ # No username/password were entered, therefore we
+ # only support connections with no authentication.
+ self.sendall(struct.pack("BBB", 0x05, 0x01, 0x00))
+ # We'll receive the server's response to determine which
+ # method was selected
+ chosenauth = self.__recvall(2)
+ if chosenauth[0:1] != chr(0x05).encode():
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ # Check the chosen authentication method
+ if chosenauth[1:2] == chr(0x00).encode():
+ # No authentication is required
+ pass
+ elif chosenauth[1:2] == chr(0x02).encode():
+ # Okay, we need to perform a basic username/password
+ # authentication.
+ packet = bytearray()
+ packet.append(0x01)
+ packet.append(len(self.__proxy[4]))
+ packet.extend(self.__proxy[4])
+ packet.append(len(self.__proxy[5]))
+ packet.extend(self.__proxy[5])
+ self.sendall(packet)
+ authstat = self.__recvall(2)
+ if authstat[0:1] != chr(0x01).encode():
+ # Bad response
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ if authstat[1:2] != chr(0x00).encode():
+ # Authentication failed
+ self.close()
+ raise Socks5AuthError((3, _socks5autherrors[3]))
+ # Authentication succeeded
+ else:
+ # Reaching here is always bad
+ self.close()
+ if chosenauth[1] == chr(0xFF).encode():
+ raise Socks5AuthError((2, _socks5autherrors[2]))
+ else:
+ raise GeneralProxyError((1, _generalerrors[1]))
+ # Now we can request the actual connection
+ req = struct.pack("BBB", 0x05, 0x01, 0x00)
+ # If the given destination address is an IP address, we'll
+ # use the IPv4 address request even if remote resolving was specified.
+ try:
+ ipaddr = socket.inet_aton(destaddr)
+ req = req + chr(0x01).encode() + ipaddr
+ except socket.error:
+ # Well it's not an IP number, so it's probably a DNS name.
+ if self.__proxy[3]:
+ # Resolve remotely
+ ipaddr = None
+ req = (
+ req
+ + chr(0x03).encode()
+ + chr(len(destaddr)).encode()
+ + destaddr.encode()
+ )
+ else:
+ # Resolve locally
+ ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
+ req = req + chr(0x01).encode() + ipaddr
+ req = req + struct.pack(">H", destport)
+ self.sendall(req)
+ # Get the response
+ resp = self.__recvall(4)
+ if resp[0:1] != chr(0x05).encode():
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ elif resp[1:2] != chr(0x00).encode():
+ # Connection failed
+ self.close()
+ if ord(resp[1:2]) <= 8:
+ raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
+ else:
+ raise Socks5Error((9, _socks5errors[9]))
+ # Get the bound address/port
+ elif resp[3:4] == chr(0x01).encode():
+ boundaddr = self.__recvall(4)
+ elif resp[3:4] == chr(0x03).encode():
+ resp = resp + self.recv(1)
+ boundaddr = self.__recvall(ord(resp[4:5]))
+ else:
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ boundport = struct.unpack(">H", self.__recvall(2))[0]
+ self.__proxysockname = (boundaddr, boundport)
+ if ipaddr != None:
+ self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
+ else:
+ self.__proxypeername = (destaddr, destport)
+
+ def getproxysockname(self):
+ """getsockname() -> address info
+ Returns the bound IP address and port number at the proxy.
+ """
+ return self.__proxysockname
+
+ def getproxypeername(self):
+ """getproxypeername() -> address info
+ Returns the IP and port number of the proxy.
+ """
+ return _orgsocket.getpeername(self)
+
+ def getpeername(self):
+ """getpeername() -> address info
+ Returns the IP address and port number of the destination
+ machine (note: getproxypeername returns the proxy)
+ """
+ return self.__proxypeername
+
+ def __negotiatesocks4(self, destaddr, destport):
+ """__negotiatesocks4(self,destaddr,destport)
+ Negotiates a connection through a SOCKS4 server.
+ """
+ # Check if the destination address provided is an IP address
+ rmtrslv = False
+ try:
+ ipaddr = socket.inet_aton(destaddr)
+ except socket.error:
+ # It's a DNS name. Check where it should be resolved.
+ if self.__proxy[3]:
+ ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
+ rmtrslv = True
+ else:
+ ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
+ # Construct the request packet
+ req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
+ # The username parameter is considered userid for SOCKS4
+ if self.__proxy[4] != None:
+ req = req + self.__proxy[4]
+ req = req + chr(0x00).encode()
+ # DNS name if remote resolving is required
+ # NOTE: This is actually an extension to the SOCKS4 protocol
+ # called SOCKS4A and may not be supported in all cases.
+ if rmtrslv:
+ req = req + destaddr + chr(0x00).encode()
+ self.sendall(req)
+ # Get the response from the server
+ resp = self.__recvall(8)
+ if resp[0:1] != chr(0x00).encode():
+ # Bad data
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ if resp[1:2] != chr(0x5A).encode():
+ # Server returned an error
+ self.close()
+ if ord(resp[1:2]) in (91, 92, 93):
+ self.close()
+ raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
+ else:
+ raise Socks4Error((94, _socks4errors[4]))
+ # Get the bound address/port
+ self.__proxysockname = (
+ socket.inet_ntoa(resp[4:]),
+ struct.unpack(">H", resp[2:4])[0],
+ )
+ if rmtrslv != None:
+ self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
+ else:
+ self.__proxypeername = (destaddr, destport)
+
+ def __negotiatehttp(self, destaddr, destport):
+ """__negotiatehttp(self,destaddr,destport)
+ Negotiates a connection through an HTTP server.
+ """
+ # If we need to resolve locally, we do this now
+ if not self.__proxy[3]:
+ addr = socket.gethostbyname(destaddr)
+ else:
+ addr = destaddr
+ headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
+ wrote_host_header = False
+ wrote_auth_header = False
+ if self.__proxy[6] != None:
+ for key, val in self.__proxy[6].iteritems():
+ headers += [key, ": ", val, "\r\n"]
+ wrote_host_header = key.lower() == "host"
+ wrote_auth_header = key.lower() == "proxy-authorization"
+ if not wrote_host_header:
+ headers += ["Host: ", destaddr, "\r\n"]
+ if not wrote_auth_header:
+ if self.__proxy[4] != None and self.__proxy[5] != None:
+ headers += [self.__getauthheader(), "\r\n"]
+ headers.append("\r\n")
+ self.sendall("".join(headers).encode())
+ # We read the response until we get the string "\r\n\r\n"
+ resp = self.recv(1)
+ while resp.find("\r\n\r\n".encode()) == -1:
+ resp = resp + self.recv(1)
+ # We just need the first line to check if the connection
+ # was successful
+ statusline = resp.splitlines()[0].split(" ".encode(), 2)
+ if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ try:
+ statuscode = int(statusline[1])
+ except ValueError:
+ self.close()
+ raise GeneralProxyError((1, _generalerrors[1]))
+ if statuscode != 200:
+ self.close()
+ raise HTTPError((statuscode, statusline[2]))
+ self.__proxysockname = ("0.0.0.0", 0)
+ self.__proxypeername = (addr, destport)
+
+ def connect(self, destpair):
+ """connect(self, despair)
+ Connects to the specified destination through a proxy.
+ destpar - A tuple of the IP/DNS address and the port number.
+ (identical to socket's connect).
+ To select the proxy server use setproxy().
+ """
+ # Do a minimal input check first
+ if (
+ (not type(destpair) in (list, tuple))
+ or (len(destpair) < 2)
+ or (not isinstance(destpair[0], (str, bytes)))
+ or (type(destpair[1]) != int)
+ ):
+ raise GeneralProxyError((5, _generalerrors[5]))
+ if self.__proxy[0] == PROXY_TYPE_SOCKS5:
+ if self.__proxy[2] != None:
+ portnum = self.__proxy[2]
+ else:
+ portnum = 1080
+ _orgsocket.connect(self, (self.__proxy[1], portnum))
+ self.__negotiatesocks5(destpair[0], destpair[1])
+ elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
+ if self.__proxy[2] != None:
+ portnum = self.__proxy[2]
+ else:
+ portnum = 1080
+ _orgsocket.connect(self, (self.__proxy[1], portnum))
+ self.__negotiatesocks4(destpair[0], destpair[1])
+ elif self.__proxy[0] == PROXY_TYPE_HTTP:
+ if self.__proxy[2] != None:
+ portnum = self.__proxy[2]
+ else:
+ portnum = 8080
+ _orgsocket.connect(self, (self.__proxy[1], portnum))
+ self.__negotiatehttp(destpair[0], destpair[1])
+ elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
+ if self.__proxy[2] != None:
+ portnum = self.__proxy[2]
+ else:
+ portnum = 8080
+ _orgsocket.connect(self, (self.__proxy[1], portnum))
+ if destpair[1] == 443:
+ self.__negotiatehttp(destpair[0], destpair[1])
+ else:
+ self.__httptunnel = False
+ elif self.__proxy[0] == None:
+ _orgsocket.connect(self, (destpair[0], destpair[1]))
+ else:
+ raise GeneralProxyError((4, _generalerrors[4]))
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..fc3c00df97bbf6e38be40ce7bec8e9d136d18214
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/METADATA
@@ -0,0 +1,79 @@
+Metadata-Version: 2.4
+Name: iniconfig
+Version: 2.3.0
+Summary: brain-dead simple config-ini parsing
+Author-email: Ronny Pfannschmidt , Holger Krekel
+License-Expression: MIT
+Project-URL: Homepage, https://github.com/pytest-dev/iniconfig
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: POSIX
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Utilities
+Requires-Python: >=3.10
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Dynamic: license-file
+
+iniconfig: brain-dead simple parsing of ini files
+=======================================================
+
+iniconfig is a small and simple INI-file parser module
+having a unique set of features:
+
+* maintains order of sections and entries
+* supports multi-line values with or without line-continuations
+* supports "#" comments everywhere
+* raises errors with proper line-numbers
+* no bells and whistles like automatic substitutions
+* iniconfig raises an Error if two sections have the same name.
+
+If you encounter issues or have feature wishes please report them to:
+
+ https://github.com/RonnyPfannschmidt/iniconfig/issues
+
+Basic Example
+===================================
+
+If you have an ini file like this:
+
+.. code-block:: ini
+
+ # content of example.ini
+ [section1] # comment
+ name1=value1 # comment
+ name1b=value1,value2 # comment
+
+ [section2]
+ name2=
+ line1
+ line2
+
+then you can do:
+
+.. code-block:: pycon
+
+ >>> import iniconfig
+ >>> ini = iniconfig.IniConfig("example.ini")
+ >>> ini['section1']['name1'] # raises KeyError if not exists
+ 'value1'
+ >>> ini.get('section1', 'name1b', [], lambda x: x.split(","))
+ ['value1', 'value2']
+ >>> ini.get('section1', 'notexist', [], lambda x: x.split(","))
+ []
+ >>> [x.name for x in list(ini)]
+ ['section1', 'section2']
+ >>> list(list(ini)[0].items())
+ [('name1', 'value1'), ('name1b', 'value1,value2')]
+ >>> 'section1' in ini
+ True
+ >>> 'inexistendsection' in ini
+ False
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..295ce5bf415e0775e56b01e0579043d81501bb70
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/RECORD
@@ -0,0 +1,15 @@
+iniconfig-2.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+iniconfig-2.3.0.dist-info/METADATA,sha256=QNdz-E5OES9JW79PG-nL0tRWwK6271MR910b8yLyFls,2526
+iniconfig-2.3.0.dist-info/RECORD,,
+iniconfig-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+iniconfig-2.3.0.dist-info/licenses/LICENSE,sha256=NAn6kfes5VeJRjJnZlbjImT-XvdYFTVyXcmiN3RVG9Q,1098
+iniconfig-2.3.0.dist-info/top_level.txt,sha256=7KfM0fugdlToj9UW7enKXk2HYALQD8qHiyKtjhSzgN8,10
+iniconfig/__init__.py,sha256=XL5eqUYj4mskAOorZ5jfRAinJvJzTI-fJxpP4xfXtaw,7497
+iniconfig/__pycache__/__init__.cpython-310.pyc,,
+iniconfig/__pycache__/_parse.cpython-310.pyc,,
+iniconfig/__pycache__/_version.cpython-310.pyc,,
+iniconfig/__pycache__/exceptions.cpython-310.pyc,,
+iniconfig/_parse.py,sha256=5ncBl7MAQiaPNnpRrs9FR4t6G6DkgOUs458OY_1CR28,5223
+iniconfig/_version.py,sha256=KNFYe-Vtdt7Z-oHyl8jmDAQ9qXoCNMAEXigj6BR1QUI,704
+iniconfig/exceptions.py,sha256=mipQ_aMxD9CvSvFWN1oTXY4QuRnKAMZ1f3sCdmjDTU0,399
+iniconfig/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..46f4b2846fd708ecb81b2d665434ce6379aa1101
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2010 - 2023 Holger Krekel and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9dda53692d2f44a97392cae823f8163d55ad4549
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/iniconfig-2.3.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+iniconfig
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__init__.py b/venv/lib/python3.10/site-packages/jsonschema/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8dec8cfacd0fbf085eeb0851272ddfef2bda9d3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/__init__.py
@@ -0,0 +1,120 @@
+"""
+An implementation of JSON Schema for Python.
+
+The main functionality is provided by the validator classes for each of the
+supported JSON Schema versions.
+
+Most commonly, `jsonschema.validators.validate` is the quickest way to simply
+validate a given instance under a schema, and will create a validator
+for you.
+"""
+import warnings
+
+from jsonschema._format import FormatChecker
+from jsonschema._types import TypeChecker
+from jsonschema.exceptions import SchemaError, ValidationError
+from jsonschema.validators import (
+ Draft3Validator,
+ Draft4Validator,
+ Draft6Validator,
+ Draft7Validator,
+ Draft201909Validator,
+ Draft202012Validator,
+ validate,
+)
+
+
+def __getattr__(name):
+ if name == "__version__":
+ warnings.warn(
+ "Accessing jsonschema.__version__ is deprecated and will be "
+ "removed in a future release. Use importlib.metadata directly "
+ "to query for jsonschema's version.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ from importlib import metadata
+ return metadata.version("jsonschema")
+ elif name == "RefResolver":
+ from jsonschema.validators import _RefResolver
+ warnings.warn(
+ _RefResolver._DEPRECATION_MESSAGE,
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _RefResolver
+ elif name == "ErrorTree":
+ warnings.warn(
+ "Importing ErrorTree directly from the jsonschema package "
+ "is deprecated and will become an ImportError. Import it from "
+ "jsonschema.exceptions instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from jsonschema.exceptions import ErrorTree
+ return ErrorTree
+ elif name == "FormatError":
+ warnings.warn(
+ "Importing FormatError directly from the jsonschema package "
+ "is deprecated and will become an ImportError. Import it from "
+ "jsonschema.exceptions instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from jsonschema.exceptions import FormatError
+ return FormatError
+ elif name == "Validator":
+ warnings.warn(
+ "Importing Validator directly from the jsonschema package "
+ "is deprecated and will become an ImportError. Import it from "
+ "jsonschema.protocols instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from jsonschema.protocols import Validator
+ return Validator
+ elif name == "RefResolutionError":
+ from jsonschema.exceptions import _RefResolutionError
+ warnings.warn(
+ _RefResolutionError._DEPRECATION_MESSAGE,
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _RefResolutionError
+
+ format_checkers = {
+ "draft3_format_checker": Draft3Validator,
+ "draft4_format_checker": Draft4Validator,
+ "draft6_format_checker": Draft6Validator,
+ "draft7_format_checker": Draft7Validator,
+ "draft201909_format_checker": Draft201909Validator,
+ "draft202012_format_checker": Draft202012Validator,
+ }
+ ValidatorForFormat = format_checkers.get(name)
+ if ValidatorForFormat is not None:
+ warnings.warn(
+ f"Accessing jsonschema.{name} is deprecated and will be "
+ "removed in a future release. Instead, use the FORMAT_CHECKER "
+ "attribute on the corresponding Validator.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return ValidatorForFormat.FORMAT_CHECKER
+
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+__all__ = [
+ "Draft3Validator",
+ "Draft4Validator",
+ "Draft6Validator",
+ "Draft7Validator",
+ "Draft201909Validator",
+ "Draft202012Validator",
+ "FormatChecker",
+ "SchemaError",
+ "TypeChecker",
+ "ValidationError",
+ "validate",
+]
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__main__.py b/venv/lib/python3.10/site-packages/jsonschema/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb260ae145d7518f8e8fa16ed13cc2c6173e7404
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/__main__.py
@@ -0,0 +1,6 @@
+"""
+The jsonschema CLI is now deprecated in favor of check-jsonschema.
+"""
+from jsonschema.cli import main
+
+main()
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9744cc6d8185785e8aab7c3c1af7225874c1c9ca
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__main__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcf190ec5fbfe31d125c177546e7055e23105a25
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/__main__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_format.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_format.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbcee7df64cc5bab1dd8e1387fcfe8da1045ae21
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_format.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_keywords.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_keywords.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b5fdc8b714802b82cf47b036fc19870a317b541
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_keywords.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ac278520153bf22b82ed8c4f03f286c7a5a8304
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_types.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98a38a824580ebe27435f60c732eb2c95d1f9ea0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_types.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23d2fe36fa188a6b1675bbdc7f350e350b95b66e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..947537fc4aa6bc8277d0c125dba3cde0c1573ae1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/cli.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c08cf6db5a052ed0111a8b90e37432d581c5c388
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/cli.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5227071cd9da5660c6876943a57bd3ead551a17
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/protocols.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/protocols.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..158690539b47e4fa22271c926f8e543934d2dd36
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/protocols.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/__pycache__/validators.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/validators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba60ef7ae6e031e2fa8f5bafdd67da09f2fbc314
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/__pycache__/validators.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_format.py b/venv/lib/python3.10/site-packages/jsonschema/_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fc7a01e12c0ffc9d853cedc36db86633a039c4c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_format.py
@@ -0,0 +1,546 @@
+from __future__ import annotations
+
+from contextlib import suppress
+from datetime import date, datetime
+from uuid import UUID
+import ipaddress
+import re
+import typing
+import warnings
+
+from jsonschema.exceptions import FormatError
+
+_FormatCheckCallable = typing.Callable[[object], bool]
+#: A format checker callable.
+_F = typing.TypeVar("_F", bound=_FormatCheckCallable)
+_RaisesType = typing.Union[type[Exception], tuple[type[Exception], ...]]
+
+_RE_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$", re.ASCII)
+
+
+class FormatChecker:
+ """
+ A ``format`` property checker.
+
+ JSON Schema does not mandate that the ``format`` property actually do any
+ validation. If validation is desired however, instances of this class can
+ be hooked into validators to enable format validation.
+
+ `FormatChecker` objects always return ``True`` when asked about
+ formats that they do not know how to validate.
+
+ To add a check for a custom format use the `FormatChecker.checks`
+ decorator.
+
+ Arguments:
+
+ formats:
+
+ The known formats to validate. This argument can be used to
+ limit which formats will be used during validation.
+
+ """
+
+ checkers: dict[
+ str,
+ tuple[_FormatCheckCallable, _RaisesType],
+ ] = {} # noqa: RUF012
+
+ def __init__(self, formats: typing.Iterable[str] | None = None):
+ if formats is None:
+ formats = self.checkers.keys()
+ self.checkers = {k: self.checkers[k] for k in formats}
+
+ def __repr__(self):
+ return f""
+
+ def checks(
+ self, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ """
+ Register a decorated function as validating a new format.
+
+ Arguments:
+
+ format:
+
+ The format that the decorated function will check.
+
+ raises:
+
+ The exception(s) raised by the decorated function when an
+ invalid instance is found.
+
+ The exception object will be accessible as the
+ `jsonschema.exceptions.ValidationError.cause` attribute of the
+ resulting validation error.
+
+ """
+
+ def _checks(func: _F) -> _F:
+ self.checkers[format] = (func, raises)
+ return func
+
+ return _checks
+
+ @classmethod
+ def cls_checks(
+ cls, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ warnings.warn(
+ (
+ "FormatChecker.cls_checks is deprecated. Call "
+ "FormatChecker.checks on a specific FormatChecker instance "
+ "instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return cls._cls_checks(format=format, raises=raises)
+
+ @classmethod
+ def _cls_checks(
+ cls, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ def _checks(func: _F) -> _F:
+ cls.checkers[format] = (func, raises)
+ return func
+
+ return _checks
+
+ def check(self, instance: object, format: str) -> None:
+ """
+ Check whether the instance conforms to the given format.
+
+ Arguments:
+
+ instance (*any primitive type*, i.e. str, number, bool):
+
+ The instance to check
+
+ format:
+
+ The format that instance should conform to
+
+ Raises:
+
+ FormatError:
+
+ if the instance does not conform to ``format``
+
+ """
+ if format not in self.checkers:
+ return
+
+ func, raises = self.checkers[format]
+ result, cause = None, None
+ try:
+ result = func(instance)
+ except raises as e:
+ cause = e
+ if not result:
+ raise FormatError(f"{instance!r} is not a {format!r}", cause=cause)
+
+ def conforms(self, instance: object, format: str) -> bool:
+ """
+ Check whether the instance conforms to the given format.
+
+ Arguments:
+
+ instance (*any primitive type*, i.e. str, number, bool):
+
+ The instance to check
+
+ format:
+
+ The format that instance should conform to
+
+ Returns:
+
+ bool: whether it conformed
+
+ """
+ try:
+ self.check(instance, format)
+ except FormatError:
+ return False
+ else:
+ return True
+
+
+draft3_format_checker = FormatChecker()
+draft4_format_checker = FormatChecker()
+draft6_format_checker = FormatChecker()
+draft7_format_checker = FormatChecker()
+draft201909_format_checker = FormatChecker()
+draft202012_format_checker = FormatChecker()
+
+_draft_checkers: dict[str, FormatChecker] = dict(
+ draft3=draft3_format_checker,
+ draft4=draft4_format_checker,
+ draft6=draft6_format_checker,
+ draft7=draft7_format_checker,
+ draft201909=draft201909_format_checker,
+ draft202012=draft202012_format_checker,
+)
+
+
+def _checks_drafts(
+ name=None,
+ draft3=None,
+ draft4=None,
+ draft6=None,
+ draft7=None,
+ draft201909=None,
+ draft202012=None,
+ raises=(),
+) -> typing.Callable[[_F], _F]:
+ draft3 = draft3 or name
+ draft4 = draft4 or name
+ draft6 = draft6 or name
+ draft7 = draft7 or name
+ draft201909 = draft201909 or name
+ draft202012 = draft202012 or name
+
+ def wrap(func: _F) -> _F:
+ if draft3:
+ func = _draft_checkers["draft3"].checks(draft3, raises)(func)
+ if draft4:
+ func = _draft_checkers["draft4"].checks(draft4, raises)(func)
+ if draft6:
+ func = _draft_checkers["draft6"].checks(draft6, raises)(func)
+ if draft7:
+ func = _draft_checkers["draft7"].checks(draft7, raises)(func)
+ if draft201909:
+ func = _draft_checkers["draft201909"].checks(draft201909, raises)(
+ func,
+ )
+ if draft202012:
+ func = _draft_checkers["draft202012"].checks(draft202012, raises)(
+ func,
+ )
+
+ # Oy. This is bad global state, but relied upon for now, until
+ # deprecation. See #519 and test_format_checkers_come_with_defaults
+ FormatChecker._cls_checks(
+ draft202012 or draft201909 or draft7 or draft6 or draft4 or draft3,
+ raises,
+ )(func)
+ return func
+
+ return wrap
+
+
+@_checks_drafts(name="idn-email")
+@_checks_drafts(name="email")
+def is_email(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return "@" in instance
+
+
+@_checks_drafts(
+ draft3="ip-address",
+ draft4="ipv4",
+ draft6="ipv4",
+ draft7="ipv4",
+ draft201909="ipv4",
+ draft202012="ipv4",
+ raises=ipaddress.AddressValueError,
+)
+def is_ipv4(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(ipaddress.IPv4Address(instance))
+
+
+@_checks_drafts(name="ipv6", raises=ipaddress.AddressValueError)
+def is_ipv6(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ address = ipaddress.IPv6Address(instance)
+ return not getattr(address, "scope_id", "")
+
+
+with suppress(ImportError):
+ from fqdn import FQDN
+
+ @_checks_drafts(
+ draft3="host-name",
+ draft4="hostname",
+ draft6="hostname",
+ draft7="hostname",
+ draft201909="hostname",
+ draft202012="hostname",
+ # fqdn.FQDN("") raises a ValueError due to a bug
+ # however, it's not clear when or if that will be fixed, so catch it
+ # here for now
+ raises=ValueError,
+ )
+ def is_host_name(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return FQDN(instance, min_labels=1).is_valid
+
+
+with suppress(ImportError):
+ # The built-in `idna` codec only implements RFC 3890, so we go elsewhere.
+ import idna
+
+ @_checks_drafts(
+ draft7="idn-hostname",
+ draft201909="idn-hostname",
+ draft202012="idn-hostname",
+ raises=(idna.IDNAError, UnicodeError),
+ )
+ def is_idn_host_name(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ idna.encode(instance)
+ return True
+
+
+try:
+ import rfc3987
+except ImportError:
+ with suppress(ImportError):
+ from rfc3986_validator import validate_rfc3986
+
+ @_checks_drafts(name="uri")
+ def is_uri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3986(instance, rule="URI")
+
+ @_checks_drafts(
+ draft6="uri-reference",
+ draft7="uri-reference",
+ draft201909="uri-reference",
+ draft202012="uri-reference",
+ raises=ValueError,
+ )
+ def is_uri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3986(instance, rule="URI_reference")
+
+ with suppress(ImportError):
+ from rfc3987_syntax import is_valid_syntax as _rfc3987_is_valid_syntax
+
+ @_checks_drafts(
+ draft7="iri",
+ draft201909="iri",
+ draft202012="iri",
+ raises=ValueError,
+ )
+ def is_iri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return _rfc3987_is_valid_syntax("iri", instance)
+
+ @_checks_drafts(
+ draft7="iri-reference",
+ draft201909="iri-reference",
+ draft202012="iri-reference",
+ raises=ValueError,
+ )
+ def is_iri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return _rfc3987_is_valid_syntax("iri_reference", instance)
+
+else:
+
+ @_checks_drafts(
+ draft7="iri",
+ draft201909="iri",
+ draft202012="iri",
+ raises=ValueError,
+ )
+ def is_iri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="IRI")
+
+ @_checks_drafts(
+ draft7="iri-reference",
+ draft201909="iri-reference",
+ draft202012="iri-reference",
+ raises=ValueError,
+ )
+ def is_iri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="IRI_reference")
+
+ @_checks_drafts(name="uri", raises=ValueError)
+ def is_uri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="URI")
+
+ @_checks_drafts(
+ draft6="uri-reference",
+ draft7="uri-reference",
+ draft201909="uri-reference",
+ draft202012="uri-reference",
+ raises=ValueError,
+ )
+ def is_uri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="URI_reference")
+
+
+with suppress(ImportError):
+ from rfc3339_validator import validate_rfc3339
+
+ @_checks_drafts(name="date-time")
+ def is_datetime(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3339(instance.upper())
+
+ @_checks_drafts(
+ draft7="time",
+ draft201909="time",
+ draft202012="time",
+ )
+ def is_time(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return is_datetime("1970-01-01T" + instance)
+
+
+@_checks_drafts(name="regex", raises=re.error)
+def is_regex(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(re.compile(instance))
+
+
+@_checks_drafts(
+ draft3="date",
+ draft7="date",
+ draft201909="date",
+ draft202012="date",
+ raises=ValueError,
+)
+def is_date(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(_RE_DATE.fullmatch(instance) and date.fromisoformat(instance))
+
+
+@_checks_drafts(draft3="time", raises=ValueError)
+def is_draft3_time(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(datetime.strptime(instance, "%H:%M:%S")) # noqa: DTZ007
+
+
+with suppress(ImportError):
+ import webcolors
+
+ @_checks_drafts(draft3="color", raises=(ValueError, TypeError))
+ def is_css21_color(instance: object) -> bool:
+ if isinstance(instance, str):
+ try:
+ webcolors.name_to_hex(instance)
+ except ValueError:
+ webcolors.normalize_hex(instance.lower())
+ return True
+
+
+with suppress(ImportError):
+ import jsonpointer
+
+ @_checks_drafts(
+ draft6="json-pointer",
+ draft7="json-pointer",
+ draft201909="json-pointer",
+ draft202012="json-pointer",
+ raises=jsonpointer.JsonPointerException,
+ )
+ def is_json_pointer(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(jsonpointer.JsonPointer(instance))
+
+ # TODO: I don't want to maintain this, so it
+ # needs to go either into jsonpointer (pending
+ # https://github.com/stefankoegl/python-json-pointer/issues/34) or
+ # into a new external library.
+ @_checks_drafts(
+ draft7="relative-json-pointer",
+ draft201909="relative-json-pointer",
+ draft202012="relative-json-pointer",
+ raises=jsonpointer.JsonPointerException,
+ )
+ def is_relative_json_pointer(instance: object) -> bool:
+ # Definition taken from:
+ # https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3
+ if not isinstance(instance, str):
+ return True
+ if not instance:
+ return False
+
+ non_negative_integer, rest = [], ""
+ for i, character in enumerate(instance):
+ if character.isdigit():
+ # digits with a leading "0" are not allowed
+ if i > 0 and int(instance[i - 1]) == 0:
+ return False
+
+ non_negative_integer.append(character)
+ continue
+
+ if not non_negative_integer:
+ return False
+
+ rest = instance[i:]
+ break
+ return (rest == "#") or bool(jsonpointer.JsonPointer(rest))
+
+
+with suppress(ImportError):
+ import uri_template
+
+ @_checks_drafts(
+ draft6="uri-template",
+ draft7="uri-template",
+ draft201909="uri-template",
+ draft202012="uri-template",
+ )
+ def is_uri_template(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return uri_template.validate(instance)
+
+
+with suppress(ImportError):
+ import isoduration
+
+ @_checks_drafts(
+ draft201909="duration",
+ draft202012="duration",
+ raises=isoduration.DurationParsingException,
+ )
+ def is_duration(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ isoduration.parse_duration(instance)
+ # FIXME: See bolsote/isoduration#25 and bolsote/isoduration#21
+ return instance.endswith(tuple("DMYWHMS"))
+
+
+@_checks_drafts(
+ draft201909="uuid",
+ draft202012="uuid",
+ raises=ValueError,
+)
+def is_uuid(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ UUID(instance)
+ return all(instance[position] == "-" for position in (8, 13, 18, 23))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_keywords.py b/venv/lib/python3.10/site-packages/jsonschema/_keywords.py
new file mode 100644
index 0000000000000000000000000000000000000000..f30f954192abeef3a031c37ddcfd6a9831e4e247
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_keywords.py
@@ -0,0 +1,449 @@
+from fractions import Fraction
+import re
+
+from jsonschema._utils import (
+ ensure_list,
+ equal,
+ extras_msg,
+ find_additional_properties,
+ find_evaluated_item_indexes_by_schema,
+ find_evaluated_property_keys_by_schema,
+ uniq,
+)
+from jsonschema.exceptions import FormatError, ValidationError
+
+
+def patternProperties(validator, patternProperties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for pattern, subschema in patternProperties.items():
+ for k, v in instance.items():
+ if re.search(pattern, k):
+ yield from validator.descend(
+ v, subschema, path=k, schema_path=pattern,
+ )
+
+
+def propertyNames(validator, propertyNames, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property in instance:
+ yield from validator.descend(instance=property, schema=propertyNames)
+
+
+def additionalProperties(validator, aP, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ extras = set(find_additional_properties(instance, schema))
+
+ if validator.is_type(aP, "object"):
+ for extra in extras:
+ yield from validator.descend(instance[extra], aP, path=extra)
+ elif not aP and extras:
+ if "patternProperties" in schema:
+ verb = "does" if len(extras) == 1 else "do"
+ joined = ", ".join(repr(each) for each in sorted(extras))
+ patterns = ", ".join(
+ repr(each) for each in sorted(schema["patternProperties"])
+ )
+ error = f"{joined} {verb} not match any of the regexes: {patterns}"
+ yield ValidationError(error)
+ else:
+ error = "Additional properties are not allowed (%s %s unexpected)"
+ yield ValidationError(error % extras_msg(sorted(extras, key=str)))
+
+
+def items(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ prefix = len(schema.get("prefixItems", []))
+ total = len(instance)
+ extra = total - prefix
+ if extra <= 0:
+ return
+
+ if items is False:
+ rest = instance[prefix:] if extra != 1 else instance[prefix]
+ item = "items" if prefix != 1 else "item"
+ yield ValidationError(
+ f"Expected at most {prefix} {item} but found {extra} "
+ f"extra: {rest!r}",
+ )
+ else:
+ for index in range(prefix, total):
+ yield from validator.descend(
+ instance=instance[index],
+ schema=items,
+ path=index,
+ )
+
+
+def const(validator, const, instance, schema):
+ if not equal(instance, const):
+ yield ValidationError(f"{const!r} was expected")
+
+
+def contains(validator, contains, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ matches = 0
+ min_contains = schema.get("minContains", 1)
+ max_contains = schema.get("maxContains", len(instance))
+
+ contains_validator = validator.evolve(schema=contains)
+
+ for each in instance:
+ if contains_validator.is_valid(each):
+ matches += 1
+ if matches > max_contains:
+ yield ValidationError(
+ "Too many items match the given schema "
+ f"(expected at most {max_contains})",
+ validator="maxContains",
+ validator_value=max_contains,
+ )
+ return
+
+ if matches < min_contains:
+ if not matches:
+ yield ValidationError(
+ f"{instance!r} does not contain items "
+ "matching the given schema",
+ )
+ else:
+ yield ValidationError(
+ "Too few items match the given schema (expected at least "
+ f"{min_contains} but only {matches} matched)",
+ validator="minContains",
+ validator_value=min_contains,
+ )
+
+
+def exclusiveMinimum(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance <= minimum:
+ yield ValidationError(
+ f"{instance!r} is less than or equal to "
+ f"the minimum of {minimum!r}",
+ )
+
+
+def exclusiveMaximum(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance >= maximum:
+ yield ValidationError(
+ f"{instance!r} is greater than or equal "
+ f"to the maximum of {maximum!r}",
+ )
+
+
+def minimum(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance < minimum:
+ message = f"{instance!r} is less than the minimum of {minimum!r}"
+ yield ValidationError(message)
+
+
+def maximum(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance > maximum:
+ message = f"{instance!r} is greater than the maximum of {maximum!r}"
+ yield ValidationError(message)
+
+
+def multipleOf(validator, dB, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if isinstance(dB, float):
+ quotient = instance / dB
+ try:
+ failed = int(quotient) != quotient
+ except OverflowError:
+ # When `instance` is large and `dB` is less than one,
+ # quotient can overflow to infinity; and then casting to int
+ # raises an error.
+ #
+ # In this case we fall back to Fraction logic, which is
+ # exact and cannot overflow. The performance is also
+ # acceptable: we try the fast all-float option first, and
+ # we know that fraction(dB) can have at most a few hundred
+ # digits in each part. The worst-case slowdown is therefore
+ # for already-slow enormous integers or Decimals.
+ failed = (Fraction(instance) / Fraction(dB)).denominator != 1
+ else:
+ failed = instance % dB
+
+ if failed:
+ yield ValidationError(f"{instance!r} is not a multiple of {dB}")
+
+
+def minItems(validator, mI, instance, schema):
+ if validator.is_type(instance, "array") and len(instance) < mI:
+ message = "should be non-empty" if mI == 1 else "is too short"
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def maxItems(validator, mI, instance, schema):
+ if validator.is_type(instance, "array") and len(instance) > mI:
+ message = "is expected to be empty" if mI == 0 else "is too long"
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def uniqueItems(validator, uI, instance, schema):
+ if (
+ uI
+ and validator.is_type(instance, "array")
+ and not uniq(instance)
+ ):
+ yield ValidationError(f"{instance!r} has non-unique elements")
+
+
+def pattern(validator, patrn, instance, schema):
+ if (
+ validator.is_type(instance, "string")
+ and not re.search(patrn, instance)
+ ):
+ yield ValidationError(f"{instance!r} does not match {patrn!r}")
+
+
+def format(validator, format, instance, schema):
+ if validator.format_checker is not None:
+ try:
+ validator.format_checker.check(instance, format)
+ except FormatError as error:
+ yield ValidationError(error.message, cause=error.cause)
+
+
+def minLength(validator, mL, instance, schema):
+ if validator.is_type(instance, "string") and len(instance) < mL:
+ message = "should be non-empty" if mL == 1 else "is too short"
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def maxLength(validator, mL, instance, schema):
+ if validator.is_type(instance, "string") and len(instance) > mL:
+ message = "is expected to be empty" if mL == 0 else "is too long"
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def dependentRequired(validator, dependentRequired, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependentRequired.items():
+ if property not in instance:
+ continue
+
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+
+
+def dependentSchemas(validator, dependentSchemas, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependentSchemas.items():
+ if property not in instance:
+ continue
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+
+
+def enum(validator, enums, instance, schema):
+ if all(not equal(each, instance) for each in enums):
+ yield ValidationError(f"{instance!r} is not one of {enums!r}")
+
+
+def ref(validator, ref, instance, schema):
+ yield from validator._validate_reference(ref=ref, instance=instance)
+
+
+def dynamicRef(validator, dynamicRef, instance, schema):
+ yield from validator._validate_reference(ref=dynamicRef, instance=instance)
+
+
+def type(validator, types, instance, schema):
+ types = ensure_list(types)
+
+ if not any(validator.is_type(instance, type) for type in types):
+ reprs = ", ".join(repr(type) for type in types)
+ yield ValidationError(f"{instance!r} is not of type {reprs}")
+
+
+def properties(validator, properties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, subschema in properties.items():
+ if property in instance:
+ yield from validator.descend(
+ instance[property],
+ subschema,
+ path=property,
+ schema_path=property,
+ )
+
+
+def required(validator, required, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ for property in required:
+ if property not in instance:
+ yield ValidationError(f"{property!r} is a required property")
+
+
+def minProperties(validator, mP, instance, schema):
+ if validator.is_type(instance, "object") and len(instance) < mP:
+ message = (
+ "should be non-empty" if mP == 1
+ else "does not have enough properties"
+ )
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def maxProperties(validator, mP, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ if validator.is_type(instance, "object") and len(instance) > mP:
+ message = (
+ "is expected to be empty" if mP == 0
+ else "has too many properties"
+ )
+ yield ValidationError(f"{instance!r} {message}")
+
+
+def allOf(validator, allOf, instance, schema):
+ for index, subschema in enumerate(allOf):
+ yield from validator.descend(instance, subschema, schema_path=index)
+
+
+def anyOf(validator, anyOf, instance, schema):
+ all_errors = []
+ for index, subschema in enumerate(anyOf):
+ errs = list(validator.descend(instance, subschema, schema_path=index))
+ if not errs:
+ break
+ all_errors.extend(errs)
+ else:
+ yield ValidationError(
+ f"{instance!r} is not valid under any of the given schemas",
+ context=all_errors,
+ )
+
+
+def oneOf(validator, oneOf, instance, schema):
+ subschemas = enumerate(oneOf)
+ all_errors = []
+ for index, subschema in subschemas:
+ errs = list(validator.descend(instance, subschema, schema_path=index))
+ if not errs:
+ first_valid = subschema
+ break
+ all_errors.extend(errs)
+ else:
+ yield ValidationError(
+ f"{instance!r} is not valid under any of the given schemas",
+ context=all_errors,
+ )
+
+ more_valid = [
+ each for _, each in subschemas
+ if validator.evolve(schema=each).is_valid(instance)
+ ]
+ if more_valid:
+ more_valid.append(first_valid)
+ reprs = ", ".join(repr(schema) for schema in more_valid)
+ yield ValidationError(f"{instance!r} is valid under each of {reprs}")
+
+
+def not_(validator, not_schema, instance, schema):
+ if validator.evolve(schema=not_schema).is_valid(instance):
+ message = f"{instance!r} should not be valid under {not_schema!r}"
+ yield ValidationError(message)
+
+
+def if_(validator, if_schema, instance, schema):
+ if validator.evolve(schema=if_schema).is_valid(instance):
+ if "then" in schema:
+ then = schema["then"]
+ yield from validator.descend(instance, then, schema_path="then")
+ elif "else" in schema:
+ else_ = schema["else"]
+ yield from validator.descend(instance, else_, schema_path="else")
+
+
+def unevaluatedItems(validator, unevaluatedItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+ evaluated_item_indexes = find_evaluated_item_indexes_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_items = [
+ item for index, item in enumerate(instance)
+ if index not in evaluated_item_indexes
+ ]
+ if unevaluated_items:
+ error = "Unevaluated items are not allowed (%s %s unexpected)"
+ yield ValidationError(error % extras_msg(unevaluated_items))
+
+
+def unevaluatedProperties(validator, unevaluatedProperties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ evaluated_keys = find_evaluated_property_keys_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_keys = []
+ for property in instance:
+ if property not in evaluated_keys:
+ for _ in validator.descend(
+ instance[property],
+ unevaluatedProperties,
+ path=property,
+ schema_path=property,
+ ):
+ # FIXME: Include context for each unevaluated property
+ # indicating why it's invalid under the subschema.
+ unevaluated_keys.append(property) # noqa: PERF401
+
+ if unevaluated_keys:
+ if unevaluatedProperties is False:
+ error = "Unevaluated properties are not allowed (%s %s unexpected)"
+ extras = sorted(unevaluated_keys, key=str)
+ yield ValidationError(error % extras_msg(extras))
+ else:
+ error = (
+ "Unevaluated properties are not valid under "
+ "the given schema (%s %s unevaluated and invalid)"
+ )
+ yield ValidationError(error % extras_msg(unevaluated_keys))
+
+
+def prefixItems(validator, prefixItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ for (index, item), subschema in zip(enumerate(instance), prefixItems):
+ yield from validator.descend(
+ instance=item,
+ schema=subschema,
+ schema_path=index,
+ path=index,
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_legacy_keywords.py b/venv/lib/python3.10/site-packages/jsonschema/_legacy_keywords.py
new file mode 100644
index 0000000000000000000000000000000000000000..c691589f8f69fdbbc0152728121361665de08f00
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_legacy_keywords.py
@@ -0,0 +1,449 @@
+import re
+
+from referencing.jsonschema import lookup_recursive_ref
+
+from jsonschema import _utils
+from jsonschema.exceptions import ValidationError
+
+
+def ignore_ref_siblings(schema):
+ """
+ Ignore siblings of ``$ref`` if it is present.
+
+ Otherwise, return all keywords.
+
+ Suitable for use with `create`'s ``applicable_validators`` argument.
+ """
+ ref = schema.get("$ref")
+ if ref is not None:
+ return [("$ref", ref)]
+ else:
+ return schema.items()
+
+
+def dependencies_draft3(validator, dependencies, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependencies.items():
+ if property not in instance:
+ continue
+
+ if validator.is_type(dependency, "object"):
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+ elif validator.is_type(dependency, "string"):
+ if dependency not in instance:
+ message = f"{dependency!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+ else:
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+
+
+def dependencies_draft4_draft6_draft7(
+ validator,
+ dependencies,
+ instance,
+ schema,
+):
+ """
+ Support for the ``dependencies`` keyword from pre-draft 2019-09.
+
+ In later drafts, the keyword was split into separate
+ ``dependentRequired`` and ``dependentSchemas`` validators.
+ """
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependencies.items():
+ if property not in instance:
+ continue
+
+ if validator.is_type(dependency, "array"):
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+ else:
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+
+
+def disallow_draft3(validator, disallow, instance, schema):
+ for disallowed in _utils.ensure_list(disallow):
+ if validator.evolve(schema={"type": [disallowed]}).is_valid(instance):
+ message = f"{disallowed!r} is disallowed for {instance!r}"
+ yield ValidationError(message)
+
+
+def extends_draft3(validator, extends, instance, schema):
+ if validator.is_type(extends, "object"):
+ yield from validator.descend(instance, extends)
+ return
+ for index, subschema in enumerate(extends):
+ yield from validator.descend(instance, subschema, schema_path=index)
+
+
+def items_draft3_draft4(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if validator.is_type(items, "object"):
+ for index, item in enumerate(instance):
+ yield from validator.descend(item, items, path=index)
+ else:
+ for (index, item), subschema in zip(enumerate(instance), items):
+ yield from validator.descend(
+ item, subschema, path=index, schema_path=index,
+ )
+
+
+def additionalItems(validator, aI, instance, schema):
+ if (
+ not validator.is_type(instance, "array")
+ or validator.is_type(schema.get("items", {}), "object")
+ ):
+ return
+
+ len_items = len(schema.get("items", []))
+ if validator.is_type(aI, "object"):
+ for index, item in enumerate(instance[len_items:], start=len_items):
+ yield from validator.descend(item, aI, path=index)
+ elif not aI and len(instance) > len(schema.get("items", [])):
+ error = "Additional items are not allowed (%s %s unexpected)"
+ yield ValidationError(
+ error % _utils.extras_msg(instance[len(schema.get("items", [])):]),
+ )
+
+
+def items_draft6_draft7_draft201909(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if validator.is_type(items, "array"):
+ for (index, item), subschema in zip(enumerate(instance), items):
+ yield from validator.descend(
+ item, subschema, path=index, schema_path=index,
+ )
+ else:
+ for index, item in enumerate(instance):
+ yield from validator.descend(item, items, path=index)
+
+
+def minimum_draft3_draft4(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if schema.get("exclusiveMinimum", False):
+ failed = instance <= minimum
+ cmp = "less than or equal to"
+ else:
+ failed = instance < minimum
+ cmp = "less than"
+
+ if failed:
+ message = f"{instance!r} is {cmp} the minimum of {minimum!r}"
+ yield ValidationError(message)
+
+
+def maximum_draft3_draft4(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if schema.get("exclusiveMaximum", False):
+ failed = instance >= maximum
+ cmp = "greater than or equal to"
+ else:
+ failed = instance > maximum
+ cmp = "greater than"
+
+ if failed:
+ message = f"{instance!r} is {cmp} the maximum of {maximum!r}"
+ yield ValidationError(message)
+
+
+def properties_draft3(validator, properties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, subschema in properties.items():
+ if property in instance:
+ yield from validator.descend(
+ instance[property],
+ subschema,
+ path=property,
+ schema_path=property,
+ )
+ elif subschema.get("required", False):
+ error = ValidationError(f"{property!r} is a required property")
+ error._set(
+ validator="required",
+ validator_value=subschema["required"],
+ instance=instance,
+ schema=schema,
+ )
+ error.path.appendleft(property)
+ error.schema_path.extend([property, "required"])
+ yield error
+
+
+def type_draft3(validator, types, instance, schema):
+ types = _utils.ensure_list(types)
+
+ all_errors = []
+ for index, type in enumerate(types):
+ if validator.is_type(type, "object"):
+ errors = list(validator.descend(instance, type, schema_path=index))
+ if not errors:
+ return
+ all_errors.extend(errors)
+ elif validator.is_type(instance, type):
+ return
+
+ reprs = []
+ for type in types:
+ try:
+ reprs.append(repr(type["name"]))
+ except Exception: # noqa: BLE001
+ reprs.append(repr(type))
+ yield ValidationError(
+ f"{instance!r} is not of type {', '.join(reprs)}",
+ context=all_errors,
+ )
+
+
+def contains_draft6_draft7(validator, contains, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if not any(
+ validator.evolve(schema=contains).is_valid(element)
+ for element in instance
+ ):
+ yield ValidationError(
+ f"None of {instance!r} are valid under the given schema",
+ )
+
+
+def recursiveRef(validator, recursiveRef, instance, schema):
+ resolved = lookup_recursive_ref(validator._resolver)
+ yield from validator.descend(
+ instance,
+ resolved.contents,
+ resolver=resolved.resolver,
+ )
+
+
+def find_evaluated_item_indexes_by_schema(validator, instance, schema):
+ """
+ Get all indexes of items that get evaluated under the current schema.
+
+ Covers all keywords related to unevaluatedItems: items, prefixItems, if,
+ then, else, contains, unevaluatedItems, allOf, oneOf, anyOf
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_indexes = []
+
+ ref = schema.get("$ref")
+ if ref is not None:
+ resolved = validator._resolver.lookup(ref)
+ evaluated_indexes.extend(
+ find_evaluated_item_indexes_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ if "$recursiveRef" in schema:
+ resolved = lookup_recursive_ref(validator._resolver)
+ evaluated_indexes.extend(
+ find_evaluated_item_indexes_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ if "items" in schema:
+ if "additionalItems" in schema:
+ return list(range(len(instance)))
+
+ if validator.is_type(schema["items"], "object"):
+ return list(range(len(instance)))
+ evaluated_indexes += list(range(len(schema["items"])))
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["then"],
+ )
+ elif "else" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ for keyword in ["contains", "unevaluatedItems"]:
+ if keyword in schema:
+ for k, v in enumerate(instance):
+ if validator.evolve(schema=schema[keyword]).is_valid(v):
+ evaluated_indexes.append(k)
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = next(validator.descend(instance, subschema), None)
+ if errs is None:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, subschema,
+ )
+
+ return evaluated_indexes
+
+
+def unevaluatedItems_draft2019(validator, unevaluatedItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+ evaluated_item_indexes = find_evaluated_item_indexes_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_items = [
+ item for index, item in enumerate(instance)
+ if index not in evaluated_item_indexes
+ ]
+ if unevaluated_items:
+ error = "Unevaluated items are not allowed (%s %s unexpected)"
+ yield ValidationError(error % _utils.extras_msg(unevaluated_items))
+
+
+def find_evaluated_property_keys_by_schema(validator, instance, schema):
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_keys = []
+
+ ref = schema.get("$ref")
+ if ref is not None:
+ resolved = validator._resolver.lookup(ref)
+ evaluated_keys.extend(
+ find_evaluated_property_keys_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ if "$recursiveRef" in schema:
+ resolved = lookup_recursive_ref(validator._resolver)
+ evaluated_keys.extend(
+ find_evaluated_property_keys_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ for keyword in [
+ "properties", "additionalProperties", "unevaluatedProperties",
+ ]:
+ if keyword in schema:
+ schema_value = schema[keyword]
+ if validator.is_type(schema_value, "boolean") and schema_value:
+ evaluated_keys += instance.keys()
+
+ elif validator.is_type(schema_value, "object"):
+ for property in schema_value:
+ if property in instance:
+ evaluated_keys.append(property)
+
+ if "patternProperties" in schema:
+ for property in instance:
+ for pattern in schema["patternProperties"]:
+ if re.search(pattern, property):
+ evaluated_keys.append(property)
+
+ if "dependentSchemas" in schema:
+ for property, subschema in schema["dependentSchemas"].items():
+ if property not in instance:
+ continue
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = next(validator.descend(instance, subschema), None)
+ if errs is None:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["then"],
+ )
+ elif "else" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ return evaluated_keys
+
+
+def unevaluatedProperties_draft2019(validator, uP, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ evaluated_keys = find_evaluated_property_keys_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_keys = []
+ for property in instance:
+ if property not in evaluated_keys:
+ for _ in validator.descend(
+ instance[property],
+ uP,
+ path=property,
+ schema_path=property,
+ ):
+ # FIXME: Include context for each unevaluated property
+ # indicating why it's invalid under the subschema.
+ unevaluated_keys.append(property) # noqa: PERF401
+
+ if unevaluated_keys:
+ if uP is False:
+ error = "Unevaluated properties are not allowed (%s %s unexpected)"
+ extras = sorted(unevaluated_keys, key=str)
+ yield ValidationError(error % _utils.extras_msg(extras))
+ else:
+ error = (
+ "Unevaluated properties are not valid under "
+ "the given schema (%s %s unevaluated and invalid)"
+ )
+ yield ValidationError(error % _utils.extras_msg(unevaluated_keys))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_types.py b/venv/lib/python3.10/site-packages/jsonschema/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3ce9d6672d471b0b3613e8dfd1b4035f1805cf5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_types.py
@@ -0,0 +1,204 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+import numbers
+
+from attrs import evolve, field, frozen
+from rpds import HashTrieMap
+
+from jsonschema.exceptions import UndefinedTypeCheck
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+ from typing import Any, Callable
+
+
+# unfortunately, the type of HashTrieMap is generic, and if used as an attrs
+# converter, the generic type is presented to mypy, which then fails to match
+# the concrete type of a type checker mapping
+# this "do nothing" wrapper presents the correct information to mypy
+def _typed_map_converter(
+ init_val: Mapping[str, Callable[[TypeChecker, Any], bool]],
+) -> HashTrieMap[str, Callable[[TypeChecker, Any], bool]]:
+ return HashTrieMap.convert(init_val)
+
+
+def is_array(checker, instance):
+ return isinstance(instance, list)
+
+
+def is_bool(checker, instance):
+ return isinstance(instance, bool)
+
+
+def is_integer(checker, instance):
+ # bool inherits from int, so ensure bools aren't reported as ints
+ if isinstance(instance, bool):
+ return False
+ return isinstance(instance, int)
+
+
+def is_null(checker, instance):
+ return instance is None
+
+
+def is_number(checker, instance):
+ # bool inherits from int, so ensure bools aren't reported as ints
+ if isinstance(instance, bool):
+ return False
+ return isinstance(instance, numbers.Number)
+
+
+def is_object(checker, instance):
+ return isinstance(instance, dict)
+
+
+def is_string(checker, instance):
+ return isinstance(instance, str)
+
+
+def is_any(checker, instance):
+ return True
+
+
+@frozen(repr=False)
+class TypeChecker:
+ """
+ A :kw:`type` property checker.
+
+ A `TypeChecker` performs type checking for a `Validator`, converting
+ between the defined JSON Schema types and some associated Python types or
+ objects.
+
+ Modifying the behavior just mentioned by redefining which Python objects
+ are considered to be of which JSON Schema types can be done using
+ `TypeChecker.redefine` or `TypeChecker.redefine_many`, and types can be
+ removed via `TypeChecker.remove`. Each of these return a new `TypeChecker`.
+
+ Arguments:
+
+ type_checkers:
+
+ The initial mapping of types to their checking functions.
+
+ """
+
+ _type_checkers: HashTrieMap[
+ str, Callable[[TypeChecker, Any], bool],
+ ] = field(default=HashTrieMap(), converter=_typed_map_converter)
+
+ def __repr__(self):
+ types = ", ".join(repr(k) for k in sorted(self._type_checkers))
+ return f"<{self.__class__.__name__} types={{{types}}}>"
+
+ def is_type(self, instance, type: str) -> bool:
+ """
+ Check if the instance is of the appropriate type.
+
+ Arguments:
+
+ instance:
+
+ The instance to check
+
+ type:
+
+ The name of the type that is expected.
+
+ Raises:
+
+ `jsonschema.exceptions.UndefinedTypeCheck`:
+
+ if ``type`` is unknown to this object.
+
+ """
+ try:
+ fn = self._type_checkers[type]
+ except KeyError:
+ raise UndefinedTypeCheck(type) from None
+
+ return fn(self, instance)
+
+ def redefine(self, type: str, fn) -> TypeChecker:
+ """
+ Produce a new checker with the given type redefined.
+
+ Arguments:
+
+ type:
+
+ The name of the type to check.
+
+ fn (collections.abc.Callable):
+
+ A callable taking exactly two parameters - the type
+ checker calling the function and the instance to check.
+ The function should return true if instance is of this
+ type and false otherwise.
+
+ """
+ return self.redefine_many({type: fn})
+
+ def redefine_many(self, definitions=()) -> TypeChecker:
+ """
+ Produce a new checker with the given types redefined.
+
+ Arguments:
+
+ definitions (dict):
+
+ A dictionary mapping types to their checking functions.
+
+ """
+ type_checkers = self._type_checkers.update(definitions)
+ return evolve(self, type_checkers=type_checkers)
+
+ def remove(self, *types) -> TypeChecker:
+ """
+ Produce a new checker with the given types forgotten.
+
+ Arguments:
+
+ types:
+
+ the names of the types to remove.
+
+ Raises:
+
+ `jsonschema.exceptions.UndefinedTypeCheck`:
+
+ if any given type is unknown to this object
+
+ """
+ type_checkers = self._type_checkers
+ for each in types:
+ try:
+ type_checkers = type_checkers.remove(each)
+ except KeyError:
+ raise UndefinedTypeCheck(each) from None
+ return evolve(self, type_checkers=type_checkers)
+
+
+draft3_type_checker = TypeChecker(
+ {
+ "any": is_any,
+ "array": is_array,
+ "boolean": is_bool,
+ "integer": is_integer,
+ "object": is_object,
+ "null": is_null,
+ "number": is_number,
+ "string": is_string,
+ },
+)
+draft4_type_checker = draft3_type_checker.remove("any")
+draft6_type_checker = draft4_type_checker.redefine(
+ "integer",
+ lambda checker, instance: (
+ is_integer(checker, instance)
+ or (isinstance(instance, float) and instance.is_integer())
+ ),
+)
+draft7_type_checker = draft6_type_checker
+draft201909_type_checker = draft7_type_checker
+draft202012_type_checker = draft201909_type_checker
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_typing.py b/venv/lib/python3.10/site-packages/jsonschema/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d091d70c7eae070149636ea18b15efcddc0bf8e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_typing.py
@@ -0,0 +1,29 @@
+"""
+Some (initially private) typing helpers for jsonschema's types.
+"""
+from collections.abc import Iterable
+from typing import Any, Callable, Protocol, Union
+
+import referencing.jsonschema
+
+from jsonschema.protocols import Validator
+
+
+class SchemaKeywordValidator(Protocol):
+ def __call__(
+ self,
+ validator: Validator,
+ value: Any,
+ instance: Any,
+ schema: referencing.jsonschema.Schema,
+ ) -> None:
+ ...
+
+
+id_of = Callable[[referencing.jsonschema.Schema], Union[str, None]]
+
+
+ApplicableValidators = Callable[
+ [referencing.jsonschema.Schema],
+ Iterable[tuple[str, Any]],
+]
diff --git a/venv/lib/python3.10/site-packages/jsonschema/_utils.py b/venv/lib/python3.10/site-packages/jsonschema/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..84a0965e50aef3106c8dfce8762cb75297855d82
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/_utils.py
@@ -0,0 +1,355 @@
+from collections.abc import Mapping, MutableMapping, Sequence
+from urllib.parse import urlsplit
+import itertools
+import re
+
+
+class URIDict(MutableMapping):
+ """
+ Dictionary which uses normalized URIs as keys.
+ """
+
+ def normalize(self, uri):
+ return urlsplit(uri).geturl()
+
+ def __init__(self, *args, **kwargs):
+ self.store = dict()
+ self.store.update(*args, **kwargs)
+
+ def __getitem__(self, uri):
+ return self.store[self.normalize(uri)]
+
+ def __setitem__(self, uri, value):
+ self.store[self.normalize(uri)] = value
+
+ def __delitem__(self, uri):
+ del self.store[self.normalize(uri)]
+
+ def __iter__(self):
+ return iter(self.store)
+
+ def __len__(self): # pragma: no cover -- untested, but to be removed
+ return len(self.store)
+
+ def __repr__(self): # pragma: no cover -- untested, but to be removed
+ return repr(self.store)
+
+
+class Unset:
+ """
+ An as-of-yet unset attribute or unprovided default parameter.
+ """
+
+ def __repr__(self): # pragma: no cover
+ return ""
+
+
+def format_as_index(container, indices):
+ """
+ Construct a single string containing indexing operations for the indices.
+
+ For example for a container ``bar``, [1, 2, "foo"] -> bar[1][2]["foo"]
+
+ Arguments:
+
+ container (str):
+
+ A word to use for the thing being indexed
+
+ indices (sequence):
+
+ The indices to format.
+
+ """
+ if not indices:
+ return container
+ return f"{container}[{']['.join(repr(index) for index in indices)}]"
+
+
+def find_additional_properties(instance, schema):
+ """
+ Return the set of additional properties for the given ``instance``.
+
+ Weeds out properties that should have been validated by ``properties`` and
+ / or ``patternProperties``.
+
+ Assumes ``instance`` is dict-like already.
+ """
+ properties = schema.get("properties", {})
+ patterns = "|".join(schema.get("patternProperties", {}))
+ for property in instance:
+ if property not in properties:
+ if patterns and re.search(patterns, property):
+ continue
+ yield property
+
+
+def extras_msg(extras):
+ """
+ Create an error message for extra items or properties.
+ """
+ verb = "was" if len(extras) == 1 else "were"
+ return ", ".join(repr(extra) for extra in extras), verb
+
+
+def ensure_list(thing):
+ """
+ Wrap ``thing`` in a list if it's a single str.
+
+ Otherwise, return it unchanged.
+ """
+ if isinstance(thing, str):
+ return [thing]
+ return thing
+
+
+def _mapping_equal(one, two):
+ """
+ Check if two mappings are equal using the semantics of `equal`.
+ """
+ if len(one) != len(two):
+ return False
+ return all(
+ key in two and equal(value, two[key])
+ for key, value in one.items()
+ )
+
+
+def _sequence_equal(one, two):
+ """
+ Check if two sequences are equal using the semantics of `equal`.
+ """
+ if len(one) != len(two):
+ return False
+ return all(equal(i, j) for i, j in zip(one, two))
+
+
+def equal(one, two):
+ """
+ Check if two things are equal evading some Python type hierarchy semantics.
+
+ Specifically in JSON Schema, evade `bool` inheriting from `int`,
+ recursing into sequences to do the same.
+ """
+ if one is two:
+ return True
+ if isinstance(one, str) or isinstance(two, str):
+ return one == two
+ if isinstance(one, Sequence) and isinstance(two, Sequence):
+ return _sequence_equal(one, two)
+ if isinstance(one, Mapping) and isinstance(two, Mapping):
+ return _mapping_equal(one, two)
+ return unbool(one) == unbool(two)
+
+
+def unbool(element, true=object(), false=object()):
+ """
+ A hack to make True and 1 and False and 0 unique for ``uniq``.
+ """
+ if element is True:
+ return true
+ elif element is False:
+ return false
+ return element
+
+
+def uniq(container):
+ """
+ Check if all of a container's elements are unique.
+
+ Tries to rely on the container being recursively sortable, or otherwise
+ falls back on (slow) brute force.
+ """
+ try:
+ sort = sorted(unbool(i) for i in container)
+ sliced = itertools.islice(sort, 1, None)
+
+ for i, j in zip(sort, sliced):
+ if equal(i, j):
+ return False
+
+ except (NotImplementedError, TypeError):
+ seen = []
+ for e in container:
+ e = unbool(e)
+
+ for i in seen:
+ if equal(i, e):
+ return False
+
+ seen.append(e)
+ return True
+
+
+def find_evaluated_item_indexes_by_schema(validator, instance, schema):
+ """
+ Get all indexes of items that get evaluated under the current schema.
+
+ Covers all keywords related to unevaluatedItems: items, prefixItems, if,
+ then, else, contains, unevaluatedItems, allOf, oneOf, anyOf
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_indexes = []
+
+ if "items" in schema:
+ return list(range(len(instance)))
+
+ ref = schema.get("$ref")
+ if ref is not None:
+ resolved = validator._resolver.lookup(ref)
+ evaluated_indexes.extend(
+ find_evaluated_item_indexes_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ dynamicRef = schema.get("$dynamicRef")
+ if dynamicRef is not None:
+ resolved = validator._resolver.lookup(dynamicRef)
+ evaluated_indexes.extend(
+ find_evaluated_item_indexes_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ if "prefixItems" in schema:
+ evaluated_indexes += list(range(len(schema["prefixItems"])))
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["then"],
+ )
+ elif "else" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ for keyword in ["contains", "unevaluatedItems"]:
+ if keyword in schema:
+ for k, v in enumerate(instance):
+ if validator.evolve(schema=schema[keyword]).is_valid(v):
+ evaluated_indexes.append(k)
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = next(validator.descend(instance, subschema), None)
+ if errs is None:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, subschema,
+ )
+
+ return evaluated_indexes
+
+
+def find_evaluated_property_keys_by_schema(validator, instance, schema):
+ """
+ Get all keys of items that get evaluated under the current schema.
+
+ Covers all keywords related to unevaluatedProperties: properties,
+ additionalProperties, unevaluatedProperties, patternProperties,
+ dependentSchemas, allOf, oneOf, anyOf, if, then, else
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_keys = []
+
+ ref = schema.get("$ref")
+ if ref is not None:
+ resolved = validator._resolver.lookup(ref)
+ evaluated_keys.extend(
+ find_evaluated_property_keys_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ dynamicRef = schema.get("$dynamicRef")
+ if dynamicRef is not None:
+ resolved = validator._resolver.lookup(dynamicRef)
+ evaluated_keys.extend(
+ find_evaluated_property_keys_by_schema(
+ validator.evolve(
+ schema=resolved.contents,
+ _resolver=resolved.resolver,
+ ),
+ instance,
+ resolved.contents,
+ ),
+ )
+
+ properties = schema.get("properties")
+ if validator.is_type(properties, "object"):
+ evaluated_keys += properties.keys() & instance.keys()
+
+ for keyword in ["additionalProperties", "unevaluatedProperties"]:
+ if (subschema := schema.get(keyword)) is None:
+ continue
+ evaluated_keys += (
+ key
+ for key, value in instance.items()
+ if is_valid(validator.descend(value, subschema))
+ )
+
+ if "patternProperties" in schema:
+ for property in instance:
+ for pattern in schema["patternProperties"]:
+ if re.search(pattern, property):
+ evaluated_keys.append(property)
+
+ if "dependentSchemas" in schema:
+ for property, subschema in schema["dependentSchemas"].items():
+ if property not in instance:
+ continue
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ for subschema in schema.get(keyword, []):
+ if not is_valid(validator.descend(instance, subschema)):
+ continue
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["then"],
+ )
+ elif "else" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ return evaluated_keys
+
+
+def is_valid(errs_it):
+ """Whether there are no errors in the given iterator."""
+ return next(errs_it, None) is None
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__init__.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3dcc689930da95198c251ce806637d6413c8b1e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__init__.py
@@ -0,0 +1,5 @@
+"""
+Benchmarks for validation.
+
+This package is *not* public API.
+"""
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63cf25e33f9cd12404f232f427b9f4478c0d7911
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..985ffb056ff9649b6bbdbbce74a531b7084125e4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..729584a780002d33b9adb518153ae0449df882f2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0895bf8056a03c7cef736f8e64448f432ee87d0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cd4f31d067ef1bff2de733813e16343ee217bca
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf40680de78c3fb12b6624609fc63a6c8a2ed418
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..024d61c43d247681315ede048e9115d48cc3a3f3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..636c0081e6cc71f0f727f2fc292a85155e7bdfe7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e795c0eb4da7221ebe8eaed2250188f5c89e2409
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc95d92868ece638b7d771816adad47b2784c138
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5c7ef3d2ef024b84cb94e0cb8fdd1b7846392c6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/const_vs_enum.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/const_vs_enum.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6fecd10f6d8b845c675be9c19e9b504b08d30b9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/const_vs_enum.py
@@ -0,0 +1,30 @@
+"""
+A benchmark for comparing equivalent validation of `const` and `enum`.
+"""
+
+from pyperf import Runner
+
+from jsonschema import Draft202012Validator
+
+value = [37] * 100
+const_schema = {"const": list(value)}
+enum_schema = {"enum": [list(value)]}
+
+valid = list(value)
+invalid = [*valid, 73]
+
+const = Draft202012Validator(const_schema)
+enum = Draft202012Validator(enum_schema)
+
+assert const.is_valid(valid)
+assert enum.is_valid(valid)
+assert not const.is_valid(invalid)
+assert not enum.is_valid(invalid)
+
+
+if __name__ == "__main__":
+ runner = Runner()
+ runner.bench_func("const valid", lambda: const.is_valid(valid))
+ runner.bench_func("const invalid", lambda: const.is_valid(invalid))
+ runner.bench_func("enum valid", lambda: enum.is_valid(valid))
+ runner.bench_func("enum invalid", lambda: enum.is_valid(invalid))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/contains.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/contains.py
new file mode 100644
index 0000000000000000000000000000000000000000..739cd044cceb807b4029dca9447e954214a24809
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/contains.py
@@ -0,0 +1,28 @@
+"""
+A benchmark for validation of the `contains` keyword.
+"""
+
+from pyperf import Runner
+
+from jsonschema import Draft202012Validator
+
+schema = {
+ "type": "array",
+ "contains": {"const": 37},
+}
+validator = Draft202012Validator(schema)
+
+size = 1000
+beginning = [37] + [0] * (size - 1)
+middle = [0] * (size // 2) + [37] + [0] * (size // 2)
+end = [0] * (size - 1) + [37]
+invalid = [0] * size
+
+
+if __name__ == "__main__":
+ runner = Runner()
+ runner.bench_func("baseline", lambda: validator.is_valid([]))
+ runner.bench_func("beginning", lambda: validator.is_valid(beginning))
+ runner.bench_func("middle", lambda: validator.is_valid(middle))
+ runner.bench_func("end", lambda: validator.is_valid(end))
+ runner.bench_func("invalid", lambda: validator.is_valid(invalid))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232.py
new file mode 100644
index 0000000000000000000000000000000000000000..efd07154822e4b0609900482eb26636fc3c100eb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232.py
@@ -0,0 +1,25 @@
+"""
+A performance benchmark using the example from issue #232.
+
+See https://github.com/python-jsonschema/jsonschema/pull/232.
+"""
+from pathlib import Path
+
+from pyperf import Runner
+from referencing import Registry
+
+from jsonschema.tests._suite import Version
+import jsonschema
+
+issue232 = Version(
+ path=Path(__file__).parent / "issue232",
+ remotes=Registry(),
+ name="issue232",
+)
+
+
+if __name__ == "__main__":
+ issue232.benchmark(
+ runner=Runner(),
+ Validator=jsonschema.Draft4Validator,
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232/issue.json b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232/issue.json
new file mode 100644
index 0000000000000000000000000000000000000000..804c340845fa0694e8db1083cfe7c290c04f36b1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/issue232/issue.json
@@ -0,0 +1,2653 @@
+[
+ {
+ "description": "Petstore",
+ "schema": {
+ "title": "A JSON Schema for Swagger 2.0 API.",
+ "id": "http://swagger.io/v2/schema.json#",
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "type": "object",
+ "required": [
+ "swagger",
+ "info",
+ "paths"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "swagger": {
+ "type": "string",
+ "enum": [
+ "2.0"
+ ],
+ "description": "The Swagger version of this document."
+ },
+ "info": {
+ "$ref": "#/definitions/info"
+ },
+ "host": {
+ "type": "string",
+ "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$",
+ "description": "The host (name or ip) of the API. Example: 'swagger.io'"
+ },
+ "basePath": {
+ "type": "string",
+ "pattern": "^/",
+ "description": "The base path to the API. Example: '/api'."
+ },
+ "schemes": {
+ "$ref": "#/definitions/schemesList"
+ },
+ "consumes": {
+ "description": "A list of MIME types accepted by the API.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "produces": {
+ "description": "A list of MIME types the API can produce.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "paths": {
+ "$ref": "#/definitions/paths"
+ },
+ "definitions": {
+ "$ref": "#/definitions/definitions"
+ },
+ "parameters": {
+ "$ref": "#/definitions/parameterDefinitions"
+ },
+ "responses": {
+ "$ref": "#/definitions/responseDefinitions"
+ },
+ "security": {
+ "$ref": "#/definitions/security"
+ },
+ "securityDefinitions": {
+ "$ref": "#/definitions/securityDefinitions"
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/tag"
+ },
+ "uniqueItems": true
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ }
+ },
+ "definitions": {
+ "info": {
+ "type": "object",
+ "description": "General information about the API.",
+ "required": [
+ "version",
+ "title"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "title": {
+ "type": "string",
+ "description": "A unique and precise title of the API."
+ },
+ "version": {
+ "type": "string",
+ "description": "A semantic version number of the API."
+ },
+ "description": {
+ "type": "string",
+ "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed."
+ },
+ "termsOfService": {
+ "type": "string",
+ "description": "The terms of service for the API."
+ },
+ "contact": {
+ "$ref": "#/definitions/contact"
+ },
+ "license": {
+ "$ref": "#/definitions/license"
+ }
+ }
+ },
+ "contact": {
+ "type": "object",
+ "description": "Contact information for the owners of the API.",
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The identifying name of the contact person/organization."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL pointing to the contact information.",
+ "format": "uri"
+ },
+ "email": {
+ "type": "string",
+ "description": "The email address of the contact person/organization.",
+ "format": "email"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "license": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The name of the license type. It's encouraged to use an OSI compatible license."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL pointing to the license.",
+ "format": "uri"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "paths": {
+ "type": "object",
+ "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ },
+ "^/": {
+ "$ref": "#/definitions/pathItem"
+ }
+ },
+ "additionalProperties": false
+ },
+ "definitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/schema"
+ },
+ "description": "One or more JSON objects describing the schemas being consumed and produced by the API."
+ },
+ "parameterDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/parameter"
+ },
+ "description": "One or more JSON representations for parameters"
+ },
+ "responseDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/response"
+ },
+ "description": "One or more JSON representations for parameters"
+ },
+ "externalDocs": {
+ "type": "object",
+ "additionalProperties": false,
+ "description": "information about external documentation",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "examples": {
+ "type": "object",
+ "additionalProperties": true
+ },
+ "mimeType": {
+ "type": "string",
+ "description": "The MIME type of the HTTP message."
+ },
+ "operation": {
+ "type": "object",
+ "required": [
+ "responses"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "uniqueItems": true
+ },
+ "summary": {
+ "type": "string",
+ "description": "A brief summary of the operation."
+ },
+ "description": {
+ "type": "string",
+ "description": "A longer description of the operation, GitHub Flavored Markdown is allowed."
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "operationId": {
+ "type": "string",
+ "description": "A unique identifier of the operation."
+ },
+ "produces": {
+ "description": "A list of MIME types the API can produce.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "consumes": {
+ "description": "A list of MIME types the API can consume.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "parameters": {
+ "$ref": "#/definitions/parametersList"
+ },
+ "responses": {
+ "$ref": "#/definitions/responses"
+ },
+ "schemes": {
+ "$ref": "#/definitions/schemesList"
+ },
+ "deprecated": {
+ "type": "boolean",
+ "default": false
+ },
+ "security": {
+ "$ref": "#/definitions/security"
+ }
+ }
+ },
+ "pathItem": {
+ "type": "object",
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "$ref": {
+ "type": "string"
+ },
+ "get": {
+ "$ref": "#/definitions/operation"
+ },
+ "put": {
+ "$ref": "#/definitions/operation"
+ },
+ "post": {
+ "$ref": "#/definitions/operation"
+ },
+ "delete": {
+ "$ref": "#/definitions/operation"
+ },
+ "options": {
+ "$ref": "#/definitions/operation"
+ },
+ "head": {
+ "$ref": "#/definitions/operation"
+ },
+ "patch": {
+ "$ref": "#/definitions/operation"
+ },
+ "parameters": {
+ "$ref": "#/definitions/parametersList"
+ }
+ }
+ },
+ "responses": {
+ "type": "object",
+ "description": "Response objects names can either be any valid HTTP status code or 'default'.",
+ "minProperties": 1,
+ "additionalProperties": false,
+ "patternProperties": {
+ "^([0-9]{3})$|^(default)$": {
+ "$ref": "#/definitions/responseValue"
+ },
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "not": {
+ "type": "object",
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ }
+ },
+ "responseValue": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/response"
+ },
+ {
+ "$ref": "#/definitions/jsonReference"
+ }
+ ]
+ },
+ "response": {
+ "type": "object",
+ "required": [
+ "description"
+ ],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "schema": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "$ref": "#/definitions/fileSchema"
+ }
+ ]
+ },
+ "headers": {
+ "$ref": "#/definitions/headers"
+ },
+ "examples": {
+ "$ref": "#/definitions/examples"
+ }
+ },
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/header"
+ }
+ },
+ "header": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "vendorExtension": {
+ "description": "Any property starting with x- is valid.",
+ "additionalProperties": true,
+ "additionalItems": true
+ },
+ "bodyParameter": {
+ "type": "object",
+ "required": [
+ "name",
+ "in",
+ "schema"
+ ],
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "body"
+ ]
+ },
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "schema": {
+ "$ref": "#/definitions/schema"
+ }
+ },
+ "additionalProperties": false
+ },
+ "headerParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "header"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "queryParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "query"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "allowEmptyValue": {
+ "type": "boolean",
+ "default": false,
+ "description": "allows sending a parameter by name only or with an empty value."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormatWithMulti"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "formDataParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "formData"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "allowEmptyValue": {
+ "type": "boolean",
+ "default": false,
+ "description": "allows sending a parameter by name only or with an empty value."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array",
+ "file"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormatWithMulti"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "pathParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "required": [
+ "required"
+ ],
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "enum": [
+ true
+ ],
+ "description": "Determines whether or not this parameter is required or optional."
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "path"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "nonBodyParameter": {
+ "type": "object",
+ "required": [
+ "name",
+ "in",
+ "type"
+ ],
+ "oneOf": [
+ {
+ "$ref": "#/definitions/headerParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/formDataParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/queryParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/pathParameterSubSchema"
+ }
+ ]
+ },
+ "parameter": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/bodyParameter"
+ },
+ {
+ "$ref": "#/definitions/nonBodyParameter"
+ }
+ ]
+ },
+ "schema": {
+ "type": "object",
+ "description": "A deterministic version of a JSON Schema object.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "$ref": {
+ "type": "string"
+ },
+ "format": {
+ "type": "string"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "multipleOf": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
+ },
+ "maximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "pattern": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern"
+ },
+ "maxItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "uniqueItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
+ },
+ "maxProperties": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minProperties": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "required": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray"
+ },
+ "enum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/enum"
+ },
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "type": "boolean"
+ }
+ ],
+ "default": {}
+ },
+ "type": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/type"
+ },
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/definitions/schema"
+ }
+ }
+ ],
+ "default": {}
+ },
+ "allOf": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/definitions/schema"
+ }
+ },
+ "properties": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/schema"
+ },
+ "default": {}
+ },
+ "discriminator": {
+ "type": "string"
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "xml": {
+ "$ref": "#/definitions/xml"
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "example": {}
+ },
+ "additionalProperties": false
+ },
+ "fileSchema": {
+ "type": "object",
+ "description": "A deterministic version of a JSON Schema object.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "format": {
+ "type": "string"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "required": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "file"
+ ]
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "example": {}
+ },
+ "additionalProperties": false
+ },
+ "primitivesItems": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "security": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/securityRequirement"
+ },
+ "uniqueItems": true
+ },
+ "securityRequirement": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "uniqueItems": true
+ }
+ },
+ "xml": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "namespace": {
+ "type": "string"
+ },
+ "prefix": {
+ "type": "string"
+ },
+ "attribute": {
+ "type": "boolean",
+ "default": false
+ },
+ "wrapped": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "tag": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "securityDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/basicAuthenticationSecurity"
+ },
+ {
+ "$ref": "#/definitions/apiKeySecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2ImplicitSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2PasswordSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2ApplicationSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2AccessCodeSecurity"
+ }
+ ]
+ }
+ },
+ "basicAuthenticationSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "basic"
+ ]
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "apiKeySecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "name",
+ "in"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "apiKey"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "in": {
+ "type": "string",
+ "enum": [
+ "header",
+ "query"
+ ]
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2ImplicitSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "authorizationUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "implicit"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "authorizationUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2PasswordSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "password"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2ApplicationSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "application"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2AccessCodeSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "authorizationUrl",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "accessCode"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "authorizationUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2Scopes": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "mediaTypeList": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/mimeType"
+ },
+ "uniqueItems": true
+ },
+ "parametersList": {
+ "type": "array",
+ "description": "The parameters needed to send a valid API call.",
+ "additionalItems": false,
+ "items": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/parameter"
+ },
+ {
+ "$ref": "#/definitions/jsonReference"
+ }
+ ]
+ },
+ "uniqueItems": true
+ },
+ "schemesList": {
+ "type": "array",
+ "description": "The transfer protocol of the API.",
+ "items": {
+ "type": "string",
+ "enum": [
+ "http",
+ "https",
+ "ws",
+ "wss"
+ ]
+ },
+ "uniqueItems": true
+ },
+ "collectionFormat": {
+ "type": "string",
+ "enum": [
+ "csv",
+ "ssv",
+ "tsv",
+ "pipes"
+ ],
+ "default": "csv"
+ },
+ "collectionFormatWithMulti": {
+ "type": "string",
+ "enum": [
+ "csv",
+ "ssv",
+ "tsv",
+ "pipes",
+ "multi"
+ ],
+ "default": "csv"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "multipleOf": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
+ },
+ "maximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "pattern": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern"
+ },
+ "maxItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "uniqueItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
+ },
+ "enum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/enum"
+ },
+ "jsonReference": {
+ "type": "object",
+ "required": [
+ "$ref"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "$ref": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ },
+ "tests": [
+ {
+ "description": "Example petsore",
+ "data": {
+ "swagger": "2.0",
+ "info": {
+ "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
+ "version": "1.0.0",
+ "title": "Swagger Petstore",
+ "termsOfService": "http://swagger.io/terms/",
+ "contact": {
+ "email": "apiteam@swagger.io"
+ },
+ "license": {
+ "name": "Apache 2.0",
+ "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
+ }
+ },
+ "host": "petstore.swagger.io",
+ "basePath": "/v2",
+ "tags": [
+ {
+ "name": "pet",
+ "description": "Everything about your Pets",
+ "externalDocs": {
+ "description": "Find out more",
+ "url": "http://swagger.io"
+ }
+ },
+ {
+ "name": "store",
+ "description": "Access to Petstore orders"
+ },
+ {
+ "name": "user",
+ "description": "Operations about user",
+ "externalDocs": {
+ "description": "Find out more about our store",
+ "url": "http://swagger.io"
+ }
+ }
+ ],
+ "schemes": [
+ "http"
+ ],
+ "paths": {
+ "/pet": {
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Add a new pet to the store",
+ "description": "",
+ "operationId": "addPet",
+ "consumes": [
+ "application/json",
+ "application/xml"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Pet object that needs to be added to the store",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ ],
+ "responses": {
+ "405": {
+ "description": "Invalid input"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ },
+ "put": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Update an existing pet",
+ "description": "",
+ "operationId": "updatePet",
+ "consumes": [
+ "application/json",
+ "application/xml"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Pet object that needs to be added to the store",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ },
+ "405": {
+ "description": "Validation exception"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/findByStatus": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Finds Pets by status",
+ "description": "Multiple status values can be provided with comma separated strings",
+ "operationId": "findPetsByStatus",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "status",
+ "in": "query",
+ "description": "Status values that need to be considered for filter",
+ "required": true,
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": [
+ "available",
+ "pending",
+ "sold"
+ ],
+ "default": "available"
+ },
+ "collectionFormat": "multi"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid status value"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/findByTags": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Finds Pets by tags",
+ "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
+ "operationId": "findPetsByTags",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "tags",
+ "in": "query",
+ "description": "Tags to filter by",
+ "required": true,
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "collectionFormat": "multi"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid tag value"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ],
+ "deprecated": true
+ }
+ },
+ "/pet/{petId}": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Find pet by ID",
+ "description": "Returns a single pet",
+ "operationId": "getPetById",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet to return",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ },
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Updates a pet in the store with form data",
+ "description": "",
+ "operationId": "updatePetWithForm",
+ "consumes": [
+ "application/x-www-form-urlencoded"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet that needs to be updated",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "name": "name",
+ "in": "formData",
+ "description": "Updated name of the pet",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "status",
+ "in": "formData",
+ "description": "Updated status of the pet",
+ "required": false,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "405": {
+ "description": "Invalid input"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ },
+ "delete": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Deletes a pet",
+ "description": "",
+ "operationId": "deletePet",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "api_key",
+ "in": "header",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "Pet id to delete",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/{petId}/uploadImage": {
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "uploads an image",
+ "description": "",
+ "operationId": "uploadFile",
+ "consumes": [
+ "multipart/form-data"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet to update",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "name": "additionalMetadata",
+ "in": "formData",
+ "description": "Additional data to pass to server",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "file",
+ "in": "formData",
+ "description": "file to upload",
+ "required": false,
+ "type": "file"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/ApiResponse"
+ }
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/store/inventory": {
+ "get": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Returns pet inventories by status",
+ "description": "Returns a map of status codes to quantities",
+ "operationId": "getInventory",
+ "produces": [
+ "application/json"
+ ],
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "integer",
+ "format": "int32"
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/store/order": {
+ "post": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Place an order for a pet",
+ "description": "",
+ "operationId": "placeOrder",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "order placed for purchasing the pet",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ },
+ "400": {
+ "description": "Invalid Order"
+ }
+ }
+ }
+ },
+ "/store/order/{orderId}": {
+ "get": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Find purchase order by ID",
+ "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions",
+ "operationId": "getOrderById",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "orderId",
+ "in": "path",
+ "description": "ID of pet that needs to be fetched",
+ "required": true,
+ "type": "integer",
+ "maximum": 10.0,
+ "minimum": 1.0,
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ },
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Order not found"
+ }
+ }
+ },
+ "delete": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Delete purchase order by ID",
+ "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors",
+ "operationId": "deleteOrder",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "orderId",
+ "in": "path",
+ "description": "ID of the order that needs to be deleted",
+ "required": true,
+ "type": "integer",
+ "minimum": 1.0,
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Order not found"
+ }
+ }
+ }
+ },
+ "/user": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Create user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "createUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Created user object",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/createWithArray": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Creates list of users with given input array",
+ "description": "",
+ "operationId": "createUsersWithArrayInput",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "List of user object",
+ "required": true,
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/createWithList": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Creates list of users with given input array",
+ "description": "",
+ "operationId": "createUsersWithListInput",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "List of user object",
+ "required": true,
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/login": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Logs user into the system",
+ "description": "",
+ "operationId": "loginUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "query",
+ "description": "The user name for login",
+ "required": true,
+ "type": "string"
+ },
+ {
+ "name": "password",
+ "in": "query",
+ "description": "The password for login in clear text",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "string"
+ },
+ "headers": {
+ "X-Rate-Limit": {
+ "type": "integer",
+ "format": "int32",
+ "description": "calls per hour allowed by the user"
+ },
+ "X-Expires-After": {
+ "type": "string",
+ "format": "date-time",
+ "description": "date in UTC when token expires"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid username/password supplied"
+ }
+ }
+ }
+ },
+ "/user/logout": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Logs out current logged in user session",
+ "description": "",
+ "operationId": "logoutUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/{username}": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Get user by user name",
+ "description": "",
+ "operationId": "getUserByName",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "The name that needs to be fetched. Use user1 for testing. ",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ },
+ "400": {
+ "description": "Invalid username supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ },
+ "put": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Updated user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "updateUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "name that need to be updated",
+ "required": true,
+ "type": "string"
+ },
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Updated user object",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid user supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ },
+ "delete": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Delete user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "deleteUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "The name that needs to be deleted",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid username supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ }
+ }
+ },
+ "securityDefinitions": {
+ "petstore_auth": {
+ "type": "oauth2",
+ "authorizationUrl": "http://petstore.swagger.io/oauth/dialog",
+ "flow": "implicit",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ },
+ "api_key": {
+ "type": "apiKey",
+ "name": "api_key",
+ "in": "header"
+ }
+ },
+ "definitions": {
+ "Order": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "petId": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "quantity": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "shipDate": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "status": {
+ "type": "string",
+ "description": "Order Status",
+ "enum": [
+ "placed",
+ "approved",
+ "delivered"
+ ]
+ },
+ "complete": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "xml": {
+ "name": "Order"
+ }
+ },
+ "Category": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "xml": {
+ "name": "Category"
+ }
+ },
+ "User": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "username": {
+ "type": "string"
+ },
+ "firstName": {
+ "type": "string"
+ },
+ "lastName": {
+ "type": "string"
+ },
+ "email": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ },
+ "phone": {
+ "type": "string"
+ },
+ "userStatus": {
+ "type": "integer",
+ "format": "int32",
+ "description": "User Status"
+ }
+ },
+ "xml": {
+ "name": "User"
+ }
+ },
+ "Tag": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "xml": {
+ "name": "Tag"
+ }
+ },
+ "Pet": {
+ "type": "object",
+ "required": [
+ "name",
+ "photoUrls"
+ ],
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "category": {
+ "$ref": "#/definitions/Category"
+ },
+ "name": {
+ "type": "string",
+ "example": "doggie"
+ },
+ "photoUrls": {
+ "type": "array",
+ "xml": {
+ "name": "photoUrl",
+ "wrapped": true
+ },
+ "items": {
+ "type": "string"
+ }
+ },
+ "tags": {
+ "type": "array",
+ "xml": {
+ "name": "tag",
+ "wrapped": true
+ },
+ "items": {
+ "$ref": "#/definitions/Tag"
+ }
+ },
+ "status": {
+ "type": "string",
+ "description": "pet status in the store",
+ "enum": [
+ "available",
+ "pending",
+ "sold"
+ ]
+ }
+ },
+ "xml": {
+ "name": "Pet"
+ }
+ },
+ "ApiResponse": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "type": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "externalDocs": {
+ "description": "Find out more about Swagger",
+ "url": "http://swagger.io"
+ }
+ },
+ "valid": true
+ }
+ ]
+ }
+]
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/json_schema_test_suite.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/json_schema_test_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..905fb6a3b88faf56e3288f7eb5053172f97abe8b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/json_schema_test_suite.py
@@ -0,0 +1,12 @@
+"""
+A performance benchmark using the official test suite.
+
+This benchmarks jsonschema using every valid example in the
+JSON-Schema-Test-Suite. It will take some time to complete.
+"""
+from pyperf import Runner
+
+from jsonschema.tests._suite import Suite
+
+if __name__ == "__main__":
+ Suite().benchmark(runner=Runner())
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/nested_schemas.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/nested_schemas.py
new file mode 100644
index 0000000000000000000000000000000000000000..b025c47cfd6736b0ea3d36856c1e2c8de35dde79
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/nested_schemas.py
@@ -0,0 +1,56 @@
+"""
+Validating highly nested schemas shouldn't cause exponential time blowups.
+
+See https://github.com/python-jsonschema/jsonschema/issues/1097.
+"""
+from itertools import cycle
+
+from jsonschema.validators import validator_for
+
+metaschemaish = {
+ "$id": "https://example.com/draft/2020-12/schema/strict",
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/core": True,
+ "https://json-schema.org/draft/2020-12/vocab/applicator": True,
+ "https://json-schema.org/draft/2020-12/vocab/unevaluated": True,
+ "https://json-schema.org/draft/2020-12/vocab/validation": True,
+ "https://json-schema.org/draft/2020-12/vocab/meta-data": True,
+ "https://json-schema.org/draft/2020-12/vocab/format-annotation": True,
+ "https://json-schema.org/draft/2020-12/vocab/content": True,
+ },
+ "$dynamicAnchor": "meta",
+
+ "$ref": "https://json-schema.org/draft/2020-12/schema",
+ "unevaluatedProperties": False,
+}
+
+
+def nested_schema(levels):
+ """
+ Produce a schema which validates deeply nested objects and arrays.
+ """
+
+ names = cycle(["foo", "bar", "baz", "quux", "spam", "eggs"])
+ schema = {"type": "object", "properties": {"ham": {"type": "string"}}}
+ for _, name in zip(range(levels - 1), names):
+ schema = {"type": "object", "properties": {name: schema}}
+ return schema
+
+
+validator = validator_for(metaschemaish)(metaschemaish)
+
+if __name__ == "__main__":
+ from pyperf import Runner
+ runner = Runner()
+
+ not_nested = nested_schema(levels=1)
+ runner.bench_func("not nested", lambda: validator.is_valid(not_nested))
+
+ for levels in range(1, 11, 3):
+ schema = nested_schema(levels=levels)
+ runner.bench_func(
+ f"nested * {levels}",
+ lambda schema=schema: validator.is_valid(schema),
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/subcomponents.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/subcomponents.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d78c7be6c88d177b89dfc80e52acae7820156a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/subcomponents.py
@@ -0,0 +1,42 @@
+"""
+A benchmark which tries to compare the possible slow subparts of validation.
+"""
+from referencing import Registry
+from referencing.jsonschema import DRAFT202012
+from rpds import HashTrieMap, HashTrieSet
+
+from jsonschema import Draft202012Validator
+
+schema = {
+ "type": "array",
+ "minLength": 1,
+ "maxLength": 1,
+ "items": {"type": "integer"},
+}
+
+hmap = HashTrieMap()
+hset = HashTrieSet()
+
+registry = Registry()
+
+v = Draft202012Validator(schema)
+
+
+def registry_data_structures():
+ return hmap.insert("foo", "bar"), hset.insert("foo")
+
+
+def registry_add():
+ resource = DRAFT202012.create_resource(schema)
+ return registry.with_resource(uri="urn:example", resource=resource)
+
+
+if __name__ == "__main__":
+ from pyperf import Runner
+ runner = Runner()
+
+ runner.bench_func("HashMap/HashSet insertion", registry_data_structures)
+ runner.bench_func("Registry insertion", registry_add)
+ runner.bench_func("Success", lambda: v.is_valid([1]))
+ runner.bench_func("Failure", lambda: v.is_valid(["foo"]))
+ runner.bench_func("Metaschema validation", lambda: v.check_schema(schema))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/unused_registry.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/unused_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b272c235625378b231d1c113bcb8ef45851cbc7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/unused_registry.py
@@ -0,0 +1,35 @@
+"""
+An unused schema registry should not cause slower validation.
+
+"Unused" here means one where no reference resolution is occurring anyhow.
+
+See https://github.com/python-jsonschema/jsonschema/issues/1088.
+"""
+from pyperf import Runner
+from referencing import Registry
+from referencing.jsonschema import DRAFT201909
+
+from jsonschema import Draft201909Validator
+
+registry = Registry().with_resource(
+ "urn:example:foo",
+ DRAFT201909.create_resource({}),
+)
+
+schema = {"$ref": "https://json-schema.org/draft/2019-09/schema"}
+instance = {"maxLength": 4}
+
+no_registry = Draft201909Validator(schema)
+with_useless_registry = Draft201909Validator(schema, registry=registry)
+
+if __name__ == "__main__":
+ runner = Runner()
+
+ runner.bench_func(
+ "no registry",
+ lambda: no_registry.is_valid(instance),
+ )
+ runner.bench_func(
+ "useless registry",
+ lambda: with_useless_registry.is_valid(instance),
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3229c0b8b9341e80ed087297efe31b04aa77fd7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py
@@ -0,0 +1,106 @@
+
+"""
+A benchmark for validation of applicators containing lots of useless schemas.
+
+Signals a small possible optimization to remove all such schemas ahead of time.
+"""
+
+from pyperf import Runner
+
+from jsonschema import Draft202012Validator as Validator
+
+NUM_USELESS = 100000
+
+subschema = {"const": 37}
+
+valid = 37
+invalid = 12
+
+baseline = Validator(subschema)
+
+
+# These should be indistinguishable from just `subschema`
+by_name = {
+ "single subschema": {
+ "anyOf": Validator({"anyOf": [subschema]}),
+ "allOf": Validator({"allOf": [subschema]}),
+ "oneOf": Validator({"oneOf": [subschema]}),
+ },
+ "redundant subschemas": {
+ "anyOf": Validator({"anyOf": [subschema] * NUM_USELESS}),
+ "allOf": Validator({"allOf": [subschema] * NUM_USELESS}),
+ },
+ "useless successful subschemas (beginning)": {
+ "anyOf": Validator({"anyOf": [subschema, *[True] * NUM_USELESS]}),
+ "allOf": Validator({"allOf": [subschema, *[True] * NUM_USELESS]}),
+ },
+ "useless successful subschemas (middle)": {
+ "anyOf": Validator(
+ {
+ "anyOf": [
+ *[True] * (NUM_USELESS // 2),
+ subschema,
+ *[True] * (NUM_USELESS // 2),
+ ],
+ },
+ ),
+ "allOf": Validator(
+ {
+ "allOf": [
+ *[True] * (NUM_USELESS // 2),
+ subschema,
+ *[True] * (NUM_USELESS // 2),
+ ],
+ },
+ ),
+ },
+ "useless successful subschemas (end)": {
+ "anyOf": Validator({"anyOf": [*[True] * NUM_USELESS, subschema]}),
+ "allOf": Validator({"allOf": [*[True] * NUM_USELESS, subschema]}),
+ },
+ "useless failing subschemas (beginning)": {
+ "anyOf": Validator({"anyOf": [subschema, *[False] * NUM_USELESS]}),
+ "oneOf": Validator({"oneOf": [subschema, *[False] * NUM_USELESS]}),
+ },
+ "useless failing subschemas (middle)": {
+ "anyOf": Validator(
+ {
+ "anyOf": [
+ *[False] * (NUM_USELESS // 2),
+ subschema,
+ *[False] * (NUM_USELESS // 2),
+ ],
+ },
+ ),
+ "oneOf": Validator(
+ {
+ "oneOf": [
+ *[False] * (NUM_USELESS // 2),
+ subschema,
+ *[False] * (NUM_USELESS // 2),
+ ],
+ },
+ ),
+ },
+ "useless failing subschemas (end)": {
+ "anyOf": Validator({"anyOf": [*[False] * NUM_USELESS, subschema]}),
+ "oneOf": Validator({"oneOf": [*[False] * NUM_USELESS, subschema]}),
+ },
+}
+
+if __name__ == "__main__":
+ runner = Runner()
+
+ runner.bench_func("baseline valid", lambda: baseline.is_valid(valid))
+ runner.bench_func("baseline invalid", lambda: baseline.is_valid(invalid))
+
+ for group, applicators in by_name.items():
+ for applicator, validator in applicators.items():
+ runner.bench_func(
+ f"{group}: {applicator} valid",
+ lambda validator=validator: validator.is_valid(valid),
+ )
+ runner.bench_func(
+ f"{group}: {applicator} invalid",
+ lambda validator=validator: validator.is_valid(invalid),
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_keywords.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_keywords.py
new file mode 100644
index 0000000000000000000000000000000000000000..50f435989dd14d34d804508067e91e5fae4a275c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/useless_keywords.py
@@ -0,0 +1,32 @@
+"""
+A benchmark for validation of schemas containing lots of useless keywords.
+
+Checks we filter them out once, ahead of time.
+"""
+
+from pyperf import Runner
+
+from jsonschema import Draft202012Validator
+
+NUM_USELESS = 100000
+schema = dict(
+ [
+ ("not", {"const": 42}),
+ *((str(i), i) for i in range(NUM_USELESS)),
+ ("type", "integer"),
+ *((str(i), i) for i in range(NUM_USELESS, NUM_USELESS)),
+ ("minimum", 37),
+ ],
+)
+validator = Draft202012Validator(schema)
+
+valid = 3737
+invalid = 12
+
+
+if __name__ == "__main__":
+ runner = Runner()
+ runner.bench_func("beginning of schema", lambda: validator.is_valid(42))
+ runner.bench_func("middle of schema", lambda: validator.is_valid("foo"))
+ runner.bench_func("end of schema", lambda: validator.is_valid(12))
+ runner.bench_func("valid", lambda: validator.is_valid(3737))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/benchmarks/validator_creation.py b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/validator_creation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4baeb3a31641a027496732a6f10e200346551209
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/benchmarks/validator_creation.py
@@ -0,0 +1,14 @@
+from pyperf import Runner
+
+from jsonschema import Draft202012Validator
+
+schema = {
+ "type": "array",
+ "minLength": 1,
+ "maxLength": 1,
+ "items": {"type": "integer"},
+}
+
+
+if __name__ == "__main__":
+ Runner().bench_func("validator creation", Draft202012Validator, schema)
diff --git a/venv/lib/python3.10/site-packages/jsonschema/cli.py b/venv/lib/python3.10/site-packages/jsonschema/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3ca4d6ad04882f8107ce134c270b4fcbc94032b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/cli.py
@@ -0,0 +1,292 @@
+"""
+The ``jsonschema`` command line.
+"""
+
+from importlib import metadata
+from json import JSONDecodeError
+from pkgutil import resolve_name
+from textwrap import dedent
+import argparse
+import json
+import sys
+import traceback
+import warnings
+
+from attrs import define, field
+
+from jsonschema.exceptions import SchemaError
+from jsonschema.validators import _RefResolver, validator_for
+
+warnings.warn(
+ (
+ "The jsonschema CLI is deprecated and will be removed in a future "
+ "version. Please use check-jsonschema instead, which can be installed "
+ "from https://pypi.org/project/check-jsonschema/"
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+)
+
+
+class _CannotLoadFile(Exception):
+ pass
+
+
+@define
+class _Outputter:
+
+ _formatter = field()
+ _stdout = field()
+ _stderr = field()
+
+ @classmethod
+ def from_arguments(cls, arguments, stdout, stderr):
+ if arguments["output"] == "plain":
+ formatter = _PlainFormatter(arguments["error_format"])
+ elif arguments["output"] == "pretty":
+ formatter = _PrettyFormatter()
+ return cls(formatter=formatter, stdout=stdout, stderr=stderr)
+
+ def load(self, path):
+ try:
+ file = open(path) # noqa: SIM115, PTH123
+ except FileNotFoundError as error:
+ self.filenotfound_error(path=path, exc_info=sys.exc_info())
+ raise _CannotLoadFile() from error
+
+ with file:
+ try:
+ return json.load(file)
+ except JSONDecodeError as error:
+ self.parsing_error(path=path, exc_info=sys.exc_info())
+ raise _CannotLoadFile() from error
+
+ def filenotfound_error(self, **kwargs):
+ self._stderr.write(self._formatter.filenotfound_error(**kwargs))
+
+ def parsing_error(self, **kwargs):
+ self._stderr.write(self._formatter.parsing_error(**kwargs))
+
+ def validation_error(self, **kwargs):
+ self._stderr.write(self._formatter.validation_error(**kwargs))
+
+ def validation_success(self, **kwargs):
+ self._stdout.write(self._formatter.validation_success(**kwargs))
+
+
+@define
+class _PrettyFormatter:
+
+ _ERROR_MSG = dedent(
+ """\
+ ===[{type}]===({path})===
+
+ {body}
+ -----------------------------
+ """,
+ )
+ _SUCCESS_MSG = "===[SUCCESS]===({path})===\n"
+
+ def filenotfound_error(self, path, exc_info):
+ return self._ERROR_MSG.format(
+ path=path,
+ type="FileNotFoundError",
+ body=f"{path!r} does not exist.",
+ )
+
+ def parsing_error(self, path, exc_info):
+ exc_type, exc_value, exc_traceback = exc_info
+ exc_lines = "".join(
+ traceback.format_exception(exc_type, exc_value, exc_traceback),
+ )
+ return self._ERROR_MSG.format(
+ path=path,
+ type=exc_type.__name__,
+ body=exc_lines,
+ )
+
+ def validation_error(self, instance_path, error):
+ return self._ERROR_MSG.format(
+ path=instance_path,
+ type=error.__class__.__name__,
+ body=error,
+ )
+
+ def validation_success(self, instance_path):
+ return self._SUCCESS_MSG.format(path=instance_path)
+
+
+@define
+class _PlainFormatter:
+
+ _error_format = field()
+
+ def filenotfound_error(self, path, exc_info):
+ return f"{path!r} does not exist.\n"
+
+ def parsing_error(self, path, exc_info):
+ return "Failed to parse {}: {}\n".format(
+ "" if path == "" else repr(path),
+ exc_info[1],
+ )
+
+ def validation_error(self, instance_path, error):
+ return self._error_format.format(file_name=instance_path, error=error)
+
+ def validation_success(self, instance_path):
+ return ""
+
+
+def _resolve_name_with_default(name):
+ if "." not in name:
+ name = "jsonschema." + name
+ return resolve_name(name)
+
+
+parser = argparse.ArgumentParser(
+ description="JSON Schema Validation CLI",
+)
+parser.add_argument(
+ "-i", "--instance",
+ action="append",
+ dest="instances",
+ help="""
+ a path to a JSON instance (i.e. filename.json) to validate (may
+ be specified multiple times). If no instances are provided via this
+ option, one will be expected on standard input.
+ """,
+)
+parser.add_argument(
+ "-F", "--error-format",
+ help="""
+ the format to use for each validation error message, specified
+ in a form suitable for str.format. This string will be passed
+ one formatted object named 'error' for each ValidationError.
+ Only provide this option when using --output=plain, which is the
+ default. If this argument is unprovided and --output=plain is
+ used, a simple default representation will be used.
+ """,
+)
+parser.add_argument(
+ "-o", "--output",
+ choices=["plain", "pretty"],
+ default="plain",
+ help="""
+ an output format to use. 'plain' (default) will produce minimal
+ text with one line for each error, while 'pretty' will produce
+ more detailed human-readable output on multiple lines.
+ """,
+)
+parser.add_argument(
+ "-V", "--validator",
+ type=_resolve_name_with_default,
+ help="""
+ the fully qualified object name of a validator to use, or, for
+ validators that are registered with jsonschema, simply the name
+ of the class.
+ """,
+)
+parser.add_argument(
+ "--base-uri",
+ help="""
+ a base URI to assign to the provided schema, even if it does not
+ declare one (via e.g. $id). This option can be used if you wish to
+ resolve relative references to a particular URI (or local path)
+ """,
+)
+parser.add_argument(
+ "--version",
+ action="version",
+ version=metadata.version("jsonschema"),
+)
+parser.add_argument(
+ "schema",
+ help="the path to a JSON Schema to validate with (i.e. schema.json)",
+)
+
+
+def parse_args(args): # noqa: D103
+ arguments = vars(parser.parse_args(args=args or ["--help"]))
+ if arguments["output"] != "plain" and arguments["error_format"]:
+ raise parser.error(
+ "--error-format can only be used with --output plain",
+ )
+ if arguments["output"] == "plain" and arguments["error_format"] is None:
+ arguments["error_format"] = "{error.instance}: {error.message}\n"
+ return arguments
+
+
+def _validate_instance(instance_path, instance, validator, outputter):
+ invalid = False
+ for error in validator.iter_errors(instance):
+ invalid = True
+ outputter.validation_error(instance_path=instance_path, error=error)
+
+ if not invalid:
+ outputter.validation_success(instance_path=instance_path)
+ return invalid
+
+
+def main(args=sys.argv[1:]): # noqa: D103
+ sys.exit(run(arguments=parse_args(args=args)))
+
+
+def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin): # noqa: D103
+ outputter = _Outputter.from_arguments(
+ arguments=arguments,
+ stdout=stdout,
+ stderr=stderr,
+ )
+
+ try:
+ schema = outputter.load(arguments["schema"])
+ except _CannotLoadFile:
+ return 1
+
+ Validator = arguments["validator"]
+ if Validator is None:
+ Validator = validator_for(schema)
+
+ try:
+ Validator.check_schema(schema)
+ except SchemaError as error:
+ outputter.validation_error(
+ instance_path=arguments["schema"],
+ error=error,
+ )
+ return 1
+
+ if arguments["instances"]:
+ load, instances = outputter.load, arguments["instances"]
+ else:
+ def load(_):
+ try:
+ return json.load(stdin)
+ except JSONDecodeError as error:
+ outputter.parsing_error(
+ path="", exc_info=sys.exc_info(),
+ )
+ raise _CannotLoadFile() from error
+ instances = [""]
+
+ resolver = _RefResolver(
+ base_uri=arguments["base_uri"],
+ referrer=schema,
+ ) if arguments["base_uri"] is not None else None
+
+ validator = Validator(schema, resolver=resolver)
+ exit_code = 0
+ for each in instances:
+ try:
+ instance = load(each)
+ except _CannotLoadFile:
+ exit_code = 1
+ else:
+ exit_code |= _validate_instance(
+ instance_path=each,
+ instance=instance,
+ validator=validator,
+ outputter=outputter,
+ )
+
+ return exit_code
diff --git a/venv/lib/python3.10/site-packages/jsonschema/exceptions.py b/venv/lib/python3.10/site-packages/jsonschema/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d955e356ef584df655accc390b4cdba22f72a545
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/exceptions.py
@@ -0,0 +1,490 @@
+"""
+Validation errors, and some surrounding helpers.
+"""
+from __future__ import annotations
+
+from collections import defaultdict, deque
+from pprint import pformat
+from textwrap import dedent, indent
+from typing import TYPE_CHECKING, Any, ClassVar
+import heapq
+import re
+import warnings
+
+from attrs import define
+from referencing.exceptions import Unresolvable as _Unresolvable
+
+from jsonschema import _utils
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Mapping, MutableMapping, Sequence
+
+ from jsonschema import _types
+
+WEAK_MATCHES: frozenset[str] = frozenset(["anyOf", "oneOf"])
+STRONG_MATCHES: frozenset[str] = frozenset()
+
+_JSON_PATH_COMPATIBLE_PROPERTY_PATTERN = re.compile("^[a-zA-Z][a-zA-Z0-9_]*$")
+
+_unset = _utils.Unset()
+
+
+def _pretty(thing: Any, prefix: str):
+ """
+ Format something for an error message as prettily as we currently can.
+ """
+ return indent(pformat(thing, width=72, sort_dicts=False), prefix).lstrip()
+
+
+def __getattr__(name):
+ if name == "RefResolutionError":
+ warnings.warn(
+ _RefResolutionError._DEPRECATION_MESSAGE,
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _RefResolutionError
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+class _Error(Exception):
+
+ _word_for_schema_in_error_message: ClassVar[str]
+ _word_for_instance_in_error_message: ClassVar[str]
+
+ def __init__(
+ self,
+ message: str,
+ validator: str = _unset, # type: ignore[assignment]
+ path: Iterable[str | int] = (),
+ cause: Exception | None = None,
+ context=(),
+ validator_value: Any = _unset,
+ instance: Any = _unset,
+ schema: Mapping[str, Any] | bool = _unset, # type: ignore[assignment]
+ schema_path: Iterable[str | int] = (),
+ parent: _Error | None = None,
+ type_checker: _types.TypeChecker = _unset, # type: ignore[assignment]
+ ) -> None:
+ super().__init__(
+ message,
+ validator,
+ path,
+ cause,
+ context,
+ validator_value,
+ instance,
+ schema,
+ schema_path,
+ parent,
+ )
+ self.message = message
+ self.path = self.relative_path = deque(path)
+ self.schema_path = self.relative_schema_path = deque(schema_path)
+ self.context = list(context)
+ self.cause = self.__cause__ = cause
+ self.validator = validator
+ self.validator_value = validator_value
+ self.instance = instance
+ self.schema = schema
+ self.parent = parent
+ self._type_checker = type_checker
+
+ for error in context:
+ error.parent = self
+
+ def __repr__(self) -> str:
+ return f"<{self.__class__.__name__}: {self.message!r}>"
+
+ def __str__(self) -> str:
+ essential_for_verbose = (
+ self.validator, self.validator_value, self.instance, self.schema,
+ )
+ if any(m is _unset for m in essential_for_verbose):
+ return self.message
+
+ schema_path = _utils.format_as_index(
+ container=self._word_for_schema_in_error_message,
+ indices=list(self.relative_schema_path)[:-1],
+ )
+ instance_path = _utils.format_as_index(
+ container=self._word_for_instance_in_error_message,
+ indices=self.relative_path,
+ )
+ prefix = 16 * " "
+
+ return dedent(
+ f"""\
+ {self.message}
+
+ Failed validating {self.validator!r} in {schema_path}:
+ {_pretty(self.schema, prefix=prefix)}
+
+ On {instance_path}:
+ {_pretty(self.instance, prefix=prefix)}
+ """.rstrip(),
+ )
+
+ @classmethod
+ def create_from(cls, other: _Error):
+ return cls(**other._contents())
+
+ @property
+ def absolute_path(self) -> Sequence[str | int]:
+ parent = self.parent
+ if parent is None:
+ return self.relative_path
+
+ path = deque(self.relative_path)
+ path.extendleft(reversed(parent.absolute_path))
+ return path
+
+ @property
+ def absolute_schema_path(self) -> Sequence[str | int]:
+ parent = self.parent
+ if parent is None:
+ return self.relative_schema_path
+
+ path = deque(self.relative_schema_path)
+ path.extendleft(reversed(parent.absolute_schema_path))
+ return path
+
+ @property
+ def json_path(self) -> str:
+ path = "$"
+ for elem in self.absolute_path:
+ if isinstance(elem, int):
+ path += "[" + str(elem) + "]"
+ elif _JSON_PATH_COMPATIBLE_PROPERTY_PATTERN.match(elem):
+ path += "." + elem
+ else:
+ escaped_elem = elem.replace("\\", "\\\\").replace("'", r"\'")
+ path += "['" + escaped_elem + "']"
+ return path
+
+ def _set(
+ self,
+ type_checker: _types.TypeChecker | None = None,
+ **kwargs: Any,
+ ) -> None:
+ if type_checker is not None and self._type_checker is _unset:
+ self._type_checker = type_checker
+
+ for k, v in kwargs.items():
+ if getattr(self, k) is _unset:
+ setattr(self, k, v)
+
+ def _contents(self):
+ attrs = (
+ "message", "cause", "context", "validator", "validator_value",
+ "path", "schema_path", "instance", "schema", "parent",
+ )
+ return {attr: getattr(self, attr) for attr in attrs}
+
+ def _matches_type(self) -> bool:
+ try:
+ # We ignore this as we want to simply crash if this happens
+ expected = self.schema["type"] # type: ignore[index]
+ except (KeyError, TypeError):
+ return False
+
+ if isinstance(expected, str):
+ return self._type_checker.is_type(self.instance, expected)
+
+ return any(
+ self._type_checker.is_type(self.instance, expected_type)
+ for expected_type in expected
+ )
+
+
+class ValidationError(_Error):
+ """
+ An instance was invalid under a provided schema.
+ """
+
+ _word_for_schema_in_error_message = "schema"
+ _word_for_instance_in_error_message = "instance"
+
+
+class SchemaError(_Error):
+ """
+ A schema was invalid under its corresponding metaschema.
+ """
+
+ _word_for_schema_in_error_message = "metaschema"
+ _word_for_instance_in_error_message = "schema"
+
+
+@define(slots=False)
+class _RefResolutionError(Exception): # noqa: PLW1641
+ """
+ A ref could not be resolved.
+ """
+
+ _DEPRECATION_MESSAGE = (
+ "jsonschema.exceptions.RefResolutionError is deprecated as of version "
+ "4.18.0. If you wish to catch potential reference resolution errors, "
+ "directly catch referencing.exceptions.Unresolvable."
+ )
+
+ _cause: Exception
+
+ def __eq__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented # pragma: no cover -- uncovered but deprecated # noqa: E501
+ return self._cause == other._cause
+
+ def __str__(self) -> str:
+ return str(self._cause)
+
+
+class _WrappedReferencingError(_RefResolutionError, _Unresolvable): # pragma: no cover -- partially uncovered but to be removed # noqa: E501
+ def __init__(self, cause: _Unresolvable):
+ object.__setattr__(self, "_wrapped", cause)
+
+ def __eq__(self, other):
+ if other.__class__ is self.__class__:
+ return self._wrapped == other._wrapped
+ elif other.__class__ is self._wrapped.__class__:
+ return self._wrapped == other
+ return NotImplemented
+
+ def __getattr__(self, attr):
+ return getattr(self._wrapped, attr)
+
+ def __hash__(self):
+ return hash(self._wrapped)
+
+ def __repr__(self):
+ return f""
+
+ def __str__(self):
+ return f"{self._wrapped.__class__.__name__}: {self._wrapped}"
+
+
+class UndefinedTypeCheck(Exception):
+ """
+ A type checker was asked to check a type it did not have registered.
+ """
+
+ def __init__(self, type: str) -> None:
+ self.type = type
+
+ def __str__(self) -> str:
+ return f"Type {self.type!r} is unknown to this type checker"
+
+
+class UnknownType(Exception):
+ """
+ A validator was asked to validate an instance against an unknown type.
+ """
+
+ def __init__(self, type, instance, schema):
+ self.type = type
+ self.instance = instance
+ self.schema = schema
+
+ def __str__(self):
+ prefix = 16 * " "
+
+ return dedent(
+ f"""\
+ Unknown type {self.type!r} for validator with schema:
+ {_pretty(self.schema, prefix=prefix)}
+
+ While checking instance:
+ {_pretty(self.instance, prefix=prefix)}
+ """.rstrip(),
+ )
+
+
+class FormatError(Exception):
+ """
+ Validating a format failed.
+ """
+
+ def __init__(self, message, cause=None):
+ super().__init__(message, cause)
+ self.message = message
+ self.cause = self.__cause__ = cause
+
+ def __str__(self):
+ return self.message
+
+
+class ErrorTree:
+ """
+ ErrorTrees make it easier to check which validations failed.
+ """
+
+ _instance = _unset
+
+ def __init__(self, errors: Iterable[ValidationError] = ()):
+ self.errors: MutableMapping[str, ValidationError] = {}
+ self._contents: Mapping[str, ErrorTree] = defaultdict(self.__class__)
+
+ for error in errors:
+ container = self
+ for element in error.path:
+ container = container[element]
+ container.errors[error.validator] = error
+
+ container._instance = error.instance
+
+ def __contains__(self, index: str | int):
+ """
+ Check whether ``instance[index]`` has any errors.
+ """
+ return index in self._contents
+
+ def __getitem__(self, index):
+ """
+ Retrieve the child tree one level down at the given ``index``.
+
+ If the index is not in the instance that this tree corresponds
+ to and is not known by this tree, whatever error would be raised
+ by ``instance.__getitem__`` will be propagated (usually this is
+ some subclass of `LookupError`.
+ """
+ if self._instance is not _unset and index not in self:
+ self._instance[index]
+ return self._contents[index]
+
+ def __setitem__(self, index: str | int, value: ErrorTree):
+ """
+ Add an error to the tree at the given ``index``.
+
+ .. deprecated:: v4.20.0
+
+ Setting items on an `ErrorTree` is deprecated without replacement.
+ To populate a tree, provide all of its sub-errors when you
+ construct the tree.
+ """
+ warnings.warn(
+ "ErrorTree.__setitem__ is deprecated without replacement.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self._contents[index] = value # type: ignore[index]
+
+ def __iter__(self):
+ """
+ Iterate (non-recursively) over the indices in the instance with errors.
+ """
+ return iter(self._contents)
+
+ def __len__(self):
+ """
+ Return the `total_errors`.
+ """
+ return self.total_errors
+
+ def __repr__(self):
+ total = len(self)
+ errors = "error" if total == 1 else "errors"
+ return f"<{self.__class__.__name__} ({total} total {errors})>"
+
+ @property
+ def total_errors(self):
+ """
+ The total number of errors in the entire tree, including children.
+ """
+ child_errors = sum(len(tree) for _, tree in self._contents.items())
+ return len(self.errors) + child_errors
+
+
+def by_relevance(weak=WEAK_MATCHES, strong=STRONG_MATCHES):
+ """
+ Create a key function that can be used to sort errors by relevance.
+
+ Arguments:
+ weak (set):
+ a collection of validation keywords to consider to be
+ "weak". If there are two errors at the same level of the
+ instance and one is in the set of weak validation keywords,
+ the other error will take priority. By default, :kw:`anyOf`
+ and :kw:`oneOf` are considered weak keywords and will be
+ superseded by other same-level validation errors.
+
+ strong (set):
+ a collection of validation keywords to consider to be
+ "strong"
+
+ """
+
+ def relevance(error):
+ validator = error.validator
+ return ( # prefer errors which are ...
+ -len(error.path), # 'deeper' and thereby more specific
+ error.path, # earlier (for sibling errors)
+ validator not in weak, # for a non-low-priority keyword
+ validator in strong, # for a high priority keyword
+ not error._matches_type(), # at least match the instance's type
+ ) # otherwise we'll treat them the same
+
+ return relevance
+
+
+relevance = by_relevance()
+"""
+A key function (e.g. to use with `sorted`) which sorts errors by relevance.
+
+Example:
+
+.. code:: python
+
+ sorted(validator.iter_errors(12), key=jsonschema.exceptions.relevance)
+"""
+
+
+def best_match(errors, key=relevance):
+ """
+ Try to find an error that appears to be the best match among given errors.
+
+ In general, errors that are higher up in the instance (i.e. for which
+ `ValidationError.path` is shorter) are considered better matches,
+ since they indicate "more" is wrong with the instance.
+
+ If the resulting match is either :kw:`oneOf` or :kw:`anyOf`, the
+ *opposite* assumption is made -- i.e. the deepest error is picked,
+ since these keywords only need to match once, and any other errors
+ may not be relevant.
+
+ Arguments:
+ errors (collections.abc.Iterable):
+
+ the errors to select from. Do not provide a mixture of
+ errors from different validation attempts (i.e. from
+ different instances or schemas), since it won't produce
+ sensical output.
+
+ key (collections.abc.Callable):
+
+ the key to use when sorting errors. See `relevance` and
+ transitively `by_relevance` for more details (the default is
+ to sort with the defaults of that function). Changing the
+ default is only useful if you want to change the function
+ that rates errors but still want the error context descent
+ done by this function.
+
+ Returns:
+ the best matching error, or ``None`` if the iterable was empty
+
+ .. note::
+
+ This function is a heuristic. Its return value may change for a given
+ set of inputs from version to version if better heuristics are added.
+
+ """
+ best = max(errors, key=key, default=None)
+ if best is None:
+ return
+
+ while best.context:
+ # Calculate the minimum via nsmallest, because we don't recurse if
+ # all nested errors have the same relevance (i.e. if min == max == all)
+ smallest = heapq.nsmallest(2, best.context, key=key)
+ if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]): # noqa: PLR2004
+ return best
+ best = smallest[0]
+ return best
diff --git a/venv/lib/python3.10/site-packages/jsonschema/protocols.py b/venv/lib/python3.10/site-packages/jsonschema/protocols.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fd993eec8145a87c7859d3a182d38030829ab0c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/protocols.py
@@ -0,0 +1,229 @@
+"""
+typing.Protocol classes for jsonschema interfaces.
+"""
+
+# for reference material on Protocols, see
+# https://www.python.org/dev/peps/pep-0544/
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, ClassVar, Protocol, runtime_checkable
+
+# in order for Sphinx to resolve references accurately from type annotations,
+# it needs to see names like `jsonschema.TypeChecker`
+# therefore, only import at type-checking time (to avoid circular references),
+# but use `jsonschema` for any types which will otherwise not be resolvable
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Mapping
+
+ import referencing.jsonschema
+
+ from jsonschema import _typing
+ from jsonschema.exceptions import ValidationError
+ import jsonschema
+ import jsonschema.validators
+
+# For code authors working on the validator protocol, these are the three
+# use-cases which should be kept in mind:
+#
+# 1. As a protocol class, it can be used in type annotations to describe the
+# available methods and attributes of a validator
+# 2. It is the source of autodoc for the validator documentation
+# 3. It is runtime_checkable, meaning that it can be used in isinstance()
+# checks.
+#
+# Since protocols are not base classes, isinstance() checking is limited in
+# its capabilities. See docs on runtime_checkable for detail
+
+
+@runtime_checkable
+class Validator(Protocol):
+ """
+ The protocol to which all validator classes adhere.
+
+ Arguments:
+
+ schema:
+
+ The schema that the validator object will validate with.
+ It is assumed to be valid, and providing
+ an invalid schema can lead to undefined behavior. See
+ `Validator.check_schema` to validate a schema first.
+
+ registry:
+
+ a schema registry that will be used for looking up JSON references
+
+ resolver:
+
+ a resolver that will be used to resolve :kw:`$ref`
+ properties (JSON references). If unprovided, one will be created.
+
+ .. deprecated:: v4.18.0
+
+ `RefResolver <_RefResolver>` has been deprecated in favor of
+ `referencing`, and with it, this argument.
+
+ format_checker:
+
+ if provided, a checker which will be used to assert about
+ :kw:`format` properties present in the schema. If unprovided,
+ *no* format validation is done, and the presence of format
+ within schemas is strictly informational. Certain formats
+ require additional packages to be installed in order to assert
+ against instances. Ensure you've installed `jsonschema` with
+ its `extra (optional) dependencies ` when
+ invoking ``pip``.
+
+ .. deprecated:: v4.12.0
+
+ Subclassing validator classes now explicitly warns this is not part of
+ their public API.
+
+ """
+
+ #: An object representing the validator's meta schema (the schema that
+ #: describes valid schemas in the given version).
+ META_SCHEMA: ClassVar[Mapping]
+
+ #: A mapping of validation keywords (`str`\s) to functions that
+ #: validate the keyword with that name. For more information see
+ #: `creating-validators`.
+ VALIDATORS: ClassVar[Mapping]
+
+ #: A `jsonschema.TypeChecker` that will be used when validating
+ #: :kw:`type` keywords in JSON schemas.
+ TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
+
+ #: A `jsonschema.FormatChecker` that will be used when validating
+ #: :kw:`format` keywords in JSON schemas.
+ FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
+
+ #: A function which given a schema returns its ID.
+ ID_OF: _typing.id_of
+
+ #: The schema that will be used to validate instances
+ schema: Mapping | bool
+
+ def __init__(
+ self,
+ schema: Mapping | bool,
+ registry: referencing.jsonschema.SchemaRegistry,
+ format_checker: jsonschema.FormatChecker | None = None,
+ ) -> None:
+ ...
+
+ @classmethod
+ def check_schema(cls, schema: Mapping | bool) -> None:
+ """
+ Validate the given schema against the validator's `META_SCHEMA`.
+
+ Raises:
+
+ `jsonschema.exceptions.SchemaError`:
+
+ if the schema is invalid
+
+ """
+
+ def is_type(self, instance: Any, type: str) -> bool:
+ """
+ Check if the instance is of the given (JSON Schema) type.
+
+ Arguments:
+
+ instance:
+
+ the value to check
+
+ type:
+
+ the name of a known (JSON Schema) type
+
+ Returns:
+
+ whether the instance is of the given type
+
+ Raises:
+
+ `jsonschema.exceptions.UnknownType`:
+
+ if ``type`` is not a known type
+
+ """
+
+ def is_valid(self, instance: Any) -> bool:
+ """
+ Check if the instance is valid under the current `schema`.
+
+ Returns:
+
+ whether the instance is valid or not
+
+ >>> schema = {"maxItems" : 2}
+ >>> Draft202012Validator(schema).is_valid([2, 3, 4])
+ False
+
+ """
+
+ def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
+ r"""
+ Lazily yield each of the validation errors in the given instance.
+
+ >>> schema = {
+ ... "type" : "array",
+ ... "items" : {"enum" : [1, 2, 3]},
+ ... "maxItems" : 2,
+ ... }
+ >>> v = Draft202012Validator(schema)
+ >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
+ ... print(error.message)
+ 4 is not one of [1, 2, 3]
+ [2, 3, 4] is too long
+
+ .. deprecated:: v4.0.0
+
+ Calling this function with a second schema argument is deprecated.
+ Use `Validator.evolve` instead.
+ """
+
+ def validate(self, instance: Any) -> None:
+ """
+ Check if the instance is valid under the current `schema`.
+
+ Raises:
+
+ `jsonschema.exceptions.ValidationError`:
+
+ if the instance is invalid
+
+ >>> schema = {"maxItems" : 2}
+ >>> Draft202012Validator(schema).validate([2, 3, 4])
+ Traceback (most recent call last):
+ ...
+ ValidationError: [2, 3, 4] is too long
+
+ """
+
+ def evolve(self, **kwargs) -> Validator:
+ """
+ Create a new validator like this one, but with given changes.
+
+ Preserves all other attributes, so can be used to e.g. create a
+ validator with a different schema but with the same :kw:`$ref`
+ resolution behavior.
+
+ >>> validator = Draft202012Validator({})
+ >>> validator.evolve(schema={"type": "number"})
+ Draft202012Validator(schema={'type': 'number'}, format_checker=None)
+
+ The returned object satisfies the validator protocol, but may not
+ be of the same concrete class! In particular this occurs
+ when a :kw:`$ref` occurs to a schema with a different
+ :kw:`$schema` than this one (i.e. for a different draft).
+
+ >>> validator.evolve(
+ ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
+ ... )
+ Draft7Validator(schema=..., format_checker=None)
+ """
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__init__.py b/venv/lib/python3.10/site-packages/jsonschema/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e86b14e4881db523e2ed442b9abe2e617d0cf3bd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/_suite.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/_suite.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43af064afb27635ba0c91962d5e5f20714f23707
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/_suite.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a03d1df6bce9431d7274708d715636902dfcf4bf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9743b13a8451f88e80ed89fc816190936b481fc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fa62e6bf514de97d39508eddfbb1452b453fe83
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2db6d488630294d4cc80023fa25df52b1ed36d4b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_format.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_format.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99dd717d7cc335a6f4a601d1bbdde4db8cb8a6c7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_format.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6043f8e0ae1f21bf4b01f86879ef097b172bd431
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_types.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..688d779bcd5ca0673a60b83f3983d4287656c12e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_types.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..469294679a10dca6cb98708e04dde71537363214
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-310.pyc b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b31776ffbfccc5c7aee17e40d6149ad18ca8e109
Binary files /dev/null and b/venv/lib/python3.10/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/_suite.py b/venv/lib/python3.10/site-packages/jsonschema/tests/_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..d61d38277d31d3eba23f6681d92066b8dba3ffc6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/_suite.py
@@ -0,0 +1,285 @@
+"""
+Python representations of the JSON Schema Test Suite tests.
+"""
+from __future__ import annotations
+
+from contextlib import suppress
+from functools import partial
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+import json
+import os
+import re
+import sys
+import unittest
+
+from attrs import field, frozen
+from referencing import Registry
+import referencing.jsonschema
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Mapping, Sequence
+
+ from referencing.jsonschema import Schema
+ import pyperf
+
+from jsonschema.validators import _VALIDATORS
+import jsonschema
+
+MAGIC_REMOTE_URL = "http://localhost:1234"
+
+_DELIMITERS = re.compile(r"[\W\- ]+")
+
+
+def _find_suite():
+ root = os.environ.get("JSON_SCHEMA_TEST_SUITE")
+ if root is not None:
+ return Path(root)
+
+ root = Path(jsonschema.__file__).parent.parent / "json"
+ if not root.is_dir(): # pragma: no cover
+ raise ValueError(
+ (
+ "Can't find the JSON-Schema-Test-Suite directory. "
+ "Set the 'JSON_SCHEMA_TEST_SUITE' environment "
+ "variable or run the tests from alongside a checkout "
+ "of the suite."
+ ),
+ )
+ return root
+
+
+@frozen
+class Suite:
+
+ _root: Path = field(factory=_find_suite)
+
+
+ def benchmark(self, runner: pyperf.Runner): # pragma: no cover
+ for name, Validator in _VALIDATORS.items():
+ self.version(name=name).benchmark(
+ runner=runner,
+ Validator=Validator,
+ )
+
+ def version(self, name) -> Version:
+ Validator = _VALIDATORS[name]
+ uri: str = Validator.ID_OF(Validator.META_SCHEMA) # type: ignore[assignment]
+ specification = referencing.jsonschema.specification_with(uri)
+
+ registry = Registry().with_contents(
+ remotes_in(root=self._root / "remotes", name=name, uri=uri),
+ default_specification=specification,
+ )
+ return Version(
+ name=name,
+ path=self._root / "tests" / name,
+ remotes=registry,
+ )
+
+
+@frozen
+class Version:
+
+ _path: Path
+ _remotes: referencing.jsonschema.SchemaRegistry
+
+ name: str
+
+ def benchmark(self, **kwargs): # pragma: no cover
+ for case in self.cases():
+ case.benchmark(**kwargs)
+
+ def cases(self) -> Iterable[_Case]:
+ return self._cases_in(paths=self._path.glob("*.json"))
+
+ def format_cases(self) -> Iterable[_Case]:
+ return self._cases_in(paths=self._path.glob("optional/format/*.json"))
+
+ def optional_cases_of(self, name: str) -> Iterable[_Case]:
+ return self._cases_in(paths=[self._path / "optional" / f"{name}.json"])
+
+ def to_unittest_testcase(self, *groups, **kwargs):
+ name = kwargs.pop("name", "Test" + self.name.title().replace("-", ""))
+ methods = {
+ method.__name__: method
+ for method in (
+ test.to_unittest_method(**kwargs)
+ for group in groups
+ for case in group
+ for test in case.tests
+ )
+ }
+ cls = type(name, (unittest.TestCase,), methods)
+
+ # We're doing crazy things, so if they go wrong, like a function
+ # behaving differently on some other interpreter, just make them
+ # not happen.
+ with suppress(Exception):
+ cls.__module__ = _someone_save_us_the_module_of_the_caller()
+
+ return cls
+
+ def _cases_in(self, paths: Iterable[Path]) -> Iterable[_Case]:
+ for path in paths:
+ for case in json.loads(path.read_text(encoding="utf-8")):
+ yield _Case.from_dict(
+ case,
+ version=self,
+ subject=path.stem,
+ remotes=self._remotes,
+ )
+
+
+@frozen
+class _Case:
+
+ version: Version
+
+ subject: str
+ description: str
+ schema: Mapping[str, Any] | bool
+ tests: list[_Test]
+ comment: str | None = None
+ specification: Sequence[dict[str, str]] = ()
+
+ @classmethod
+ def from_dict(cls, data, remotes, **kwargs):
+ data.update(kwargs)
+ tests = [
+ _Test(
+ version=data["version"],
+ subject=data["subject"],
+ case_description=data["description"],
+ schema=data["schema"],
+ remotes=remotes,
+ **test,
+ ) for test in data.pop("tests")
+ ]
+ return cls(tests=tests, **data)
+
+ def benchmark(self, runner: pyperf.Runner, **kwargs): # pragma: no cover
+ for test in self.tests:
+ runner.bench_func(
+ test.fully_qualified_name,
+ partial(test.validate_ignoring_errors, **kwargs),
+ )
+
+
+def remotes_in(
+ root: Path,
+ name: str,
+ uri: str,
+) -> Iterable[tuple[str, Schema]]:
+ # This messy logic is because the test suite is terrible at indicating
+ # what remotes are needed for what drafts, and mixes in schemas which
+ # have no $schema and which are invalid under earlier versions, in with
+ # other schemas which are needed for tests.
+
+ for each in root.rglob("*.json"):
+ schema = json.loads(each.read_text())
+
+ relative = str(each.relative_to(root)).replace("\\", "/")
+
+ if (
+ ( # invalid boolean schema
+ name in {"draft3", "draft4"}
+ and each.stem == "tree"
+ ) or
+ ( # draft/*.json
+ "$schema" not in schema
+ and relative.startswith("draft")
+ and not relative.startswith(name)
+ )
+ ):
+ continue
+ yield f"{MAGIC_REMOTE_URL}/{relative}", schema
+
+
+@frozen(repr=False)
+class _Test:
+
+ version: Version
+
+ subject: str
+ case_description: str
+ description: str
+
+ data: Any
+ schema: Mapping[str, Any] | bool
+
+ valid: bool
+
+ _remotes: referencing.jsonschema.SchemaRegistry
+
+ comment: str | None = None
+
+ def __repr__(self): # pragma: no cover
+ return f""
+
+ @property
+ def fully_qualified_name(self): # pragma: no cover
+ return " > ".join( # noqa: FLY002
+ [
+ self.version.name,
+ self.subject,
+ self.case_description,
+ self.description,
+ ],
+ )
+
+ def to_unittest_method(self, skip=lambda test: None, **kwargs):
+ if self.valid:
+ def fn(this):
+ self.validate(**kwargs)
+ else:
+ def fn(this):
+ with this.assertRaises(jsonschema.ValidationError):
+ self.validate(**kwargs)
+
+ fn.__name__ = "_".join(
+ [
+ "test",
+ _DELIMITERS.sub("_", self.subject),
+ _DELIMITERS.sub("_", self.case_description),
+ _DELIMITERS.sub("_", self.description),
+ ],
+ )
+ reason = skip(self)
+ if reason is None or os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
+ return fn
+ elif os.environ.get("JSON_SCHEMA_EXPECTED_FAILURES", "0") != "0": # pragma: no cover # noqa: E501
+ return unittest.expectedFailure(fn)
+ else:
+ return unittest.skip(reason)(fn)
+
+ def validate(self, Validator, **kwargs):
+ Validator.check_schema(self.schema)
+ validator = Validator(
+ schema=self.schema,
+ registry=self._remotes,
+ **kwargs,
+ )
+ if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": # pragma: no cover
+ breakpoint() # noqa: T100
+ validator.validate(instance=self.data)
+
+ def validate_ignoring_errors(self, Validator): # pragma: no cover
+ with suppress(jsonschema.ValidationError):
+ self.validate(Validator=Validator)
+
+
+def _someone_save_us_the_module_of_the_caller():
+ """
+ The FQON of the module 2nd stack frames up from here.
+
+ This is intended to allow us to dynamically return test case classes that
+ are indistinguishable from being defined in the module that wants them.
+
+ Otherwise, trial will mis-print the FQON, and copy pasting it won't re-run
+ the class that really is running.
+
+ Save us all, this is all so so so so so terrible.
+ """
+
+ return sys._getframe(2).f_globals["__name__"]
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/fuzz_validate.py b/venv/lib/python3.10/site-packages/jsonschema/tests/fuzz_validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..c12e88bcfe9bfdc0e0ffaab502789a6b585d4be2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/fuzz_validate.py
@@ -0,0 +1,50 @@
+"""
+Fuzzing setup for OSS-Fuzz.
+
+See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the
+other half of the setup here.
+"""
+import sys
+
+from hypothesis import given, strategies
+
+import jsonschema
+
+PRIM = strategies.one_of(
+ strategies.booleans(),
+ strategies.integers(),
+ strategies.floats(allow_nan=False, allow_infinity=False),
+ strategies.text(),
+)
+DICT = strategies.recursive(
+ base=strategies.one_of(
+ strategies.booleans(),
+ strategies.dictionaries(strategies.text(), PRIM),
+ ),
+ extend=lambda inner: strategies.dictionaries(strategies.text(), inner),
+)
+
+
+@given(obj1=DICT, obj2=DICT)
+def test_schemas(obj1, obj2):
+ try:
+ jsonschema.validate(instance=obj1, schema=obj2)
+ except jsonschema.exceptions.ValidationError:
+ pass
+ except jsonschema.exceptions.SchemaError:
+ pass
+
+
+def main():
+ atheris.instrument_all()
+ atheris.Setup(
+ sys.argv,
+ test_schemas.hypothesis.fuzz_one_input,
+ enable_python_coverage=True,
+ )
+ atheris.Fuzz()
+
+
+if __name__ == "__main__":
+ import atheris
+ main()
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_cli.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..bed9f3e4c4089a4cc653ffdb02d3648042df4088
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_cli.py
@@ -0,0 +1,904 @@
+from contextlib import redirect_stderr, redirect_stdout
+from importlib import metadata
+from io import StringIO
+from json import JSONDecodeError
+from pathlib import Path
+from textwrap import dedent
+from unittest import TestCase
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import warnings
+
+from jsonschema import Draft4Validator, Draft202012Validator
+from jsonschema.exceptions import (
+ SchemaError,
+ ValidationError,
+ _RefResolutionError,
+)
+from jsonschema.validators import _LATEST_VERSION, validate
+
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ from jsonschema import cli
+
+
+def fake_validator(*errors):
+ errors = list(reversed(errors))
+
+ class FakeValidator:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def iter_errors(self, instance):
+ if errors:
+ return errors.pop()
+ return [] # pragma: no cover
+
+ @classmethod
+ def check_schema(self, schema):
+ pass
+
+ return FakeValidator
+
+
+def fake_open(all_contents):
+ def open(path):
+ contents = all_contents.get(path)
+ if contents is None:
+ raise FileNotFoundError(path)
+ return StringIO(contents)
+ return open
+
+
+def _message_for(non_json):
+ try:
+ json.loads(non_json)
+ except JSONDecodeError as error:
+ return str(error)
+ else: # pragma: no cover
+ raise RuntimeError("Tried and failed to capture a JSON dump error.")
+
+
+class TestCLI(TestCase):
+ def run_cli(
+ self, argv, files=None, stdin=StringIO(), exit_code=0, **override,
+ ):
+ arguments = cli.parse_args(argv)
+ arguments.update(override)
+
+ self.assertFalse(hasattr(cli, "open"))
+ cli.open = fake_open(files or {})
+ try:
+ stdout, stderr = StringIO(), StringIO()
+ actual_exit_code = cli.run(
+ arguments,
+ stdin=stdin,
+ stdout=stdout,
+ stderr=stderr,
+ )
+ finally:
+ del cli.open
+
+ self.assertEqual(
+ actual_exit_code, exit_code, msg=dedent(
+ f"""
+ Expected an exit code of {exit_code} != {actual_exit_code}.
+
+ stdout: {stdout.getvalue()}
+
+ stderr: {stderr.getvalue()}
+ """,
+ ),
+ )
+ return stdout.getvalue(), stderr.getvalue()
+
+ def assertOutputs(self, stdout="", stderr="", **kwargs):
+ self.assertEqual(
+ self.run_cli(**kwargs),
+ (dedent(stdout), dedent(stderr)),
+ )
+
+ def test_invalid_instance(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="12: I am an error!\n",
+ )
+
+ def test_invalid_instance_pretty_output(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_instance)===
+
+ I am an error!
+ -----------------------------
+ """,
+ )
+
+ def test_invalid_instance_explicit_plain_output(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["--output", "plain", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="12: I am an error!\n",
+ )
+
+ def test_invalid_instance_multiple_errors(self):
+ instance = 12
+ first = ValidationError("First error", instance=instance)
+ second = ValidationError("Second error", instance=instance)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(instance),
+ ),
+ validator=fake_validator([first, second]),
+
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: First error
+ 12: Second error
+ """,
+ )
+
+ def test_invalid_instance_multiple_errors_pretty_output(self):
+ instance = 12
+ first = ValidationError("First error", instance=instance)
+ second = ValidationError("Second error", instance=instance)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(instance),
+ ),
+ validator=fake_validator([first, second]),
+
+ argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_instance)===
+
+ First error
+ -----------------------------
+ ===[ValidationError]===(some_instance)===
+
+ Second error
+ -----------------------------
+ """,
+ )
+
+ def test_multiple_invalid_instances(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ 12: An error
+ 12: Another error
+ foo: BOOM
+ """,
+ )
+
+ def test_multiple_invalid_instances_pretty_output(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "--output", "pretty",
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_first_instance)===
+
+ An error
+ -----------------------------
+ ===[ValidationError]===(some_first_instance)===
+
+ Another error
+ -----------------------------
+ ===[ValidationError]===(some_second_instance)===
+
+ BOOM
+ -----------------------------
+ """,
+ )
+
+ def test_custom_error_format(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "--error-format", ":{error.message}._-_.{error.instance}:",
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr=":An error._-_.12::Another error._-_.12::BOOM._-_.foo:",
+ )
+
+ def test_invalid_schema(self):
+ self.assertOutputs(
+ files=dict(some_schema='{"type": 12}'),
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: 12 is not valid under any of the given schemas
+ """,
+ )
+
+ def test_invalid_schema_pretty_output(self):
+ schema = {"type": 12}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance="")
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_schema_multiple_errors(self):
+ self.assertOutputs(
+ files=dict(some_schema='{"type": 12, "items": 57}'),
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 57: 57 is not of type 'object', 'boolean'
+ """,
+ )
+
+ def test_invalid_schema_multiple_errors_pretty_output(self):
+ schema = {"type": 12, "items": 57}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance="")
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_schema_with_invalid_instance(self):
+ """
+ "Validating" an instance that's invalid under an invalid schema
+ just shows the schema error.
+ """
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"type": 12, "minimum": 30}',
+ some_instance="13",
+ ),
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: 12 is not valid under any of the given schemas
+ """,
+ )
+
+ def test_invalid_schema_with_invalid_instance_pretty_output(self):
+ instance, schema = 13, {"type": 12, "minimum": 30}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance=instance)
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema=json.dumps(schema),
+ some_instance=json.dumps(instance),
+ ),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_instance_continues_with_the_rest(self):
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"minimum": 30}',
+ first_instance="not valid JSON!",
+ second_instance="12",
+ ),
+ argv=[
+ "-i", "first_instance",
+ "-i", "second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse 'first_instance': {}
+ 12: 12 is less than the minimum of 30
+ """.format(_message_for("not valid JSON!")),
+ )
+
+ def test_custom_error_format_applies_to_schema_errors(self):
+ instance, schema = 13, {"type": 12, "minimum": 30}
+
+ with self.assertRaises(SchemaError):
+ validate(schema=schema, instance=instance)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+
+ argv=[
+ "--error-format", ":{error.message}._-_.{error.instance}:",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr=":12 is not valid under any of the given schemas._-_.12:",
+ )
+
+ def test_instance_is_invalid_JSON(self):
+ instance = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr=f"""\
+ Failed to parse 'some_instance': {_message_for(instance)}
+ """,
+ )
+
+ def test_instance_is_invalid_JSON_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(
+ some_schema="{}",
+ some_instance="not valid JSON!",
+ ),
+
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_instance)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_schema", stderr)
+
+ def test_instance_is_invalid_JSON_on_stdin(self):
+ instance = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO(instance),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr=f"""\
+ Failed to parse : {_message_for(instance)}
+ """,
+ )
+
+ def test_instance_is_invalid_JSON_on_stdin_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("not valid JSON!"),
+
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "()===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_schema", stderr)
+
+ def test_schema_is_invalid_JSON(self):
+ schema = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema=schema),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr=f"""\
+ Failed to parse 'some_schema': {_message_for(schema)}
+ """,
+ )
+
+ def test_schema_is_invalid_JSON_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(some_schema="not valid JSON!"),
+
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_schema)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+
+ def test_schema_and_instance_are_both_invalid_JSON(self):
+ """
+ Only the schema error is reported, as we abort immediately.
+ """
+ schema, instance = "not valid JSON!", "also not valid JSON!"
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr=f"""\
+ Failed to parse 'some_schema': {_message_for(schema)}
+ """,
+ )
+
+ def test_schema_and_instance_are_both_invalid_JSON_pretty_output(self):
+ """
+ Only the schema error is reported, as we abort immediately.
+ """
+ stdout, stderr = self.run_cli(
+ files=dict(
+ some_schema="not valid JSON!",
+ some_instance="also not valid JSON!",
+ ),
+
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_schema)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_instance", stderr)
+
+ def test_instance_does_not_exist(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ argv=["-i", "nonexisting_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 'nonexisting_instance' does not exist.
+ """,
+ )
+
+ def test_instance_does_not_exist_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ argv=[
+ "--output", "pretty",
+ "-i", "nonexisting_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_instance)===
+
+ 'nonexisting_instance' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_schema_does_not_exist(self):
+ self.assertOutputs(
+ argv=["nonexisting_schema"],
+
+ exit_code=1,
+ stderr="'nonexisting_schema' does not exist.\n",
+ )
+
+ def test_schema_does_not_exist_pretty_output(self):
+ self.assertOutputs(
+ argv=["--output", "pretty", "nonexisting_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_schema)===
+
+ 'nonexisting_schema' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_neither_instance_nor_schema_exist(self):
+ self.assertOutputs(
+ argv=["-i", "nonexisting_instance", "nonexisting_schema"],
+
+ exit_code=1,
+ stderr="'nonexisting_schema' does not exist.\n",
+ )
+
+ def test_neither_instance_nor_schema_exist_pretty_output(self):
+ self.assertOutputs(
+ argv=[
+ "--output", "pretty",
+ "-i", "nonexisting_instance",
+ "nonexisting_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_schema)===
+
+ 'nonexisting_schema' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_successful_validation(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+ stdout="===[SUCCESS]===(some_instance)===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_of_stdin(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("{}"),
+ argv=["some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_of_stdin_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("{}"),
+ argv=["--output", "pretty", "some_schema"],
+ stdout="===[SUCCESS]===()===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_of_just_the_schema(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_of_just_the_schema_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+ stdout="===[SUCCESS]===(some_instance)===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_via_explicit_base_uri(self):
+ ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115
+ ref_schema_file.close()
+ self.addCleanup(os.remove, ref_schema_file.name)
+
+ ref_path = Path(ref_schema_file.name)
+ ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
+
+ schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}'
+
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance="1"),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", ref_path.parent.as_uri() + "/",
+ "some_schema",
+ ],
+ stdout="",
+ stderr="",
+ )
+
+ def test_unsuccessful_validation_via_explicit_base_uri(self):
+ ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115
+ ref_schema_file.close()
+ self.addCleanup(os.remove, ref_schema_file.name)
+
+ ref_path = Path(ref_schema_file.name)
+ ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
+
+ schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}'
+
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance='"1"'),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", ref_path.parent.as_uri() + "/",
+ "some_schema",
+ ],
+ exit_code=1,
+ stdout="",
+ stderr="1: '1' is not of type 'integer'\n",
+ )
+
+ def test_nonexistent_file_with_explicit_base_uri(self):
+ schema = '{"$ref": "someNonexistentFile.json#definitions/num"}'
+ instance = "1"
+
+ with self.assertRaises(_RefResolutionError) as e:
+ self.assertOutputs(
+ files=dict(
+ some_schema=schema,
+ some_instance=instance,
+ ),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", Path.cwd().as_uri(),
+ "some_schema",
+ ],
+ )
+ error = str(e.exception)
+ self.assertIn(f"{os.sep}someNonexistentFile.json'", error)
+
+ def test_invalid_explicit_base_uri(self):
+ schema = '{"$ref": "foo.json#definitions/num"}'
+ instance = "1"
+
+ with self.assertRaises(_RefResolutionError) as e:
+ self.assertOutputs(
+ files=dict(
+ some_schema=schema,
+ some_instance=instance,
+ ),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", "not@UR1",
+ "some_schema",
+ ],
+ )
+ error = str(e.exception)
+ self.assertEqual(
+ error, "unknown url type: 'foo.json'",
+ )
+
+ def test_it_validates_using_the_latest_validator_when_unspecified(self):
+ # There isn't a better way now I can think of to ensure that the
+ # latest version was used, given that the call to validator_for
+ # is hidden inside the CLI, so guard that that's the case, and
+ # this test will have to be updated when versions change until
+ # we can think of a better way to ensure this behavior.
+ self.assertIs(Draft202012Validator, _LATEST_VERSION)
+
+ self.assertOutputs(
+ files=dict(some_schema='{"const": "check"}', some_instance='"a"'),
+ argv=["-i", "some_instance", "some_schema"],
+ exit_code=1,
+ stdout="",
+ stderr="a: 'check' was expected\n",
+ )
+
+ def test_it_validates_using_draft7_when_specified(self):
+ """
+ Specifically, `const` validation applies for Draft 7.
+ """
+ schema = """
+ {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "const": "check"
+ }
+ """
+ instance = '"foo"'
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+ exit_code=1,
+ stdout="",
+ stderr="foo: 'check' was expected\n",
+ )
+
+ def test_it_validates_using_draft4_when_specified(self):
+ """
+ Specifically, `const` validation *does not* apply for Draft 4.
+ """
+ schema = """
+ {
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "const": "check"
+ }
+ """
+ instance = '"foo"'
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+
+class TestParser(TestCase):
+
+ FakeValidator = fake_validator()
+
+ def test_find_validator_by_fully_qualified_object_name(self):
+ arguments = cli.parse_args(
+ [
+ "--validator",
+ "jsonschema.tests.test_cli.TestParser.FakeValidator",
+ "--instance", "mem://some/instance",
+ "mem://some/schema",
+ ],
+ )
+ self.assertIs(arguments["validator"], self.FakeValidator)
+
+ def test_find_validator_in_jsonschema(self):
+ arguments = cli.parse_args(
+ [
+ "--validator", "Draft4Validator",
+ "--instance", "mem://some/instance",
+ "mem://some/schema",
+ ],
+ )
+ self.assertIs(arguments["validator"], Draft4Validator)
+
+ def cli_output_for(self, *argv):
+ stdout, stderr = StringIO(), StringIO()
+ with redirect_stdout(stdout), redirect_stderr(stderr): # noqa: SIM117
+ with self.assertRaises(SystemExit):
+ cli.parse_args(argv)
+ return stdout.getvalue(), stderr.getvalue()
+
+ def test_unknown_output(self):
+ stdout, stderr = self.cli_output_for(
+ "--output", "foo",
+ "mem://some/schema",
+ )
+ self.assertIn("invalid choice: 'foo'", stderr)
+ self.assertFalse(stdout)
+
+ def test_useless_error_format(self):
+ stdout, stderr = self.cli_output_for(
+ "--output", "pretty",
+ "--error-format", "foo",
+ "mem://some/schema",
+ )
+ self.assertIn(
+ "--error-format can only be used with --output plain",
+ stderr,
+ )
+ self.assertFalse(stdout)
+
+
+class TestCLIIntegration(TestCase):
+ def test_license(self):
+ our_metadata = metadata.metadata("jsonschema")
+ self.assertEqual(our_metadata.get("License-Expression"), "MIT")
+
+ def test_version(self):
+ version = subprocess.check_output(
+ [sys.executable, "-W", "ignore", "-m", "jsonschema", "--version"],
+ stderr=subprocess.STDOUT,
+ )
+ version = version.decode("utf-8").strip()
+ self.assertEqual(version, metadata.version("jsonschema"))
+
+ def test_no_arguments_shows_usage_notes(self):
+ output = subprocess.check_output(
+ [sys.executable, "-m", "jsonschema"],
+ stderr=subprocess.STDOUT,
+ )
+ output_for_help = subprocess.check_output(
+ [sys.executable, "-m", "jsonschema", "--help"],
+ stderr=subprocess.STDOUT,
+ )
+ self.assertEqual(output, output_for_help)
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_deprecations.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54b02f380ae098ba7b3f2c518a44935859f1ce6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_deprecations.py
@@ -0,0 +1,432 @@
+from contextlib import contextmanager
+from io import BytesIO
+from unittest import TestCase, mock
+import importlib.metadata
+import json
+import subprocess
+import sys
+import urllib.request
+
+import referencing.exceptions
+
+from jsonschema import FormatChecker, exceptions, protocols, validators
+
+
+class TestDeprecations(TestCase):
+ def test_version(self):
+ """
+ As of v4.0.0, __version__ is deprecated in favor of importlib.metadata.
+ """
+
+ message = "Accessing jsonschema.__version__ is deprecated"
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import __version__
+
+ self.assertEqual(__version__, importlib.metadata.version("jsonschema"))
+ self.assertEqual(w.filename, __file__)
+
+ def test_validators_ErrorTree(self):
+ """
+ As of v4.0.0, importing ErrorTree from jsonschema.validators is
+ deprecated in favor of doing so from jsonschema.exceptions.
+ """
+
+ message = "Importing ErrorTree from jsonschema.validators is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema.validators import ErrorTree
+
+ self.assertEqual(ErrorTree, exceptions.ErrorTree)
+ self.assertEqual(w.filename, __file__)
+
+ def test_import_ErrorTree(self):
+ """
+ As of v4.18.0, importing ErrorTree from the package root is
+ deprecated in favor of doing so from jsonschema.exceptions.
+ """
+
+ message = "Importing ErrorTree directly from the jsonschema package "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import ErrorTree
+
+ self.assertEqual(ErrorTree, exceptions.ErrorTree)
+ self.assertEqual(w.filename, __file__)
+
+ def test_ErrorTree_setitem(self):
+ """
+ As of v4.20.0, setting items on an ErrorTree is deprecated.
+ """
+
+ e = exceptions.ValidationError("some error", path=["foo"])
+ tree = exceptions.ErrorTree()
+ subtree = exceptions.ErrorTree(errors=[e])
+
+ message = "ErrorTree.__setitem__ is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ tree["foo"] = subtree
+
+ self.assertEqual(tree["foo"], subtree)
+ self.assertEqual(w.filename, __file__)
+
+ def test_import_FormatError(self):
+ """
+ As of v4.18.0, importing FormatError from the package root is
+ deprecated in favor of doing so from jsonschema.exceptions.
+ """
+
+ message = "Importing FormatError directly from the jsonschema package "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import FormatError
+
+ self.assertEqual(FormatError, exceptions.FormatError)
+ self.assertEqual(w.filename, __file__)
+
+ def test_import_Validator(self):
+ """
+ As of v4.19.0, importing Validator from the package root is
+ deprecated in favor of doing so from jsonschema.protocols.
+ """
+
+ message = "Importing Validator directly from the jsonschema package "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import Validator
+
+ self.assertEqual(Validator, protocols.Validator)
+ self.assertEqual(w.filename, __file__)
+
+ def test_validators_validators(self):
+ """
+ As of v4.0.0, accessing jsonschema.validators.validators is
+ deprecated.
+ """
+
+ message = "Accessing jsonschema.validators.validators is deprecated"
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ value = validators.validators
+
+ self.assertEqual(value, validators._VALIDATORS)
+ self.assertEqual(w.filename, __file__)
+
+ def test_validators_meta_schemas(self):
+ """
+ As of v4.0.0, accessing jsonschema.validators.meta_schemas is
+ deprecated.
+ """
+
+ message = "Accessing jsonschema.validators.meta_schemas is deprecated"
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ value = validators.meta_schemas
+
+ self.assertEqual(value, validators._META_SCHEMAS)
+ self.assertEqual(w.filename, __file__)
+
+ def test_RefResolver_in_scope(self):
+ """
+ As of v4.0.0, RefResolver.in_scope is deprecated.
+ """
+
+ resolver = validators._RefResolver.from_schema({})
+ message = "jsonschema.RefResolver.in_scope is deprecated "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w: # noqa: SIM117
+ with resolver.in_scope("foo"):
+ pass
+
+ self.assertEqual(w.filename, __file__)
+
+ def test_Validator_is_valid_two_arguments(self):
+ """
+ As of v4.0.0, calling is_valid with two arguments (to provide a
+ different schema) is deprecated.
+ """
+
+ validator = validators.Draft7Validator({})
+ message = "Passing a schema to Validator.is_valid is deprecated "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ result = validator.is_valid("foo", {"type": "number"})
+
+ self.assertFalse(result)
+ self.assertEqual(w.filename, __file__)
+
+ def test_Validator_iter_errors_two_arguments(self):
+ """
+ As of v4.0.0, calling iter_errors with two arguments (to provide a
+ different schema) is deprecated.
+ """
+
+ validator = validators.Draft7Validator({})
+ message = "Passing a schema to Validator.iter_errors is deprecated "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ error, = validator.iter_errors("foo", {"type": "number"})
+
+ self.assertEqual(error.validator, "type")
+ self.assertEqual(w.filename, __file__)
+
+ def test_Validator_resolver(self):
+ """
+ As of v4.18.0, accessing Validator.resolver is deprecated.
+ """
+
+ validator = validators.Draft7Validator({})
+ message = "Accessing Draft7Validator.resolver is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ self.assertIsInstance(validator.resolver, validators._RefResolver)
+
+ self.assertEqual(w.filename, __file__)
+
+ def test_RefResolver(self):
+ """
+ As of v4.18.0, RefResolver is fully deprecated.
+ """
+
+ message = "jsonschema.RefResolver is deprecated"
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import RefResolver
+ self.assertEqual(w.filename, __file__)
+
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema.validators import RefResolver # noqa: F401
+ self.assertEqual(w.filename, __file__)
+
+ def test_RefResolutionError(self):
+ """
+ As of v4.18.0, RefResolutionError is deprecated in favor of directly
+ catching errors from the referencing library.
+ """
+
+ message = "jsonschema.exceptions.RefResolutionError is deprecated"
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import RefResolutionError
+
+ self.assertEqual(RefResolutionError, exceptions._RefResolutionError)
+ self.assertEqual(w.filename, __file__)
+
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema.exceptions import RefResolutionError
+
+ self.assertEqual(RefResolutionError, exceptions._RefResolutionError)
+ self.assertEqual(w.filename, __file__)
+
+ def test_catching_Unresolvable_directly(self):
+ """
+ This behavior is the intended behavior (i.e. it's not deprecated), but
+ given we do "tricksy" things in the iterim to wrap exceptions in a
+ multiple inheritance subclass, we need to be extra sure it works and
+ stays working.
+ """
+ validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
+
+ with self.assertRaises(referencing.exceptions.Unresolvable) as e:
+ validator.validate(12)
+
+ expected = referencing.exceptions.Unresolvable(ref="urn:nothing")
+ self.assertEqual(
+ (e.exception, str(e.exception)),
+ (expected, "Unresolvable: urn:nothing"),
+ )
+
+ def test_catching_Unresolvable_via_RefResolutionError(self):
+ """
+ Until RefResolutionError is removed, it is still possible to catch
+ exceptions from reference resolution using it, even though they may
+ have been raised by referencing.
+ """
+ with self.assertWarns(DeprecationWarning):
+ from jsonschema import RefResolutionError
+
+ validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
+
+ with self.assertRaises(referencing.exceptions.Unresolvable) as u:
+ validator.validate(12)
+
+ with self.assertRaises(RefResolutionError) as e:
+ validator.validate(12)
+
+ self.assertEqual(
+ (e.exception, str(e.exception)),
+ (u.exception, "Unresolvable: urn:nothing"),
+ )
+
+ def test_WrappedReferencingError_hashability(self):
+ """
+ Ensure the wrapped referencing errors are hashable when possible.
+ """
+ with self.assertWarns(DeprecationWarning):
+ from jsonschema import RefResolutionError
+
+ validator = validators.Draft202012Validator({"$ref": "urn:nothing"})
+
+ with self.assertRaises(referencing.exceptions.Unresolvable) as u:
+ validator.validate(12)
+
+ with self.assertRaises(RefResolutionError) as e:
+ validator.validate(12)
+
+ self.assertIn(e.exception, {u.exception})
+ self.assertIn(u.exception, {e.exception})
+
+ def test_Validator_subclassing(self):
+ """
+ As of v4.12.0, subclassing a validator class produces an explicit
+ deprecation warning.
+
+ This was never intended to be public API (and some comments over the
+ years in issues said so, but obviously that's not a great way to make
+ sure it's followed).
+
+ A future version will explicitly raise an error.
+ """
+
+ message = "Subclassing validator classes is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ class Subclass(validators.Draft202012Validator):
+ pass
+
+ self.assertEqual(w.filename, __file__)
+
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ class AnotherSubclass(validators.create(meta_schema={})):
+ pass
+
+ def test_FormatChecker_cls_checks(self):
+ """
+ As of v4.14.0, FormatChecker.cls_checks is deprecated without
+ replacement.
+ """
+
+ self.addCleanup(FormatChecker.checkers.pop, "boom", None)
+
+ message = "FormatChecker.cls_checks "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ FormatChecker.cls_checks("boom")
+
+ self.assertEqual(w.filename, __file__)
+
+ def test_draftN_format_checker(self):
+ """
+ As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated
+ in favor of Validator.FORMAT_CHECKER.
+ """
+
+ message = "Accessing jsonschema.draft202012_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft202012_format_checker
+
+ self.assertIs(
+ draft202012_format_checker,
+ validators.Draft202012Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ message = "Accessing jsonschema.draft201909_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft201909_format_checker
+
+ self.assertIs(
+ draft201909_format_checker,
+ validators.Draft201909Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ message = "Accessing jsonschema.draft7_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft7_format_checker
+
+ self.assertIs(
+ draft7_format_checker,
+ validators.Draft7Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ message = "Accessing jsonschema.draft6_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft6_format_checker
+
+ self.assertIs(
+ draft6_format_checker,
+ validators.Draft6Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ message = "Accessing jsonschema.draft4_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft4_format_checker
+
+ self.assertIs(
+ draft4_format_checker,
+ validators.Draft4Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ message = "Accessing jsonschema.draft3_format_checker is "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ from jsonschema import draft3_format_checker
+
+ self.assertIs(
+ draft3_format_checker,
+ validators.Draft3Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+
+ with self.assertRaises(ImportError):
+ from jsonschema import draft1234_format_checker # noqa: F401
+
+ def test_import_cli(self):
+ """
+ As of v4.17.0, importing jsonschema.cli is deprecated.
+ """
+
+ message = "The jsonschema CLI is deprecated and will be removed "
+ with self.assertWarnsRegex(DeprecationWarning, message) as w:
+ import jsonschema.cli
+ importlib.reload(jsonschema.cli)
+
+ self.assertEqual(w.filename, importlib.__file__)
+
+ def test_cli(self):
+ """
+ As of v4.17.0, the jsonschema CLI is deprecated.
+ """
+
+ process = subprocess.run(
+ [sys.executable, "-m", "jsonschema"],
+ capture_output=True,
+ check=True,
+ )
+ self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr)
+
+ def test_automatic_remote_retrieval(self):
+ """
+ Automatic retrieval of remote references is deprecated as of v4.18.0.
+ """
+ ref = "http://bar#/$defs/baz"
+ schema = {"$defs": {"baz": {"type": "integer"}}}
+
+ if "requests" in sys.modules: # pragma: no cover
+ self.addCleanup(
+ sys.modules.__setitem__, "requests", sys.modules["requests"],
+ )
+ sys.modules["requests"] = None
+
+ @contextmanager
+ def fake_urlopen(request):
+ self.assertIsInstance(request, urllib.request.Request)
+ self.assertEqual(request.full_url, "http://bar")
+
+ # Ha ha urllib.request.Request "normalizes" header names and
+ # Request.get_header does not also normalize them...
+ (header, value), = request.header_items()
+ self.assertEqual(header.lower(), "user-agent")
+ self.assertEqual(
+ value, "python-jsonschema (deprecated $ref resolution)",
+ )
+ yield BytesIO(json.dumps(schema).encode("utf8"))
+
+ validator = validators.Draft202012Validator({"$ref": ref})
+
+ message = "Automatically retrieving remote references "
+ patch = mock.patch.object(urllib.request, "urlopen", new=fake_urlopen)
+
+ with patch, self.assertWarnsRegex(DeprecationWarning, message):
+ self.assertEqual(
+ (validator.is_valid({}), validator.is_valid(37)),
+ (False, True),
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_exceptions.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d515a998506e779b9e2f2340204bca33f73ae04
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_exceptions.py
@@ -0,0 +1,759 @@
+from unittest import TestCase
+import textwrap
+
+import jsonpath_ng
+
+from jsonschema import exceptions
+from jsonschema.validators import _LATEST_VERSION
+
+
+class TestBestMatch(TestCase):
+ def best_match_of(self, instance, schema):
+ errors = list(_LATEST_VERSION(schema).iter_errors(instance))
+ msg = f"No errors found for {instance} under {schema!r}!"
+ self.assertTrue(errors, msg=msg)
+
+ best = exceptions.best_match(iter(errors))
+ reversed_best = exceptions.best_match(reversed(errors))
+
+ self.assertEqual(
+ best._contents(),
+ reversed_best._contents(),
+ f"No consistent best match!\nGot: {best}\n\nThen: {reversed_best}",
+ )
+ return best
+
+ def test_shallower_errors_are_better_matches(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "minProperties": 2,
+ "properties": {"bar": {"type": "object"}},
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": []}}, schema=schema)
+ self.assertEqual(best.validator, "minProperties")
+
+ def test_oneOf_and_anyOf_are_weak_matches(self):
+ """
+ A property you *must* match is probably better than one you have to
+ match a part of.
+ """
+
+ schema = {
+ "minProperties": 2,
+ "anyOf": [{"type": "string"}, {"type": "number"}],
+ "oneOf": [{"type": "string"}, {"type": "number"}],
+ }
+ best = self.best_match_of(instance={}, schema=schema)
+ self.assertEqual(best.validator, "minProperties")
+
+ def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
+ """
+ If the most relevant error is an anyOf, then we traverse its context
+ and select the otherwise *least* relevant error, since in this case
+ that means the most specific, deep, error inside the instance.
+
+ I.e. since only one of the schemas must match, we look for the most
+ relevant one.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_no_anyOf_traversal_for_equally_relevant_errors(self):
+ """
+ We don't traverse into an anyOf (as above) if all of its context errors
+ seem to be equally "wrong" against the instance.
+ """
+
+ schema = {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "integer"},
+ {"type": "object"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "anyOf")
+
+ def test_anyOf_traversal_for_single_equally_relevant_error(self):
+ """
+ We *do* traverse anyOf with a single nested error, even though it is
+ vacuously equally relevant to itself.
+ """
+
+ schema = {
+ "anyOf": [
+ {"type": "string"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "type")
+
+ def test_anyOf_traversal_for_single_sibling_errors(self):
+ """
+ We *do* traverse anyOf with a single subschema that fails multiple
+ times (e.g. on multiple items).
+ """
+
+ schema = {
+ "anyOf": [
+ {"items": {"const": 37}},
+ ],
+ }
+ best = self.best_match_of(instance=[12, 12], schema=schema)
+ self.assertEqual(best.validator, "const")
+
+ def test_anyOf_traversal_for_non_type_matching_sibling_errors(self):
+ """
+ We *do* traverse anyOf with multiple subschemas when one does not type
+ match.
+ """
+
+ schema = {
+ "anyOf": [
+ {"type": "object"},
+ {"items": {"const": 37}},
+ ],
+ }
+ best = self.best_match_of(instance=[12, 12], schema=schema)
+ self.assertEqual(best.validator, "const")
+
+ def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
+ """
+ If the most relevant error is an oneOf, then we traverse its context
+ and select the otherwise *least* relevant error, since in this case
+ that means the most specific, deep, error inside the instance.
+
+ I.e. since only one of the schemas must match, we look for the most
+ relevant one.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "oneOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_no_oneOf_traversal_for_equally_relevant_errors(self):
+ """
+ We don't traverse into an oneOf (as above) if all of its context errors
+ seem to be equally "wrong" against the instance.
+ """
+
+ schema = {
+ "oneOf": [
+ {"type": "string"},
+ {"type": "integer"},
+ {"type": "object"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "oneOf")
+
+ def test_oneOf_traversal_for_single_equally_relevant_error(self):
+ """
+ We *do* traverse oneOf with a single nested error, even though it is
+ vacuously equally relevant to itself.
+ """
+
+ schema = {
+ "oneOf": [
+ {"type": "string"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "type")
+
+ def test_oneOf_traversal_for_single_sibling_errors(self):
+ """
+ We *do* traverse oneOf with a single subschema that fails multiple
+ times (e.g. on multiple items).
+ """
+
+ schema = {
+ "oneOf": [
+ {"items": {"const": 37}},
+ ],
+ }
+ best = self.best_match_of(instance=[12, 12], schema=schema)
+ self.assertEqual(best.validator, "const")
+
+ def test_oneOf_traversal_for_non_type_matching_sibling_errors(self):
+ """
+ We *do* traverse oneOf with multiple subschemas when one does not type
+ match.
+ """
+
+ schema = {
+ "oneOf": [
+ {"type": "object"},
+ {"items": {"const": 37}},
+ ],
+ }
+ best = self.best_match_of(instance=[12, 12], schema=schema)
+ self.assertEqual(best.validator, "const")
+
+ def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
+ """
+ Now, if the error is allOf, we traverse but select the *most* relevant
+ error from the context, because all schemas here must match anyways.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "allOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "string")
+
+ def test_nested_context_for_oneOf(self):
+ """
+ We traverse into nested contexts (a oneOf containing an error in a
+ nested oneOf here).
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "oneOf": [
+ {"type": "string"},
+ {
+ "oneOf": [
+ {"type": "string"},
+ {
+ "properties": {
+ "bar": {"type": "array"},
+ },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_it_prioritizes_matching_types(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "array", "minItems": 2},
+ {"type": "string", "minLength": 10},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertEqual(best.validator, "minLength")
+
+ reordered = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string", "minLength": 10},
+ {"type": "array", "minItems": 2},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
+ self.assertEqual(best.validator, "minLength")
+
+ def test_it_prioritizes_matching_union_types(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": ["array", "object"], "minItems": 2},
+ {"type": ["integer", "string"], "minLength": 10},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertEqual(best.validator, "minLength")
+
+ reordered = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string", "minLength": 10},
+ {"type": "array", "minItems": 2},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
+ self.assertEqual(best.validator, "minLength")
+
+ def test_boolean_schemas(self):
+ schema = {"properties": {"foo": False}}
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertIsNone(best.validator)
+
+ def test_one_error(self):
+ validator = _LATEST_VERSION({"minProperties": 2})
+ error, = validator.iter_errors({})
+ self.assertEqual(
+ exceptions.best_match(validator.iter_errors({})).validator,
+ "minProperties",
+ )
+
+ def test_no_errors(self):
+ validator = _LATEST_VERSION({})
+ self.assertIsNone(exceptions.best_match(validator.iter_errors({})))
+
+
+class TestByRelevance(TestCase):
+ def test_short_paths_are_better_matches(self):
+ shallow = exceptions.ValidationError("Oh no!", path=["baz"])
+ deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])
+ match = max([shallow, deep], key=exceptions.relevance)
+ self.assertIs(match, shallow)
+
+ match = max([deep, shallow], key=exceptions.relevance)
+ self.assertIs(match, shallow)
+
+ def test_global_errors_are_even_better_matches(self):
+ shallow = exceptions.ValidationError("Oh no!", path=[])
+ deep = exceptions.ValidationError("Oh yes!", path=["foo"])
+
+ errors = sorted([shallow, deep], key=exceptions.relevance)
+ self.assertEqual(
+ [list(error.path) for error in errors],
+ [["foo"], []],
+ )
+
+ errors = sorted([deep, shallow], key=exceptions.relevance)
+ self.assertEqual(
+ [list(error.path) for error in errors],
+ [["foo"], []],
+ )
+
+ def test_weak_keywords_are_lower_priority(self):
+ weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
+ normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
+
+ best_match = exceptions.by_relevance(weak="a")
+
+ match = max([weak, normal], key=best_match)
+ self.assertIs(match, normal)
+
+ match = max([normal, weak], key=best_match)
+ self.assertIs(match, normal)
+
+ def test_strong_keywords_are_higher_priority(self):
+ weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
+ normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
+ strong = exceptions.ValidationError("Oh fine!", path=[], validator="c")
+
+ best_match = exceptions.by_relevance(weak="a", strong="c")
+
+ match = max([weak, normal, strong], key=best_match)
+ self.assertIs(match, strong)
+
+ match = max([strong, normal, weak], key=best_match)
+ self.assertIs(match, strong)
+
+
+class TestErrorTree(TestCase):
+ def test_it_knows_how_many_total_errors_it_contains(self):
+ # FIXME: #442
+ errors = [
+ exceptions.ValidationError("Something", validator=i)
+ for i in range(8)
+ ]
+ tree = exceptions.ErrorTree(errors)
+ self.assertEqual(tree.total_errors, 8)
+
+ def test_it_contains_an_item_if_the_item_had_an_error(self):
+ errors = [exceptions.ValidationError("a message", path=["bar"])]
+ tree = exceptions.ErrorTree(errors)
+ self.assertIn("bar", tree)
+
+ def test_it_does_not_contain_an_item_if_the_item_had_no_error(self):
+ errors = [exceptions.ValidationError("a message", path=["bar"])]
+ tree = exceptions.ErrorTree(errors)
+ self.assertNotIn("foo", tree)
+
+ def test_keywords_that_failed_appear_in_errors_dict(self):
+ error = exceptions.ValidationError("a message", validator="foo")
+ tree = exceptions.ErrorTree([error])
+ self.assertEqual(tree.errors, {"foo": error})
+
+ def test_it_creates_a_child_tree_for_each_nested_path(self):
+ errors = [
+ exceptions.ValidationError("a bar message", path=["bar"]),
+ exceptions.ValidationError("a bar -> 0 message", path=["bar", 0]),
+ ]
+ tree = exceptions.ErrorTree(errors)
+ self.assertIn(0, tree["bar"])
+ self.assertNotIn(1, tree["bar"])
+
+ def test_children_have_their_errors_dicts_built(self):
+ e1, e2 = (
+ exceptions.ValidationError("1", validator="foo", path=["bar", 0]),
+ exceptions.ValidationError("2", validator="quux", path=["bar", 0]),
+ )
+ tree = exceptions.ErrorTree([e1, e2])
+ self.assertEqual(tree["bar"][0].errors, {"foo": e1, "quux": e2})
+
+ def test_multiple_errors_with_instance(self):
+ e1, e2 = (
+ exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1"),
+ exceptions.ValidationError(
+ "2",
+ validator="quux",
+ path=["foobar", 2],
+ instance="i2"),
+ )
+ exceptions.ErrorTree([e1, e2])
+
+ def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self):
+ error = exceptions.ValidationError("123", validator="foo", instance=[])
+ tree = exceptions.ErrorTree([error])
+
+ with self.assertRaises(IndexError):
+ tree[0]
+
+ def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):
+ """
+ If a keyword refers to a path that isn't in the instance, the
+ tree still properly returns a subtree for that path.
+ """
+
+ error = exceptions.ValidationError(
+ "a message", validator="foo", instance={}, path=["foo"],
+ )
+ tree = exceptions.ErrorTree([error])
+ self.assertIsInstance(tree["foo"], exceptions.ErrorTree)
+
+ def test_iter(self):
+ e1, e2 = (
+ exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1"),
+ exceptions.ValidationError(
+ "2",
+ validator="quux",
+ path=["foobar", 2],
+ instance="i2"),
+ )
+ tree = exceptions.ErrorTree([e1, e2])
+ self.assertEqual(set(tree), {"bar", "foobar"})
+
+ def test_repr_single(self):
+ error = exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1",
+ )
+ tree = exceptions.ErrorTree([error])
+ self.assertEqual(repr(tree), "")
+
+ def test_repr_multiple(self):
+ e1, e2 = (
+ exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1"),
+ exceptions.ValidationError(
+ "2",
+ validator="quux",
+ path=["foobar", 2],
+ instance="i2"),
+ )
+ tree = exceptions.ErrorTree([e1, e2])
+ self.assertEqual(repr(tree), "")
+
+ def test_repr_empty(self):
+ tree = exceptions.ErrorTree([])
+ self.assertEqual(repr(tree), "")
+
+
+class TestErrorInitReprStr(TestCase):
+ def make_error(self, **kwargs):
+ defaults = dict(
+ message="hello",
+ validator="type",
+ validator_value="string",
+ instance=5,
+ schema={"type": "string"},
+ )
+ defaults.update(kwargs)
+ return exceptions.ValidationError(**defaults)
+
+ def assertShows(self, expected, **kwargs):
+ expected = textwrap.dedent(expected).rstrip("\n")
+
+ error = self.make_error(**kwargs)
+ message_line, _, rest = str(error).partition("\n")
+ self.assertEqual(message_line, error.message)
+ self.assertEqual(rest, expected)
+
+ def test_it_calls_super_and_sets_args(self):
+ error = self.make_error()
+ self.assertGreater(len(error.args), 1)
+
+ def test_repr(self):
+ self.assertEqual(
+ repr(exceptions.ValidationError(message="Hello!")),
+ "",
+ )
+
+ def test_unset_error(self):
+ error = exceptions.ValidationError("message")
+ self.assertEqual(str(error), "message")
+
+ kwargs = {
+ "validator": "type",
+ "validator_value": "string",
+ "instance": 5,
+ "schema": {"type": "string"},
+ }
+ # Just the message should show if any of the attributes are unset
+ for attr in kwargs:
+ k = dict(kwargs)
+ del k[attr]
+ error = exceptions.ValidationError("message", **k)
+ self.assertEqual(str(error), "message")
+
+ def test_empty_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema:
+ {'type': 'string'}
+
+ On instance:
+ 5
+ """,
+ path=[],
+ schema_path=[],
+ )
+
+ def test_one_item_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema:
+ {'type': 'string'}
+
+ On instance[0]:
+ 5
+ """,
+ path=[0],
+ schema_path=["items"],
+ )
+
+ def test_multiple_item_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema['items'][0]:
+ {'type': 'string'}
+
+ On instance[0]['a']:
+ 5
+ """,
+ path=[0, "a"],
+ schema_path=["items", 0, 1],
+ )
+
+ def test_uses_pprint(self):
+ self.assertShows(
+ """
+ Failed validating 'maxLength' in schema:
+ {0: 0,
+ 1: 1,
+ 2: 2,
+ 3: 3,
+ 4: 4,
+ 5: 5,
+ 6: 6,
+ 7: 7,
+ 8: 8,
+ 9: 9,
+ 10: 10,
+ 11: 11,
+ 12: 12,
+ 13: 13,
+ 14: 14,
+ 15: 15,
+ 16: 16,
+ 17: 17,
+ 18: 18,
+ 19: 19}
+
+ On instance:
+ [0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ 16,
+ 17,
+ 18,
+ 19,
+ 20,
+ 21,
+ 22,
+ 23,
+ 24]
+ """,
+ instance=list(range(25)),
+ schema=dict(zip(range(20), range(20))),
+ validator="maxLength",
+ )
+
+ def test_does_not_reorder_dicts(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema:
+ {'do': 3, 'not': 7, 'sort': 37, 'me': 73}
+
+ On instance:
+ {'here': 73, 'too': 37, 'no': 7, 'sorting': 3}
+ """,
+ schema={
+ "do": 3,
+ "not": 7,
+ "sort": 37,
+ "me": 73,
+ },
+ instance={
+ "here": 73,
+ "too": 37,
+ "no": 7,
+ "sorting": 3,
+ },
+ )
+
+ def test_str_works_with_instances_having_overriden_eq_operator(self):
+ """
+ Check for #164 which rendered exceptions unusable when a
+ `ValidationError` involved instances with an `__eq__` method
+ that returned truthy values.
+ """
+
+ class DontEQMeBro:
+ def __eq__(this, other): # pragma: no cover
+ self.fail("Don't!")
+
+ def __ne__(this, other): # pragma: no cover
+ self.fail("Don't!")
+
+ instance = DontEQMeBro()
+ error = exceptions.ValidationError(
+ "a message",
+ validator="foo",
+ instance=instance,
+ validator_value="some",
+ schema="schema",
+ )
+ self.assertIn(repr(instance), str(error))
+
+
+class TestHashable(TestCase):
+ def test_hashable(self):
+ {exceptions.ValidationError("")}
+ {exceptions.SchemaError("")}
+
+
+class TestJsonPathRendering(TestCase):
+ def validate_json_path_rendering(self, property_name, expected_path):
+ error = exceptions.ValidationError(
+ path=[property_name],
+ message="1",
+ validator="foo",
+ instance="i1",
+ )
+
+ rendered_json_path = error.json_path
+ self.assertEqual(rendered_json_path, expected_path)
+
+ re_parsed_name = jsonpath_ng.parse(rendered_json_path).right.fields[0]
+ self.assertEqual(re_parsed_name, property_name)
+
+ def test_basic(self):
+ self.validate_json_path_rendering("x", "$.x")
+
+ def test_empty(self):
+ self.validate_json_path_rendering("", "$['']")
+
+ def test_number(self):
+ self.validate_json_path_rendering("1", "$['1']")
+
+ def test_period(self):
+ self.validate_json_path_rendering(".", "$['.']")
+
+ def test_single_quote(self):
+ self.validate_json_path_rendering("'", r"$['\'']")
+
+ def test_space(self):
+ self.validate_json_path_rendering(" ", "$[' ']")
+
+ def test_backslash(self):
+ self.validate_json_path_rendering("\\", r"$['\\']")
+
+ def test_backslash_single_quote(self):
+ self.validate_json_path_rendering(r"\'", r"$['\\\'']")
+
+ def test_underscore(self):
+ self.validate_json_path_rendering("_", r"$['_']")
+
+ def test_double_quote(self):
+ self.validate_json_path_rendering('"', """$['"']""")
+
+ def test_hyphen(self):
+ self.validate_json_path_rendering("-", "$['-']")
+
+ def test_json_path_injection(self):
+ self.validate_json_path_rendering("a[0]", "$['a[0]']")
+
+ def test_open_bracket(self):
+ self.validate_json_path_rendering("[", "$['[']")
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_format.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..d829f9848f51f882d5a3f9413c80e0dbdcdaf292
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_format.py
@@ -0,0 +1,91 @@
+"""
+Tests for the parts of jsonschema related to the :kw:`format` keyword.
+"""
+
+from unittest import TestCase
+
+from jsonschema import FormatChecker, ValidationError
+from jsonschema.exceptions import FormatError
+from jsonschema.validators import Draft4Validator
+
+BOOM = ValueError("Boom!")
+BANG = ZeroDivisionError("Bang!")
+
+
+def boom(thing):
+ if thing == "bang":
+ raise BANG
+ raise BOOM
+
+
+class TestFormatChecker(TestCase):
+ def test_it_can_validate_no_formats(self):
+ checker = FormatChecker(formats=())
+ self.assertFalse(checker.checkers)
+
+ def test_it_raises_a_key_error_for_unknown_formats(self):
+ with self.assertRaises(KeyError):
+ FormatChecker(formats=["o noes"])
+
+ def test_it_can_register_cls_checkers(self):
+ original = dict(FormatChecker.checkers)
+ self.addCleanup(FormatChecker.checkers.pop, "boom")
+ with self.assertWarns(DeprecationWarning):
+ FormatChecker.cls_checks("boom")(boom)
+ self.assertEqual(
+ FormatChecker.checkers,
+ dict(original, boom=(boom, ())),
+ )
+
+ def test_it_can_register_checkers(self):
+ checker = FormatChecker()
+ checker.checks("boom")(boom)
+ self.assertEqual(
+ checker.checkers,
+ dict(FormatChecker.checkers, boom=(boom, ())),
+ )
+
+ def test_it_catches_registered_errors(self):
+ checker = FormatChecker()
+ checker.checks("boom", raises=type(BOOM))(boom)
+
+ with self.assertRaises(FormatError) as cm:
+ checker.check(instance=12, format="boom")
+
+ self.assertIs(cm.exception.cause, BOOM)
+ self.assertIs(cm.exception.__cause__, BOOM)
+ self.assertEqual(str(cm.exception), "12 is not a 'boom'")
+
+ # Unregistered errors should not be caught
+ with self.assertRaises(type(BANG)):
+ checker.check(instance="bang", format="boom")
+
+ def test_format_error_causes_become_validation_error_causes(self):
+ checker = FormatChecker()
+ checker.checks("boom", raises=ValueError)(boom)
+ validator = Draft4Validator({"format": "boom"}, format_checker=checker)
+
+ with self.assertRaises(ValidationError) as cm:
+ validator.validate("BOOM")
+
+ self.assertIs(cm.exception.cause, BOOM)
+ self.assertIs(cm.exception.__cause__, BOOM)
+
+ def test_format_checkers_come_with_defaults(self):
+ # This is bad :/ but relied upon.
+ # The docs for quite awhile recommended people do things like
+ # validate(..., format_checker=FormatChecker())
+ # We should change that, but we can't without deprecation...
+ checker = FormatChecker()
+ with self.assertRaises(FormatError):
+ checker.check(instance="not-an-ipv4", format="ipv4")
+
+ def test_repr(self):
+ checker = FormatChecker(formats=())
+ checker.checks("foo")(lambda thing: True) # pragma: no cover
+ checker.checks("bar")(lambda thing: True) # pragma: no cover
+ checker.checks("baz")(lambda thing: True) # pragma: no cover
+ self.assertEqual(
+ repr(checker),
+ "",
+ )
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_jsonschema_test_suite.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_jsonschema_test_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..41c982553688ab179dcb95eedc3aae78648e2a4d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_jsonschema_test_suite.py
@@ -0,0 +1,262 @@
+"""
+Test runner for the JSON Schema official test suite
+
+Tests comprehensive correctness of each draft's validator.
+
+See https://github.com/json-schema-org/JSON-Schema-Test-Suite for details.
+"""
+
+
+from jsonschema.tests._suite import Suite
+import jsonschema
+
+SUITE = Suite()
+DRAFT3 = SUITE.version(name="draft3")
+DRAFT4 = SUITE.version(name="draft4")
+DRAFT6 = SUITE.version(name="draft6")
+DRAFT7 = SUITE.version(name="draft7")
+DRAFT201909 = SUITE.version(name="draft2019-09")
+DRAFT202012 = SUITE.version(name="draft2020-12")
+
+
+def skip(message, **kwargs):
+ def skipper(test):
+ if all(value == getattr(test, attr) for attr, value in kwargs.items()):
+ return message
+ return skipper
+
+
+def ecmascript_regex(test):
+ if test.subject == "ecmascript-regex":
+ return "ECMA regex support will be added in #1142."
+
+
+def missing_format(Validator):
+ def missing_format(test): # pragma: no cover
+ schema = test.schema
+ if (
+ schema is True
+ or schema is False
+ or "format" not in schema
+ or schema["format"] in Validator.FORMAT_CHECKER.checkers
+ or test.valid
+ ):
+ return
+
+ return f"Format checker {schema['format']!r} not found."
+ return missing_format
+
+
+def complex_email_validation(test):
+ if test.subject != "email":
+ return
+
+ message = "Complex email validation is (intentionally) unsupported."
+ return skip(
+ message=message,
+ description="an invalid domain",
+ )(test) or skip(
+ message=message,
+ description="an invalid IPv4-address-literal",
+ )(test) or skip(
+ message=message,
+ description="dot after local part is not valid",
+ )(test) or skip(
+ message=message,
+ description="dot before local part is not valid",
+ )(test) or skip(
+ message=message,
+ description="two subsequent dots inside local part are not valid",
+ )(test)
+
+
+def leap_second(test):
+ message = "Leap seconds are unsupported."
+ return skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second, Zulu",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second with offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, positive time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, negative time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, large positive time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, large negative time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, zero time-offset",
+ )(test) or skip(
+ message=message,
+ subject="date-time",
+ description="a valid date-time with a leap second, UTC",
+ )(test) or skip(
+ message=message,
+ subject="date-time",
+ description="a valid date-time with a leap second, with minus offset",
+ )(test)
+
+
+TestDraft3 = DRAFT3.to_unittest_testcase(
+ DRAFT3.cases(),
+ DRAFT3.format_cases(),
+ DRAFT3.optional_cases_of(name="bignum"),
+ DRAFT3.optional_cases_of(name="non-bmp-regex"),
+ DRAFT3.optional_cases_of(name="zeroTerminatedFloats"),
+ Validator=jsonschema.Draft3Validator,
+ format_checker=jsonschema.Draft3Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ ecmascript_regex(test)
+ or missing_format(jsonschema.Draft3Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft4 = DRAFT4.to_unittest_testcase(
+ DRAFT4.cases(),
+ DRAFT4.format_cases(),
+ DRAFT4.optional_cases_of(name="bignum"),
+ DRAFT4.optional_cases_of(name="float-overflow"),
+ DRAFT4.optional_cases_of(name="id"),
+ DRAFT4.optional_cases_of(name="non-bmp-regex"),
+ DRAFT4.optional_cases_of(name="zeroTerminatedFloats"),
+ Validator=jsonschema.Draft4Validator,
+ format_checker=jsonschema.Draft4Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ ecmascript_regex(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft4Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft6 = DRAFT6.to_unittest_testcase(
+ DRAFT6.cases(),
+ DRAFT6.format_cases(),
+ DRAFT6.optional_cases_of(name="bignum"),
+ DRAFT6.optional_cases_of(name="float-overflow"),
+ DRAFT6.optional_cases_of(name="id"),
+ DRAFT6.optional_cases_of(name="non-bmp-regex"),
+ Validator=jsonschema.Draft6Validator,
+ format_checker=jsonschema.Draft6Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ ecmascript_regex(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft6Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft7 = DRAFT7.to_unittest_testcase(
+ DRAFT7.cases(),
+ DRAFT7.format_cases(),
+ DRAFT7.optional_cases_of(name="bignum"),
+ DRAFT7.optional_cases_of(name="cross-draft"),
+ DRAFT7.optional_cases_of(name="float-overflow"),
+ DRAFT6.optional_cases_of(name="id"),
+ DRAFT7.optional_cases_of(name="non-bmp-regex"),
+ DRAFT7.optional_cases_of(name="unknownKeyword"),
+ Validator=jsonschema.Draft7Validator,
+ format_checker=jsonschema.Draft7Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ ecmascript_regex(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft7Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft201909 = DRAFT201909.to_unittest_testcase(
+ DRAFT201909.cases(),
+ DRAFT201909.optional_cases_of(name="anchor"),
+ DRAFT201909.optional_cases_of(name="bignum"),
+ DRAFT201909.optional_cases_of(name="cross-draft"),
+ DRAFT201909.optional_cases_of(name="float-overflow"),
+ DRAFT201909.optional_cases_of(name="id"),
+ DRAFT201909.optional_cases_of(name="no-schema"),
+ DRAFT201909.optional_cases_of(name="non-bmp-regex"),
+ DRAFT201909.optional_cases_of(name="refOfUnknownKeyword"),
+ DRAFT201909.optional_cases_of(name="unknownKeyword"),
+ Validator=jsonschema.Draft201909Validator,
+ skip=skip(
+ message="Vocabulary support is still in-progress.",
+ subject="vocabulary",
+ description=(
+ "no validation: invalid number, but it still validates"
+ ),
+ ),
+)
+
+
+TestDraft201909Format = DRAFT201909.to_unittest_testcase(
+ DRAFT201909.format_cases(),
+ name="TestDraft201909Format",
+ Validator=jsonschema.Draft201909Validator,
+ format_checker=jsonschema.Draft201909Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ complex_email_validation(test)
+ or ecmascript_regex(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft201909Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft202012 = DRAFT202012.to_unittest_testcase(
+ DRAFT202012.cases(),
+ DRAFT201909.optional_cases_of(name="anchor"),
+ DRAFT202012.optional_cases_of(name="bignum"),
+ DRAFT202012.optional_cases_of(name="cross-draft"),
+ DRAFT202012.optional_cases_of(name="float-overflow"),
+ DRAFT202012.optional_cases_of(name="id"),
+ DRAFT202012.optional_cases_of(name="no-schema"),
+ DRAFT202012.optional_cases_of(name="non-bmp-regex"),
+ DRAFT202012.optional_cases_of(name="refOfUnknownKeyword"),
+ DRAFT202012.optional_cases_of(name="unknownKeyword"),
+ Validator=jsonschema.Draft202012Validator,
+ skip=skip(
+ message="Vocabulary support is still in-progress.",
+ subject="vocabulary",
+ description=(
+ "no validation: invalid number, but it still validates"
+ ),
+ ),
+)
+
+
+TestDraft202012Format = DRAFT202012.to_unittest_testcase(
+ DRAFT202012.format_cases(),
+ name="TestDraft202012Format",
+ Validator=jsonschema.Draft202012Validator,
+ format_checker=jsonschema.Draft202012Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ complex_email_validation(test)
+ or ecmascript_regex(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft202012Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_types.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd97b180029ae05d7f3b22f1048f9adcb769f36f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_types.py
@@ -0,0 +1,221 @@
+"""
+Tests for the `TypeChecker`-based type interface.
+
+The actual correctness of the type checking is handled in
+`test_jsonschema_test_suite`; these tests check that TypeChecker
+functions correctly at a more granular level.
+"""
+from collections import namedtuple
+from unittest import TestCase
+
+from jsonschema import ValidationError, _keywords
+from jsonschema._types import TypeChecker
+from jsonschema.exceptions import UndefinedTypeCheck, UnknownType
+from jsonschema.validators import Draft202012Validator, extend
+
+
+def equals_2(checker, instance):
+ return instance == 2
+
+
+def is_namedtuple(instance):
+ return isinstance(instance, tuple) and getattr(instance, "_fields", None)
+
+
+def is_object_or_named_tuple(checker, instance):
+ if Draft202012Validator.TYPE_CHECKER.is_type(instance, "object"):
+ return True
+ return is_namedtuple(instance)
+
+
+class TestTypeChecker(TestCase):
+ def test_is_type(self):
+ checker = TypeChecker({"two": equals_2})
+ self.assertEqual(
+ (
+ checker.is_type(instance=2, type="two"),
+ checker.is_type(instance="bar", type="two"),
+ ),
+ (True, False),
+ )
+
+ def test_is_unknown_type(self):
+ with self.assertRaises(UndefinedTypeCheck) as e:
+ TypeChecker().is_type(4, "foobar")
+ self.assertIn(
+ "'foobar' is unknown to this type checker",
+ str(e.exception),
+ )
+ self.assertTrue(
+ e.exception.__suppress_context__,
+ msg="Expected the internal KeyError to be hidden.",
+ )
+
+ def test_checks_can_be_added_at_init(self):
+ checker = TypeChecker({"two": equals_2})
+ self.assertEqual(checker, TypeChecker().redefine("two", equals_2))
+
+ def test_redefine_existing_type(self):
+ self.assertEqual(
+ TypeChecker().redefine("two", object()).redefine("two", equals_2),
+ TypeChecker().redefine("two", equals_2),
+ )
+
+ def test_remove(self):
+ self.assertEqual(
+ TypeChecker({"two": equals_2}).remove("two"),
+ TypeChecker(),
+ )
+
+ def test_remove_unknown_type(self):
+ with self.assertRaises(UndefinedTypeCheck) as context:
+ TypeChecker().remove("foobar")
+ self.assertIn("foobar", str(context.exception))
+
+ def test_redefine_many(self):
+ self.assertEqual(
+ TypeChecker().redefine_many({"foo": int, "bar": str}),
+ TypeChecker().redefine("foo", int).redefine("bar", str),
+ )
+
+ def test_remove_multiple(self):
+ self.assertEqual(
+ TypeChecker({"foo": int, "bar": str}).remove("foo", "bar"),
+ TypeChecker(),
+ )
+
+ def test_type_check_can_raise_key_error(self):
+ """
+ Make sure no one writes:
+
+ try:
+ self._type_checkers[type](...)
+ except KeyError:
+
+ ignoring the fact that the function itself can raise that.
+ """
+
+ error = KeyError("Stuff")
+
+ def raises_keyerror(checker, instance):
+ raise error
+
+ with self.assertRaises(KeyError) as context:
+ TypeChecker({"foo": raises_keyerror}).is_type(4, "foo")
+
+ self.assertIs(context.exception, error)
+
+ def test_repr(self):
+ checker = TypeChecker({"foo": is_namedtuple, "bar": is_namedtuple})
+ self.assertEqual(repr(checker), "")
+
+
+class TestCustomTypes(TestCase):
+ def test_simple_type_can_be_extended(self):
+ def int_or_str_int(checker, instance):
+ if not isinstance(instance, (int, str)):
+ return False
+ try:
+ int(instance)
+ except ValueError:
+ return False
+ return True
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=Draft202012Validator.TYPE_CHECKER.redefine(
+ "integer", int_or_str_int,
+ ),
+ )
+ validator = CustomValidator({"type": "integer"})
+
+ validator.validate(4)
+ validator.validate("4")
+
+ with self.assertRaises(ValidationError):
+ validator.validate(4.4)
+
+ with self.assertRaises(ValidationError):
+ validator.validate("foo")
+
+ def test_object_can_be_extended(self):
+ schema = {"type": "object"}
+
+ Point = namedtuple("Point", ["x", "y"])
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ )
+ validator = CustomValidator(schema)
+
+ validator.validate(Point(x=4, y=5))
+
+ def test_object_extensions_require_custom_validators(self):
+ schema = {"type": "object", "required": ["x"]}
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ )
+ validator = CustomValidator(schema)
+
+ Point = namedtuple("Point", ["x", "y"])
+ # Cannot handle required
+ with self.assertRaises(ValidationError):
+ validator.validate(Point(x=4, y=5))
+
+ def test_object_extensions_can_handle_custom_validators(self):
+ schema = {
+ "type": "object",
+ "required": ["x"],
+ "properties": {"x": {"type": "integer"}},
+ }
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ def coerce_named_tuple(fn):
+ def coerced(validator, value, instance, schema):
+ if is_namedtuple(instance):
+ instance = instance._asdict()
+ return fn(validator, value, instance, schema)
+ return coerced
+
+ required = coerce_named_tuple(_keywords.required)
+ properties = coerce_named_tuple(_keywords.properties)
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ validators={"required": required, "properties": properties},
+ )
+
+ validator = CustomValidator(schema)
+
+ Point = namedtuple("Point", ["x", "y"])
+ # Can now process required and properties
+ validator.validate(Point(x=4, y=5))
+
+ with self.assertRaises(ValidationError):
+ validator.validate(Point(x="not an integer", y=5))
+
+ # As well as still handle objects.
+ validator.validate({"x": 4, "y": 5})
+
+ with self.assertRaises(ValidationError):
+ validator.validate({"x": "not an integer", "y": 5})
+
+ def test_unknown_type(self):
+ with self.assertRaises(UnknownType) as e:
+ Draft202012Validator({}).is_type(12, "some unknown type")
+ self.assertIn("'some unknown type'", str(e.exception))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_utils.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9764b0f9e92edb38c19e1fc43b248a20186ef6b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_utils.py
@@ -0,0 +1,138 @@
+from math import nan
+from unittest import TestCase
+
+from jsonschema._utils import equal
+
+
+class TestEqual(TestCase):
+ def test_none(self):
+ self.assertTrue(equal(None, None))
+
+ def test_nan(self):
+ self.assertTrue(equal(nan, nan))
+
+
+class TestDictEqual(TestCase):
+ def test_equal_dictionaries(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "b"}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_equal_dictionaries_with_nan(self):
+ dict_1 = {"a": nan, "c": "d"}
+ dict_2 = {"c": "d", "a": nan}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_missing_key(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "x": "b"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_additional_key(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "b", "x": "x"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_missing_value(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "x"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_empty_dictionaries(self):
+ dict_1 = {}
+ dict_2 = {}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_one_none(self):
+ dict_1 = None
+ dict_2 = {"a": "b", "c": "d"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_same_item(self):
+ dict_1 = {"a": "b", "c": "d"}
+ self.assertTrue(equal(dict_1, dict_1))
+
+ def test_nested_equal(self):
+ dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
+ dict_2 = {"c": "d", "a": {"a": "b", "c": "d"}}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_nested_dict_unequal(self):
+ dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
+ dict_2 = {"c": "d", "a": {"a": "b", "c": "x"}}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_mixed_nested_equal(self):
+ dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
+ dict_2 = {"c": "d", "a": ["a", "b", "c", "d"]}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_nested_list_unequal(self):
+ dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
+ dict_2 = {"c": "d", "a": ["b", "c", "d", "a"]}
+ self.assertFalse(equal(dict_1, dict_2))
+
+
+class TestListEqual(TestCase):
+ def test_equal_lists(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["a", "b", "c"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_equal_lists_with_nan(self):
+ list_1 = ["a", nan, "c"]
+ list_2 = ["a", nan, "c"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_unsorted_lists(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["b", "b", "a"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_first_list_larger(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["a", "b"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_second_list_larger(self):
+ list_1 = ["a", "b"]
+ list_2 = ["a", "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_list_with_none_unequal(self):
+ list_1 = ["a", "b", None]
+ list_2 = ["a", "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ list_1 = ["a", "b", None]
+ list_2 = [None, "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_list_with_none_equal(self):
+ list_1 = ["a", None, "c"]
+ list_2 = ["a", None, "c"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_empty_list(self):
+ list_1 = []
+ list_2 = []
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_one_none(self):
+ list_1 = None
+ list_2 = []
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_same_list(self):
+ list_1 = ["a", "b", "c"]
+ self.assertTrue(equal(list_1, list_1))
+
+ def test_equal_nested_lists(self):
+ list_1 = ["a", ["b", "c"], "d"]
+ list_2 = ["a", ["b", "c"], "d"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_unequal_nested_lists(self):
+ list_1 = ["a", ["b", "c"], "d"]
+ list_2 = ["a", [], "c"]
+ self.assertFalse(equal(list_1, list_2))
diff --git a/venv/lib/python3.10/site-packages/jsonschema/tests/test_validators.py b/venv/lib/python3.10/site-packages/jsonschema/tests/test_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..28cc4027372c10df1d071eb656102b3b81bc5ecc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/tests/test_validators.py
@@ -0,0 +1,2575 @@
+from __future__ import annotations
+
+from collections import deque, namedtuple
+from contextlib import contextmanager
+from decimal import Decimal
+from io import BytesIO
+from typing import Any
+from unittest import TestCase, mock
+from urllib.request import pathname2url
+import json
+import os
+import sys
+import tempfile
+import warnings
+
+from attrs import define, field
+from referencing.jsonschema import DRAFT202012
+import referencing.exceptions
+
+from jsonschema import (
+ FormatChecker,
+ TypeChecker,
+ exceptions,
+ protocols,
+ validators,
+)
+
+
+def fail(validator, errors, instance, schema):
+ for each in errors:
+ each.setdefault("message", "You told me to fail!")
+ yield exceptions.ValidationError(**each)
+
+
+class TestCreateAndExtend(TestCase):
+ def setUp(self):
+ self.addCleanup(
+ self.assertEqual,
+ validators._META_SCHEMAS,
+ dict(validators._META_SCHEMAS),
+ )
+ self.addCleanup(
+ self.assertEqual,
+ validators._VALIDATORS,
+ dict(validators._VALIDATORS),
+ )
+
+ self.meta_schema = {"$id": "some://meta/schema"}
+ self.validators = {"fail": fail}
+ self.type_checker = TypeChecker()
+ self.Validator = validators.create(
+ meta_schema=self.meta_schema,
+ validators=self.validators,
+ type_checker=self.type_checker,
+ )
+
+ def test_attrs(self):
+ self.assertEqual(
+ (
+ self.Validator.VALIDATORS,
+ self.Validator.META_SCHEMA,
+ self.Validator.TYPE_CHECKER,
+ ), (
+ self.validators,
+ self.meta_schema,
+ self.type_checker,
+ ),
+ )
+
+ def test_init(self):
+ schema = {"fail": []}
+ self.assertEqual(self.Validator(schema).schema, schema)
+
+ def test_iter_errors_successful(self):
+ schema = {"fail": []}
+ validator = self.Validator(schema)
+
+ errors = list(validator.iter_errors("hello"))
+ self.assertEqual(errors, [])
+
+ def test_iter_errors_one_error(self):
+ schema = {"fail": [{"message": "Whoops!"}]}
+ validator = self.Validator(schema)
+
+ expected_error = exceptions.ValidationError(
+ "Whoops!",
+ instance="goodbye",
+ schema=schema,
+ validator="fail",
+ validator_value=[{"message": "Whoops!"}],
+ schema_path=deque(["fail"]),
+ )
+
+ errors = list(validator.iter_errors("goodbye"))
+ self.assertEqual(len(errors), 1)
+ self.assertEqual(errors[0]._contents(), expected_error._contents())
+
+ def test_iter_errors_multiple_errors(self):
+ schema = {
+ "fail": [
+ {"message": "First"},
+ {"message": "Second!", "validator": "asdf"},
+ {"message": "Third"},
+ ],
+ }
+ validator = self.Validator(schema)
+
+ errors = list(validator.iter_errors("goodbye"))
+ self.assertEqual(len(errors), 3)
+
+ def test_if_a_version_is_provided_it_is_registered(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.addCleanup(validators._VALIDATORS.pop, "my version")
+ self.assertEqual(Validator.__name__, "MyVersionValidator")
+ self.assertEqual(Validator.__qualname__, "MyVersionValidator")
+
+ def test_repr(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.addCleanup(validators._VALIDATORS.pop, "my version")
+ self.assertEqual(
+ repr(Validator({})),
+ "MyVersionValidator(schema={}, format_checker=None)",
+ )
+
+ def test_long_repr(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.addCleanup(validators._VALIDATORS.pop, "my version")
+ self.assertEqual(
+ repr(Validator({"a": list(range(1000))})), (
+ "MyVersionValidator(schema={'a': [0, 1, 2, 3, 4, 5, ...]}, "
+ "format_checker=None)"
+ ),
+ )
+
+ def test_repr_no_version(self):
+ Validator = validators.create(meta_schema={})
+ self.assertEqual(
+ repr(Validator({})),
+ "Validator(schema={}, format_checker=None)",
+ )
+
+ def test_dashes_are_stripped_from_validator_names(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="foo-bar",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.addCleanup(validators._VALIDATORS.pop, "foo-bar")
+ self.assertEqual(Validator.__qualname__, "FooBarValidator")
+
+ def test_if_a_version_is_not_provided_it_is_not_registered(self):
+ original = dict(validators._META_SCHEMAS)
+ validators.create(meta_schema={"id": "id"})
+ self.assertEqual(validators._META_SCHEMAS, original)
+
+ def test_validates_registers_meta_schema_id(self):
+ meta_schema_key = "meta schema id"
+ my_meta_schema = {"id": meta_schema_key}
+
+ validators.create(
+ meta_schema=my_meta_schema,
+ version="my version",
+ id_of=lambda s: s.get("id", ""),
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
+ self.addCleanup(validators._VALIDATORS.pop, "my version")
+
+ self.assertIn(meta_schema_key, validators._META_SCHEMAS)
+
+ def test_validates_registers_meta_schema_draft6_id(self):
+ meta_schema_key = "meta schema $id"
+ my_meta_schema = {"$id": meta_schema_key}
+
+ validators.create(
+ meta_schema=my_meta_schema,
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
+ self.addCleanup(validators._VALIDATORS.pop, "my version")
+
+ self.assertIn(meta_schema_key, validators._META_SCHEMAS)
+
+ def test_create_default_types(self):
+ Validator = validators.create(meta_schema={}, validators=())
+ self.assertTrue(
+ all(
+ Validator({}).is_type(instance=instance, type=type)
+ for type, instance in [
+ ("array", []),
+ ("boolean", True),
+ ("integer", 12),
+ ("null", None),
+ ("number", 12.0),
+ ("object", {}),
+ ("string", "foo"),
+ ]
+ ),
+ )
+
+ def test_check_schema_with_different_metaschema(self):
+ """
+ One can create a validator class whose metaschema uses a different
+ dialect than itself.
+ """
+
+ NoEmptySchemasValidator = validators.create(
+ meta_schema={
+ "$schema": validators.Draft202012Validator.META_SCHEMA["$id"],
+ "not": {"const": {}},
+ },
+ )
+ NoEmptySchemasValidator.check_schema({"foo": "bar"})
+
+ with self.assertRaises(exceptions.SchemaError):
+ NoEmptySchemasValidator.check_schema({})
+
+ NoEmptySchemasValidator({"foo": "bar"}).validate("foo")
+
+ def test_check_schema_with_different_metaschema_defaults_to_self(self):
+ """
+ A validator whose metaschema doesn't declare $schema defaults to its
+ own validation behavior, not the latest "normal" specification.
+ """
+
+ NoEmptySchemasValidator = validators.create(
+ meta_schema={"fail": [{"message": "Meta schema whoops!"}]},
+ validators={"fail": fail},
+ )
+ with self.assertRaises(exceptions.SchemaError):
+ NoEmptySchemasValidator.check_schema({})
+
+ def test_extend(self):
+ original = dict(self.Validator.VALIDATORS)
+ new = object()
+
+ Extended = validators.extend(
+ self.Validator,
+ validators={"new": new},
+ )
+ self.assertEqual(
+ (
+ Extended.VALIDATORS,
+ Extended.META_SCHEMA,
+ Extended.TYPE_CHECKER,
+ self.Validator.VALIDATORS,
+ ), (
+ dict(original, new=new),
+ self.Validator.META_SCHEMA,
+ self.Validator.TYPE_CHECKER,
+ original,
+ ),
+ )
+
+ def test_extend_idof(self):
+ """
+ Extending a validator preserves its notion of schema IDs.
+ """
+ def id_of(schema):
+ return schema.get("__test__", self.Validator.ID_OF(schema))
+ correct_id = "the://correct/id/"
+ meta_schema = {
+ "$id": "the://wrong/id/",
+ "__test__": correct_id,
+ }
+ Original = validators.create(
+ meta_schema=meta_schema,
+ validators=self.validators,
+ type_checker=self.type_checker,
+ id_of=id_of,
+ )
+ self.assertEqual(Original.ID_OF(Original.META_SCHEMA), correct_id)
+
+ Derived = validators.extend(Original)
+ self.assertEqual(Derived.ID_OF(Derived.META_SCHEMA), correct_id)
+
+ def test_extend_applicable_validators(self):
+ """
+ Extending a validator preserves its notion of applicable validators.
+ """
+
+ schema = {
+ "$defs": {"test": {"type": "number"}},
+ "$ref": "#/$defs/test",
+ "maximum": 1,
+ }
+
+ draft4 = validators.Draft4Validator(schema)
+ self.assertTrue(draft4.is_valid(37)) # as $ref ignores siblings
+
+ Derived = validators.extend(validators.Draft4Validator)
+ self.assertTrue(Derived(schema).is_valid(37))
+
+
+class TestValidationErrorMessages(TestCase):
+ def message_for(self, instance, schema, *args, **kwargs):
+ cls = kwargs.pop("cls", validators._LATEST_VERSION)
+ cls.check_schema(schema)
+ validator = cls(schema, *args, **kwargs)
+ errors = list(validator.iter_errors(instance))
+ self.assertTrue(errors, msg=f"No errors were raised for {instance!r}")
+ self.assertEqual(
+ len(errors),
+ 1,
+ msg=f"Expected exactly one error, found {errors!r}",
+ )
+ return errors[0].message
+
+ def test_single_type_failure(self):
+ message = self.message_for(instance=1, schema={"type": "string"})
+ self.assertEqual(message, "1 is not of type 'string'")
+
+ def test_single_type_list_failure(self):
+ message = self.message_for(instance=1, schema={"type": ["string"]})
+ self.assertEqual(message, "1 is not of type 'string'")
+
+ def test_multiple_type_failure(self):
+ types = "string", "object"
+ message = self.message_for(instance=1, schema={"type": list(types)})
+ self.assertEqual(message, "1 is not of type 'string', 'object'")
+
+ def test_object_with_named_type_failure(self):
+ schema = {"type": [{"name": "Foo", "minimum": 3}]}
+ message = self.message_for(
+ instance=1,
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "1 is not of type 'Foo'")
+
+ def test_minimum(self):
+ message = self.message_for(instance=1, schema={"minimum": 2})
+ self.assertEqual(message, "1 is less than the minimum of 2")
+
+ def test_maximum(self):
+ message = self.message_for(instance=1, schema={"maximum": 0})
+ self.assertEqual(message, "1 is greater than the maximum of 0")
+
+ def test_dependencies_single_element(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: on}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_object_without_title_type_failure_draft3(self):
+ type = {"type": [{"minimum": 3}]}
+ message = self.message_for(
+ instance=1,
+ schema={"type": [type]},
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(
+ message,
+ "1 is not of type {'type': [{'minimum': 3}]}",
+ )
+
+ def test_dependencies_list_draft3(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: [on]}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_dependencies_list_draft7(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: [on]}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft7Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_additionalItems_single_failure(self):
+ message = self.message_for(
+ instance=[2],
+ schema={"items": [], "additionalItems": False},
+ cls=validators.Draft3Validator,
+ )
+ self.assertIn("(2 was unexpected)", message)
+
+ def test_additionalItems_multiple_failures(self):
+ message = self.message_for(
+ instance=[1, 2, 3],
+ schema={"items": [], "additionalItems": False},
+ cls=validators.Draft3Validator,
+ )
+ self.assertIn("(1, 2, 3 were unexpected)", message)
+
+ def test_additionalProperties_single_failure(self):
+ additional = "foo"
+ schema = {"additionalProperties": False}
+ message = self.message_for(instance={additional: 2}, schema=schema)
+ self.assertIn("('foo' was unexpected)", message)
+
+ def test_additionalProperties_multiple_failures(self):
+ schema = {"additionalProperties": False}
+ message = self.message_for(
+ instance=dict.fromkeys(["foo", "bar"]),
+ schema=schema,
+ )
+
+ self.assertIn(repr("foo"), message)
+ self.assertIn(repr("bar"), message)
+ self.assertIn("were unexpected)", message)
+
+ def test_const(self):
+ schema = {"const": 12}
+ message = self.message_for(
+ instance={"foo": "bar"},
+ schema=schema,
+ )
+ self.assertIn("12 was expected", message)
+
+ def test_contains_draft_6(self):
+ schema = {"contains": {"const": 12}}
+ message = self.message_for(
+ instance=[2, {}, []],
+ schema=schema,
+ cls=validators.Draft6Validator,
+ )
+ self.assertEqual(
+ message,
+ "None of [2, {}, []] are valid under the given schema",
+ )
+
+ def test_invalid_format_default_message(self):
+ checker = FormatChecker(formats=())
+ checker.checks("thing")(lambda value: False)
+
+ schema = {"format": "thing"}
+ message = self.message_for(
+ instance="bla",
+ schema=schema,
+ format_checker=checker,
+ )
+
+ self.assertIn(repr("bla"), message)
+ self.assertIn(repr("thing"), message)
+ self.assertIn("is not a", message)
+
+ def test_additionalProperties_false_patternProperties(self):
+ schema = {"type": "object",
+ "additionalProperties": False,
+ "patternProperties": {
+ "^abc$": {"type": "string"},
+ "^def$": {"type": "string"},
+ }}
+ message = self.message_for(
+ instance={"zebra": 123},
+ schema=schema,
+ cls=validators.Draft4Validator,
+ )
+ self.assertEqual(
+ message,
+ "{} does not match any of the regexes: {}, {}".format(
+ repr("zebra"), repr("^abc$"), repr("^def$"),
+ ),
+ )
+ message = self.message_for(
+ instance={"zebra": 123, "fish": 456},
+ schema=schema,
+ cls=validators.Draft4Validator,
+ )
+ self.assertEqual(
+ message,
+ "{}, {} do not match any of the regexes: {}, {}".format(
+ repr("fish"), repr("zebra"), repr("^abc$"), repr("^def$"),
+ ),
+ )
+
+ def test_False_schema(self):
+ message = self.message_for(
+ instance="something",
+ schema=False,
+ )
+ self.assertEqual(message, "False schema does not allow 'something'")
+
+ def test_multipleOf(self):
+ message = self.message_for(
+ instance=3,
+ schema={"multipleOf": 2},
+ )
+ self.assertEqual(message, "3 is not a multiple of 2")
+
+ def test_minItems(self):
+ message = self.message_for(instance=[], schema={"minItems": 2})
+ self.assertEqual(message, "[] is too short")
+
+ def test_maxItems(self):
+ message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 2})
+ self.assertEqual(message, "[1, 2, 3] is too long")
+
+ def test_minItems_1(self):
+ message = self.message_for(instance=[], schema={"minItems": 1})
+ self.assertEqual(message, "[] should be non-empty")
+
+ def test_maxItems_0(self):
+ message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 0})
+ self.assertEqual(message, "[1, 2, 3] is expected to be empty")
+
+ def test_minLength(self):
+ message = self.message_for(
+ instance="",
+ schema={"minLength": 2},
+ )
+ self.assertEqual(message, "'' is too short")
+
+ def test_maxLength(self):
+ message = self.message_for(
+ instance="abc",
+ schema={"maxLength": 2},
+ )
+ self.assertEqual(message, "'abc' is too long")
+
+ def test_minLength_1(self):
+ message = self.message_for(instance="", schema={"minLength": 1})
+ self.assertEqual(message, "'' should be non-empty")
+
+ def test_maxLength_0(self):
+ message = self.message_for(instance="abc", schema={"maxLength": 0})
+ self.assertEqual(message, "'abc' is expected to be empty")
+
+ def test_minProperties(self):
+ message = self.message_for(instance={}, schema={"minProperties": 2})
+ self.assertEqual(message, "{} does not have enough properties")
+
+ def test_maxProperties(self):
+ message = self.message_for(
+ instance={"a": {}, "b": {}, "c": {}},
+ schema={"maxProperties": 2},
+ )
+ self.assertEqual(
+ message,
+ "{'a': {}, 'b': {}, 'c': {}} has too many properties",
+ )
+
+ def test_minProperties_1(self):
+ message = self.message_for(instance={}, schema={"minProperties": 1})
+ self.assertEqual(message, "{} should be non-empty")
+
+ def test_maxProperties_0(self):
+ message = self.message_for(
+ instance={1: 2},
+ schema={"maxProperties": 0},
+ )
+ self.assertEqual(message, "{1: 2} is expected to be empty")
+
+ def test_prefixItems_with_items(self):
+ message = self.message_for(
+ instance=[1, 2, "foo"],
+ schema={"items": False, "prefixItems": [{}, {}]},
+ )
+ self.assertEqual(
+ message,
+ "Expected at most 2 items but found 1 extra: 'foo'",
+ )
+
+ def test_prefixItems_with_multiple_extra_items(self):
+ message = self.message_for(
+ instance=[1, 2, "foo", 5],
+ schema={"items": False, "prefixItems": [{}, {}]},
+ )
+ self.assertEqual(
+ message,
+ "Expected at most 2 items but found 2 extra: ['foo', 5]",
+ )
+
+ def test_pattern(self):
+ message = self.message_for(
+ instance="bbb",
+ schema={"pattern": "^a*$"},
+ )
+ self.assertEqual(message, "'bbb' does not match '^a*$'")
+
+ def test_does_not_contain(self):
+ message = self.message_for(
+ instance=[],
+ schema={"contains": {"type": "string"}},
+ )
+ self.assertEqual(
+ message,
+ "[] does not contain items matching the given schema",
+ )
+
+ def test_contains_too_few(self):
+ message = self.message_for(
+ instance=["foo", 1],
+ schema={"contains": {"type": "string"}, "minContains": 2},
+ )
+ self.assertEqual(
+ message,
+ "Too few items match the given schema "
+ "(expected at least 2 but only 1 matched)",
+ )
+
+ def test_contains_too_few_both_constrained(self):
+ message = self.message_for(
+ instance=["foo", 1],
+ schema={
+ "contains": {"type": "string"},
+ "minContains": 2,
+ "maxContains": 4,
+ },
+ )
+ self.assertEqual(
+ message,
+ "Too few items match the given schema (expected at least 2 but "
+ "only 1 matched)",
+ )
+
+ def test_contains_too_many(self):
+ message = self.message_for(
+ instance=["foo", "bar", "baz"],
+ schema={"contains": {"type": "string"}, "maxContains": 2},
+ )
+ self.assertEqual(
+ message,
+ "Too many items match the given schema (expected at most 2)",
+ )
+
+ def test_contains_too_many_both_constrained(self):
+ message = self.message_for(
+ instance=["foo"] * 5,
+ schema={
+ "contains": {"type": "string"},
+ "minContains": 2,
+ "maxContains": 4,
+ },
+ )
+ self.assertEqual(
+ message,
+ "Too many items match the given schema (expected at most 4)",
+ )
+
+ def test_exclusiveMinimum(self):
+ message = self.message_for(
+ instance=3,
+ schema={"exclusiveMinimum": 5},
+ )
+ self.assertEqual(
+ message,
+ "3 is less than or equal to the minimum of 5",
+ )
+
+ def test_exclusiveMaximum(self):
+ message = self.message_for(instance=3, schema={"exclusiveMaximum": 2})
+ self.assertEqual(
+ message,
+ "3 is greater than or equal to the maximum of 2",
+ )
+
+ def test_required(self):
+ message = self.message_for(instance={}, schema={"required": ["foo"]})
+ self.assertEqual(message, "'foo' is a required property")
+
+ def test_dependentRequired(self):
+ message = self.message_for(
+ instance={"foo": {}},
+ schema={"dependentRequired": {"foo": ["bar"]}},
+ )
+ self.assertEqual(message, "'bar' is a dependency of 'foo'")
+
+ def test_oneOf_matches_none(self):
+ message = self.message_for(instance={}, schema={"oneOf": [False]})
+ self.assertEqual(
+ message,
+ "{} is not valid under any of the given schemas",
+ )
+
+ def test_oneOf_matches_too_many(self):
+ message = self.message_for(instance={}, schema={"oneOf": [True, True]})
+ self.assertEqual(message, "{} is valid under each of True, True")
+
+ def test_unevaluated_items(self):
+ schema = {"type": "array", "unevaluatedItems": False}
+ message = self.message_for(instance=["foo", "bar"], schema=schema)
+ self.assertIn(
+ message,
+ "Unevaluated items are not allowed ('foo', 'bar' were unexpected)",
+ )
+
+ def test_unevaluated_items_on_invalid_type(self):
+ schema = {"type": "array", "unevaluatedItems": False}
+ message = self.message_for(instance="foo", schema=schema)
+ self.assertEqual(message, "'foo' is not of type 'array'")
+
+ def test_unevaluated_properties_invalid_against_subschema(self):
+ schema = {
+ "properties": {"foo": {"type": "string"}},
+ "unevaluatedProperties": {"const": 12},
+ }
+ message = self.message_for(
+ instance={
+ "foo": "foo",
+ "bar": "bar",
+ "baz": 12,
+ },
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated properties are not valid under the given schema "
+ "('bar' was unevaluated and invalid)",
+ )
+
+ def test_unevaluated_properties_disallowed(self):
+ schema = {"type": "object", "unevaluatedProperties": False}
+ message = self.message_for(
+ instance={
+ "foo": "foo",
+ "bar": "bar",
+ },
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated properties are not allowed "
+ "('bar', 'foo' were unexpected)",
+ )
+
+ def test_unevaluated_properties_on_invalid_type(self):
+ schema = {"type": "object", "unevaluatedProperties": False}
+ message = self.message_for(instance="foo", schema=schema)
+ self.assertEqual(message, "'foo' is not of type 'object'")
+
+ def test_single_item(self):
+ schema = {"prefixItems": [{}], "items": False}
+ message = self.message_for(
+ instance=["foo", "bar", "baz"],
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Expected at most 1 item but found 2 extra: ['bar', 'baz']",
+ )
+
+ def test_heterogeneous_additionalItems_with_Items(self):
+ schema = {"items": [{}], "additionalItems": False}
+ message = self.message_for(
+ instance=["foo", "bar", 37],
+ schema=schema,
+ cls=validators.Draft7Validator,
+ )
+ self.assertEqual(
+ message,
+ "Additional items are not allowed ('bar', 37 were unexpected)",
+ )
+
+ def test_heterogeneous_items_prefixItems(self):
+ schema = {"prefixItems": [{}], "items": False}
+ message = self.message_for(
+ instance=["foo", "bar", 37],
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Expected at most 1 item but found 2 extra: ['bar', 37]",
+ )
+
+ def test_heterogeneous_unevaluatedItems_prefixItems(self):
+ schema = {"prefixItems": [{}], "unevaluatedItems": False}
+ message = self.message_for(
+ instance=["foo", "bar", 37],
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated items are not allowed ('bar', 37 were unexpected)",
+ )
+
+ def test_heterogeneous_properties_additionalProperties(self):
+ """
+ Not valid deserialized JSON, but this should not blow up.
+ """
+ schema = {"properties": {"foo": {}}, "additionalProperties": False}
+ message = self.message_for(
+ instance={"foo": {}, "a": "baz", 37: 12},
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Additional properties are not allowed (37, 'a' were unexpected)",
+ )
+
+ def test_heterogeneous_properties_unevaluatedProperties(self):
+ """
+ Not valid deserialized JSON, but this should not blow up.
+ """
+ schema = {"properties": {"foo": {}}, "unevaluatedProperties": False}
+ message = self.message_for(
+ instance={"foo": {}, "a": "baz", 37: 12},
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated properties are not allowed (37, 'a' were unexpected)",
+ )
+
+
+class TestValidationErrorDetails(TestCase):
+ # TODO: These really need unit tests for each individual keyword, rather
+ # than just these higher level tests.
+ def test_anyOf(self):
+ instance = 5
+ schema = {
+ "anyOf": [
+ {"minimum": 20},
+ {"type": "string"},
+ ],
+ }
+
+ validator = validators.Draft4Validator(schema)
+ errors = list(validator.iter_errors(instance))
+ self.assertEqual(len(errors), 1)
+ e = errors[0]
+
+ self.assertEqual(e.validator, "anyOf")
+ self.assertEqual(e.validator_value, schema["anyOf"])
+ self.assertEqual(e.instance, instance)
+ self.assertEqual(e.schema, schema)
+ self.assertIsNone(e.parent)
+
+ self.assertEqual(e.path, deque([]))
+ self.assertEqual(e.relative_path, deque([]))
+ self.assertEqual(e.absolute_path, deque([]))
+ self.assertEqual(e.json_path, "$")
+
+ self.assertEqual(e.schema_path, deque(["anyOf"]))
+ self.assertEqual(e.relative_schema_path, deque(["anyOf"]))
+ self.assertEqual(e.absolute_schema_path, deque(["anyOf"]))
+
+ self.assertEqual(len(e.context), 2)
+
+ e1, e2 = sorted_errors(e.context)
+
+ self.assertEqual(e1.validator, "minimum")
+ self.assertEqual(e1.validator_value, schema["anyOf"][0]["minimum"])
+ self.assertEqual(e1.instance, instance)
+ self.assertEqual(e1.schema, schema["anyOf"][0])
+ self.assertIs(e1.parent, e)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e1.absolute_path, deque([]))
+ self.assertEqual(e1.relative_path, deque([]))
+ self.assertEqual(e1.json_path, "$")
+
+ self.assertEqual(e1.schema_path, deque([0, "minimum"]))
+ self.assertEqual(e1.relative_schema_path, deque([0, "minimum"]))
+ self.assertEqual(
+ e1.absolute_schema_path, deque(["anyOf", 0, "minimum"]),
+ )
+
+ self.assertFalse(e1.context)
+
+ self.assertEqual(e2.validator, "type")
+ self.assertEqual(e2.validator_value, schema["anyOf"][1]["type"])
+ self.assertEqual(e2.instance, instance)
+ self.assertEqual(e2.schema, schema["anyOf"][1])
+ self.assertIs(e2.parent, e)
+
+ self.assertEqual(e2.path, deque([]))
+ self.assertEqual(e2.relative_path, deque([]))
+ self.assertEqual(e2.absolute_path, deque([]))
+ self.assertEqual(e2.json_path, "$")
+
+ self.assertEqual(e2.schema_path, deque([1, "type"]))
+ self.assertEqual(e2.relative_schema_path, deque([1, "type"]))
+ self.assertEqual(e2.absolute_schema_path, deque(["anyOf", 1, "type"]))
+
+ self.assertEqual(len(e2.context), 0)
+
+ def test_type(self):
+ instance = {"foo": 1}
+ schema = {
+ "type": [
+ {"type": "integer"},
+ {
+ "type": "object",
+ "properties": {"foo": {"enum": [2]}},
+ },
+ ],
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = list(validator.iter_errors(instance))
+ self.assertEqual(len(errors), 1)
+ e = errors[0]
+
+ self.assertEqual(e.validator, "type")
+ self.assertEqual(e.validator_value, schema["type"])
+ self.assertEqual(e.instance, instance)
+ self.assertEqual(e.schema, schema)
+ self.assertIsNone(e.parent)
+
+ self.assertEqual(e.path, deque([]))
+ self.assertEqual(e.relative_path, deque([]))
+ self.assertEqual(e.absolute_path, deque([]))
+ self.assertEqual(e.json_path, "$")
+
+ self.assertEqual(e.schema_path, deque(["type"]))
+ self.assertEqual(e.relative_schema_path, deque(["type"]))
+ self.assertEqual(e.absolute_schema_path, deque(["type"]))
+
+ self.assertEqual(len(e.context), 2)
+
+ e1, e2 = sorted_errors(e.context)
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e1.validator_value, schema["type"][0]["type"])
+ self.assertEqual(e1.instance, instance)
+ self.assertEqual(e1.schema, schema["type"][0])
+ self.assertIs(e1.parent, e)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e1.relative_path, deque([]))
+ self.assertEqual(e1.absolute_path, deque([]))
+ self.assertEqual(e1.json_path, "$")
+
+ self.assertEqual(e1.schema_path, deque([0, "type"]))
+ self.assertEqual(e1.relative_schema_path, deque([0, "type"]))
+ self.assertEqual(e1.absolute_schema_path, deque(["type", 0, "type"]))
+
+ self.assertFalse(e1.context)
+
+ self.assertEqual(e2.validator, "enum")
+ self.assertEqual(e2.validator_value, [2])
+ self.assertEqual(e2.instance, 1)
+ self.assertEqual(e2.schema, {"enum": [2]})
+ self.assertIs(e2.parent, e)
+
+ self.assertEqual(e2.path, deque(["foo"]))
+ self.assertEqual(e2.relative_path, deque(["foo"]))
+ self.assertEqual(e2.absolute_path, deque(["foo"]))
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(
+ e2.schema_path, deque([1, "properties", "foo", "enum"]),
+ )
+ self.assertEqual(
+ e2.relative_schema_path, deque([1, "properties", "foo", "enum"]),
+ )
+ self.assertEqual(
+ e2.absolute_schema_path,
+ deque(["type", 1, "properties", "foo", "enum"]),
+ )
+
+ self.assertFalse(e2.context)
+
+ def test_single_nesting(self):
+ instance = {"foo": 2, "bar": [1], "baz": 15, "quux": "spam"}
+ schema = {
+ "properties": {
+ "foo": {"type": "string"},
+ "bar": {"minItems": 2},
+ "baz": {"maximum": 10, "enum": [2, 4, 6, 8]},
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2, e3, e4 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["baz"]))
+ self.assertEqual(e3.path, deque(["baz"]))
+ self.assertEqual(e4.path, deque(["foo"]))
+
+ self.assertEqual(e1.relative_path, deque(["bar"]))
+ self.assertEqual(e2.relative_path, deque(["baz"]))
+ self.assertEqual(e3.relative_path, deque(["baz"]))
+ self.assertEqual(e4.relative_path, deque(["foo"]))
+
+ self.assertEqual(e1.absolute_path, deque(["bar"]))
+ self.assertEqual(e2.absolute_path, deque(["baz"]))
+ self.assertEqual(e3.absolute_path, deque(["baz"]))
+ self.assertEqual(e4.absolute_path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.baz")
+ self.assertEqual(e3.json_path, "$.baz")
+ self.assertEqual(e4.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "minItems")
+ self.assertEqual(e2.validator, "enum")
+ self.assertEqual(e3.validator, "maximum")
+ self.assertEqual(e4.validator, "type")
+
+ def test_multiple_nesting(self):
+ instance = [1, {"foo": 2, "bar": {"baz": [1]}}, "quux"]
+ schema = {
+ "type": "string",
+ "items": {
+ "type": ["string", "object"],
+ "properties": {
+ "foo": {"enum": [1, 3]},
+ "bar": {
+ "type": "array",
+ "properties": {
+ "bar": {"required": True},
+ "baz": {"minItems": 2},
+ },
+ },
+ },
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2, e3, e4, e5, e6 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e2.path, deque([0]))
+ self.assertEqual(e3.path, deque([1, "bar"]))
+ self.assertEqual(e4.path, deque([1, "bar", "bar"]))
+ self.assertEqual(e5.path, deque([1, "bar", "baz"]))
+ self.assertEqual(e6.path, deque([1, "foo"]))
+
+ self.assertEqual(e1.json_path, "$")
+ self.assertEqual(e2.json_path, "$[0]")
+ self.assertEqual(e3.json_path, "$[1].bar")
+ self.assertEqual(e4.json_path, "$[1].bar.bar")
+ self.assertEqual(e5.json_path, "$[1].bar.baz")
+ self.assertEqual(e6.json_path, "$[1].foo")
+
+ self.assertEqual(e1.schema_path, deque(["type"]))
+ self.assertEqual(e2.schema_path, deque(["items", "type"]))
+ self.assertEqual(
+ list(e3.schema_path), ["items", "properties", "bar", "type"],
+ )
+ self.assertEqual(
+ list(e4.schema_path),
+ ["items", "properties", "bar", "properties", "bar", "required"],
+ )
+ self.assertEqual(
+ list(e5.schema_path),
+ ["items", "properties", "bar", "properties", "baz", "minItems"],
+ )
+ self.assertEqual(
+ list(e6.schema_path), ["items", "properties", "foo", "enum"],
+ )
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "type")
+ self.assertEqual(e3.validator, "type")
+ self.assertEqual(e4.validator, "required")
+ self.assertEqual(e5.validator, "minItems")
+ self.assertEqual(e6.validator, "enum")
+
+ def test_recursive(self):
+ schema = {
+ "definitions": {
+ "node": {
+ "anyOf": [{
+ "type": "object",
+ "required": ["name", "children"],
+ "properties": {
+ "name": {
+ "type": "string",
+ },
+ "children": {
+ "type": "object",
+ "patternProperties": {
+ "^.*$": {
+ "$ref": "#/definitions/node",
+ },
+ },
+ },
+ },
+ }],
+ },
+ },
+ "type": "object",
+ "required": ["root"],
+ "properties": {"root": {"$ref": "#/definitions/node"}},
+ }
+
+ instance = {
+ "root": {
+ "name": "root",
+ "children": {
+ "a": {
+ "name": "a",
+ "children": {
+ "ab": {
+ "name": "ab",
+ # missing "children"
+ },
+ },
+ },
+ },
+ },
+ }
+ validator = validators.Draft4Validator(schema)
+
+ e, = validator.iter_errors(instance)
+ self.assertEqual(e.absolute_path, deque(["root"]))
+ self.assertEqual(
+ e.absolute_schema_path, deque(["properties", "root", "anyOf"]),
+ )
+ self.assertEqual(e.json_path, "$.root")
+
+ e1, = e.context
+ self.assertEqual(e1.absolute_path, deque(["root", "children", "a"]))
+ self.assertEqual(
+ e1.absolute_schema_path, deque(
+ [
+ "properties",
+ "root",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ ],
+ ),
+ )
+ self.assertEqual(e1.json_path, "$.root.children.a")
+
+ e2, = e1.context
+ self.assertEqual(
+ e2.absolute_path, deque(
+ ["root", "children", "a", "children", "ab"],
+ ),
+ )
+ self.assertEqual(
+ e2.absolute_schema_path, deque(
+ [
+ "properties",
+ "root",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ ],
+ ),
+ )
+ self.assertEqual(e2.json_path, "$.root.children.a.children.ab")
+
+ def test_additionalProperties(self):
+ instance = {"bar": "bar", "foo": 2}
+ schema = {"additionalProperties": {"type": "integer", "minimum": 5}}
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_patternProperties(self):
+ instance = {"bar": 1, "foo": 2}
+ schema = {
+ "patternProperties": {
+ "bar": {"type": "string"},
+ "foo": {"minimum": 5},
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_additionalItems(self):
+ instance = ["foo", 1]
+ schema = {
+ "items": [],
+ "additionalItems": {"type": "integer", "minimum": 5},
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([0]))
+ self.assertEqual(e2.path, deque([1]))
+
+ self.assertEqual(e1.json_path, "$[0]")
+ self.assertEqual(e2.json_path, "$[1]")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_additionalItems_with_items(self):
+ instance = ["foo", "bar", 1]
+ schema = {
+ "items": [{}],
+ "additionalItems": {"type": "integer", "minimum": 5},
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([1]))
+ self.assertEqual(e2.path, deque([2]))
+
+ self.assertEqual(e1.json_path, "$[1]")
+ self.assertEqual(e2.json_path, "$[2]")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_propertyNames(self):
+ instance = {"foo": 12}
+ schema = {"propertyNames": {"not": {"const": "foo"}}}
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(instance)
+
+ self.assertEqual(error.validator, "not")
+ self.assertEqual(
+ error.message,
+ "'foo' should not be valid under {'const': 'foo'}",
+ )
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["propertyNames", "not"]))
+
+ def test_if_then(self):
+ schema = {
+ "if": {"const": 12},
+ "then": {"const": 13},
+ }
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(12)
+
+ self.assertEqual(error.validator, "const")
+ self.assertEqual(error.message, "13 was expected")
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["then", "const"]))
+
+ def test_if_else(self):
+ schema = {
+ "if": {"const": 12},
+ "else": {"const": 13},
+ }
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(15)
+
+ self.assertEqual(error.validator, "const")
+ self.assertEqual(error.message, "13 was expected")
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["else", "const"]))
+
+ def test_boolean_schema_False(self):
+ validator = validators.Draft7Validator(False)
+ error, = validator.iter_errors(12)
+
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "False schema does not allow 12",
+ None,
+ None,
+ 12,
+ False,
+ deque([]),
+ "$",
+ ),
+ )
+
+ def test_ref(self):
+ ref, schema = "someRef", {"additionalProperties": {"type": "integer"}}
+ validator = validators.Draft7Validator(
+ {"$ref": ref},
+ resolver=validators._RefResolver("", {}, store={ref: schema}),
+ )
+ error, = validator.iter_errors({"foo": "notAnInteger"})
+
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "'notAnInteger' is not of type 'integer'",
+ "type",
+ "integer",
+ "notAnInteger",
+ deque(["foo"]),
+ {"type": "integer"},
+ deque(["additionalProperties", "type"]),
+ "$.foo",
+ ),
+ )
+
+ def test_prefixItems(self):
+ schema = {"prefixItems": [{"type": "string"}, {}, {}, {"maximum": 3}]}
+ validator = validators.Draft202012Validator(schema)
+ type_error, min_error = validator.iter_errors([1, 2, "foo", 5])
+ self.assertEqual(
+ (
+ type_error.message,
+ type_error.validator,
+ type_error.validator_value,
+ type_error.instance,
+ type_error.absolute_path,
+ type_error.schema,
+ type_error.schema_path,
+ type_error.json_path,
+ ),
+ (
+ "1 is not of type 'string'",
+ "type",
+ "string",
+ 1,
+ deque([0]),
+ {"type": "string"},
+ deque(["prefixItems", 0, "type"]),
+ "$[0]",
+ ),
+ )
+ self.assertEqual(
+ (
+ min_error.message,
+ min_error.validator,
+ min_error.validator_value,
+ min_error.instance,
+ min_error.absolute_path,
+ min_error.schema,
+ min_error.schema_path,
+ min_error.json_path,
+ ),
+ (
+ "5 is greater than the maximum of 3",
+ "maximum",
+ 3,
+ 5,
+ deque([3]),
+ {"maximum": 3},
+ deque(["prefixItems", 3, "maximum"]),
+ "$[3]",
+ ),
+ )
+
+ def test_prefixItems_with_items(self):
+ schema = {
+ "items": {"type": "string"},
+ "prefixItems": [{}],
+ }
+ validator = validators.Draft202012Validator(schema)
+ e1, e2 = validator.iter_errors(["foo", 2, "bar", 4, "baz"])
+ self.assertEqual(
+ (
+ e1.message,
+ e1.validator,
+ e1.validator_value,
+ e1.instance,
+ e1.absolute_path,
+ e1.schema,
+ e1.schema_path,
+ e1.json_path,
+ ),
+ (
+ "2 is not of type 'string'",
+ "type",
+ "string",
+ 2,
+ deque([1]),
+ {"type": "string"},
+ deque(["items", "type"]),
+ "$[1]",
+ ),
+ )
+ self.assertEqual(
+ (
+ e2.message,
+ e2.validator,
+ e2.validator_value,
+ e2.instance,
+ e2.absolute_path,
+ e2.schema,
+ e2.schema_path,
+ e2.json_path,
+ ),
+ (
+ "4 is not of type 'string'",
+ "type",
+ "string",
+ 4,
+ deque([3]),
+ {"type": "string"},
+ deque(["items", "type"]),
+ "$[3]",
+ ),
+ )
+
+ def test_contains_too_many(self):
+ """
+ `contains` + `maxContains` produces only one error, even if there are
+ many more incorrectly matching elements.
+ """
+ schema = {"contains": {"type": "string"}, "maxContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors(["foo", 2, "bar", 4, "baz", "quux"])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "Too many items match the given schema (expected at most 2)",
+ "maxContains",
+ 2,
+ ["foo", 2, "bar", 4, "baz", "quux"],
+ deque([]),
+ {"contains": {"type": "string"}, "maxContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_contains_too_few(self):
+ schema = {"contains": {"type": "string"}, "minContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors(["foo", 2, 4])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ (
+ "Too few items match the given schema "
+ "(expected at least 2 but only 1 matched)"
+ ),
+ "minContains",
+ 2,
+ ["foo", 2, 4],
+ deque([]),
+ {"contains": {"type": "string"}, "minContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_contains_none(self):
+ schema = {"contains": {"type": "string"}, "minContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors([2, 4])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "[2, 4] does not contain items matching the given schema",
+ "contains",
+ {"type": "string"},
+ [2, 4],
+ deque([]),
+ {"contains": {"type": "string"}, "minContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_ref_sibling(self):
+ schema = {
+ "$defs": {"foo": {"required": ["bar"]}},
+ "properties": {
+ "aprop": {
+ "$ref": "#/$defs/foo",
+ "required": ["baz"],
+ },
+ },
+ }
+
+ validator = validators.Draft202012Validator(schema)
+ e1, e2 = validator.iter_errors({"aprop": {}})
+ self.assertEqual(
+ (
+ e1.message,
+ e1.validator,
+ e1.validator_value,
+ e1.instance,
+ e1.absolute_path,
+ e1.schema,
+ e1.schema_path,
+ e1.relative_schema_path,
+ e1.json_path,
+ ),
+ (
+ "'bar' is a required property",
+ "required",
+ ["bar"],
+ {},
+ deque(["aprop"]),
+ {"required": ["bar"]},
+ deque(["properties", "aprop", "required"]),
+ deque(["properties", "aprop", "required"]),
+ "$.aprop",
+ ),
+ )
+ self.assertEqual(
+ (
+ e2.message,
+ e2.validator,
+ e2.validator_value,
+ e2.instance,
+ e2.absolute_path,
+ e2.schema,
+ e2.schema_path,
+ e2.relative_schema_path,
+ e2.json_path,
+ ),
+ (
+ "'baz' is a required property",
+ "required",
+ ["baz"],
+ {},
+ deque(["aprop"]),
+ {"$ref": "#/$defs/foo", "required": ["baz"]},
+ deque(["properties", "aprop", "required"]),
+ deque(["properties", "aprop", "required"]),
+ "$.aprop",
+ ),
+ )
+
+
+class MetaSchemaTestsMixin:
+ # TODO: These all belong upstream
+ def test_invalid_properties(self):
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"properties": 12})
+
+ def test_minItems_invalid_string(self):
+ with self.assertRaises(exceptions.SchemaError):
+ # needs to be an integer
+ self.Validator.check_schema({"minItems": "1"})
+
+ def test_enum_allows_empty_arrays(self):
+ """
+ Technically, all the spec says is they SHOULD have elements, not MUST.
+
+ (As of Draft 6. Previous drafts do say MUST).
+
+ See #529.
+ """
+ if self.Validator in {
+ validators.Draft3Validator,
+ validators.Draft4Validator,
+ }:
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"enum": []})
+ else:
+ self.Validator.check_schema({"enum": []})
+
+ def test_enum_allows_non_unique_items(self):
+ """
+ Technically, all the spec says is they SHOULD be unique, not MUST.
+
+ (As of Draft 6. Previous drafts do say MUST).
+
+ See #529.
+ """
+ if self.Validator in {
+ validators.Draft3Validator,
+ validators.Draft4Validator,
+ }:
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"enum": [12, 12]})
+ else:
+ self.Validator.check_schema({"enum": [12, 12]})
+
+ def test_schema_with_invalid_regex(self):
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"pattern": "*notaregex"})
+
+ def test_schema_with_invalid_regex_with_disabled_format_validation(self):
+ self.Validator.check_schema(
+ {"pattern": "*notaregex"},
+ format_checker=None,
+ )
+
+
+class ValidatorTestMixin(MetaSchemaTestsMixin):
+ def test_it_implements_the_validator_protocol(self):
+ self.assertIsInstance(self.Validator({}), protocols.Validator)
+
+ def test_valid_instances_are_valid(self):
+ schema, instance = self.valid
+ self.assertTrue(self.Validator(schema).is_valid(instance))
+
+ def test_invalid_instances_are_not_valid(self):
+ schema, instance = self.invalid
+ self.assertFalse(self.Validator(schema).is_valid(instance))
+
+ def test_non_existent_properties_are_ignored(self):
+ self.Validator({object(): object()}).validate(instance=object())
+
+ def test_evolve(self):
+ schema, format_checker = {"type": "integer"}, FormatChecker()
+ original = self.Validator(
+ schema,
+ format_checker=format_checker,
+ )
+ new = original.evolve(
+ schema={"type": "string"},
+ format_checker=self.Validator.FORMAT_CHECKER,
+ )
+
+ expected = self.Validator(
+ {"type": "string"},
+ format_checker=self.Validator.FORMAT_CHECKER,
+ _resolver=new._resolver,
+ )
+
+ self.assertEqual(new, expected)
+ self.assertNotEqual(new, original)
+
+ def test_evolve_with_subclass(self):
+ """
+ Subclassing validators isn't supported public API, but some users have
+ done it, because we don't actually error entirely when it's done :/
+
+ We need to deprecate doing so first to help as many of these users
+ ensure they can move to supported APIs, but this test ensures that in
+ the interim, we haven't broken those users.
+ """
+
+ with self.assertWarns(DeprecationWarning):
+ @define
+ class OhNo(self.Validator):
+ foo = field(factory=lambda: [1, 2, 3])
+ _bar = field(default=37)
+
+ validator = OhNo({}, bar=12)
+ self.assertEqual(validator.foo, [1, 2, 3])
+
+ new = validator.evolve(schema={"type": "integer"})
+ self.assertEqual(new.foo, [1, 2, 3])
+ self.assertEqual(new._bar, 12)
+
+ def test_is_type_is_true_for_valid_type(self):
+ self.assertTrue(self.Validator({}).is_type("foo", "string"))
+
+ def test_is_type_is_false_for_invalid_type(self):
+ self.assertFalse(self.Validator({}).is_type("foo", "array"))
+
+ def test_is_type_evades_bool_inheriting_from_int(self):
+ self.assertFalse(self.Validator({}).is_type(True, "integer"))
+ self.assertFalse(self.Validator({}).is_type(True, "number"))
+
+ def test_it_can_validate_with_decimals(self):
+ schema = {"items": {"type": "number"}}
+ Validator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "number",
+ lambda checker, thing: isinstance(
+ thing, (int, float, Decimal),
+ ) and not isinstance(thing, bool),
+ ),
+ )
+
+ validator = Validator(schema)
+ validator.validate([1, 1.1, Decimal(1) / Decimal(8)])
+
+ invalid = ["foo", {}, [], True, None]
+ self.assertEqual(
+ [error.instance for error in validator.iter_errors(invalid)],
+ invalid,
+ )
+
+ def test_it_returns_true_for_formats_it_does_not_know_about(self):
+ validator = self.Validator(
+ {"format": "carrot"}, format_checker=FormatChecker(),
+ )
+ validator.validate("bugs")
+
+ def test_it_does_not_validate_formats_by_default(self):
+ validator = self.Validator({})
+ self.assertIsNone(validator.format_checker)
+
+ def test_it_validates_formats_if_a_checker_is_provided(self):
+ checker = FormatChecker()
+ bad = ValueError("Bad!")
+
+ @checker.checks("foo", raises=ValueError)
+ def check(value):
+ if value == "good":
+ return True
+ elif value == "bad":
+ raise bad
+ else: # pragma: no cover
+ self.fail(f"What is {value}? [Baby Don't Hurt Me]")
+
+ validator = self.Validator(
+ {"format": "foo"}, format_checker=checker,
+ )
+
+ validator.validate("good")
+ with self.assertRaises(exceptions.ValidationError) as cm:
+ validator.validate("bad")
+
+ # Make sure original cause is attached
+ self.assertIs(cm.exception.cause, bad)
+
+ def test_non_string_custom_type(self):
+ non_string_type = object()
+ schema = {"type": [non_string_type]}
+ Crazy = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ non_string_type,
+ lambda checker, thing: isinstance(thing, int),
+ ),
+ )
+ Crazy(schema).validate(15)
+
+ def test_it_properly_formats_tuples_in_errors(self):
+ """
+ A tuple instance properly formats validation errors for uniqueItems.
+
+ See #224
+ """
+ TupleValidator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "array",
+ lambda checker, thing: isinstance(thing, tuple),
+ ),
+ )
+ with self.assertRaises(exceptions.ValidationError) as e:
+ TupleValidator({"uniqueItems": True}).validate((1, 1))
+ self.assertIn("(1, 1) has non-unique elements", str(e.exception))
+
+ def test_check_redefined_sequence(self):
+ """
+ Allow array to validate against another defined sequence type
+ """
+ schema = {"type": "array", "uniqueItems": True}
+ MyMapping = namedtuple("MyMapping", "a, b")
+ Validator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine_many(
+ {
+ "array": lambda checker, thing: isinstance(
+ thing, (list, deque),
+ ),
+ "object": lambda checker, thing: isinstance(
+ thing, (dict, MyMapping),
+ ),
+ },
+ ),
+ )
+ validator = Validator(schema)
+
+ valid_instances = [
+ deque(["a", None, "1", "", True]),
+ deque([[False], [0]]),
+ [deque([False]), deque([0])],
+ [[deque([False])], [deque([0])]],
+ [[[[[deque([False])]]]], [[[[deque([0])]]]]],
+ [deque([deque([False])]), deque([deque([0])])],
+ [MyMapping("a", 0), MyMapping("a", False)],
+ [
+ MyMapping("a", [deque([0])]),
+ MyMapping("a", [deque([False])]),
+ ],
+ [
+ MyMapping("a", [MyMapping("a", deque([0]))]),
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ ],
+ [deque(deque(deque([False]))), deque(deque(deque([0])))],
+ ]
+
+ for instance in valid_instances:
+ validator.validate(instance)
+
+ invalid_instances = [
+ deque(["a", "b", "a"]),
+ deque([[False], [False]]),
+ [deque([False]), deque([False])],
+ [[deque([False])], [deque([False])]],
+ [[[[[deque([False])]]]], [[[[deque([False])]]]]],
+ [deque([deque([False])]), deque([deque([False])])],
+ [MyMapping("a", False), MyMapping("a", False)],
+ [
+ MyMapping("a", [deque([False])]),
+ MyMapping("a", [deque([False])]),
+ ],
+ [
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ ],
+ [deque(deque(deque([False]))), deque(deque(deque([False])))],
+ ]
+
+ for instance in invalid_instances:
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(instance)
+
+ def test_it_creates_a_ref_resolver_if_not_provided(self):
+ with self.assertWarns(DeprecationWarning):
+ resolver = self.Validator({}).resolver
+ self.assertIsInstance(resolver, validators._RefResolver)
+
+ def test_it_upconverts_from_deprecated_RefResolvers(self):
+ ref, schema = "someCoolRef", {"type": "integer"}
+ resolver = validators._RefResolver("", {}, store={ref: schema})
+ validator = self.Validator({"$ref": ref}, resolver=resolver)
+
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(None)
+
+ def test_it_upconverts_from_yet_older_deprecated_legacy_RefResolvers(self):
+ """
+ Legacy RefResolvers support only the context manager form of
+ resolution.
+ """
+
+ class LegacyRefResolver:
+ @contextmanager
+ def resolving(this, ref):
+ self.assertEqual(ref, "the ref")
+ yield {"type": "integer"}
+
+ resolver = LegacyRefResolver()
+ schema = {"$ref": "the ref"}
+
+ with self.assertRaises(exceptions.ValidationError):
+ self.Validator(schema, resolver=resolver).validate(None)
+
+
+class AntiDraft6LeakMixin:
+ """
+ Make sure functionality from draft 6 doesn't leak backwards in time.
+ """
+
+ def test_True_is_not_a_schema(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ self.Validator.check_schema(True)
+ self.assertIn("True is not of type", str(e.exception))
+
+ def test_False_is_not_a_schema(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ self.Validator.check_schema(False)
+ self.assertIn("False is not of type", str(e.exception))
+
+ def test_True_is_not_a_schema_even_if_you_forget_to_check(self):
+ with self.assertRaises(Exception) as e:
+ self.Validator(True).validate(12)
+ self.assertNotIsInstance(e.exception, exceptions.ValidationError)
+
+ def test_False_is_not_a_schema_even_if_you_forget_to_check(self):
+ with self.assertRaises(Exception) as e:
+ self.Validator(False).validate(12)
+ self.assertNotIsInstance(e.exception, exceptions.ValidationError)
+
+
+class TestDraft3Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
+ Validator = validators.Draft3Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+ def test_any_type_is_valid_for_type_any(self):
+ validator = self.Validator({"type": "any"})
+ validator.validate(object())
+
+ def test_any_type_is_redefinable(self):
+ """
+ Sigh, because why not.
+ """
+ Crazy = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "any", lambda checker, thing: isinstance(thing, int),
+ ),
+ )
+ validator = Crazy({"type": "any"})
+ validator.validate(12)
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate("foo")
+
+ def test_is_type_is_true_for_any_type(self):
+ self.assertTrue(self.Validator({"type": "any"}).is_valid(object()))
+
+ def test_is_type_does_not_evade_bool_if_it_is_being_tested(self):
+ self.assertTrue(self.Validator({}).is_type(True, "boolean"))
+ self.assertTrue(self.Validator({"type": "any"}).is_valid(True))
+
+
+class TestDraft4Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
+ Validator = validators.Draft4Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft6Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft6Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft7Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft7Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft201909Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft201909Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft202012Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft202012Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestLatestValidator(TestCase):
+ """
+ These really apply to multiple versions but are easiest to test on one.
+ """
+
+ def test_ref_resolvers_may_have_boolean_schemas_stored(self):
+ ref = "someCoolRef"
+ schema = {"$ref": ref}
+ resolver = validators._RefResolver("", {}, store={ref: False})
+ validator = validators._LATEST_VERSION(schema, resolver=resolver)
+
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(None)
+
+
+class TestValidatorFor(TestCase):
+ def test_draft_3(self):
+ schema = {"$schema": "http://json-schema.org/draft-03/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft3Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-03/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft3Validator,
+ )
+
+ def test_draft_4(self):
+ schema = {"$schema": "http://json-schema.org/draft-04/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft4Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft4Validator,
+ )
+
+ def test_draft_6(self):
+ schema = {"$schema": "http://json-schema.org/draft-06/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft6Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-06/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft6Validator,
+ )
+
+ def test_draft_7(self):
+ schema = {"$schema": "http://json-schema.org/draft-07/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft7Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-07/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft7Validator,
+ )
+
+ def test_draft_201909(self):
+ schema = {"$schema": "https://json-schema.org/draft/2019-09/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft201909Validator,
+ )
+
+ schema = {"$schema": "https://json-schema.org/draft/2019-09/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft201909Validator,
+ )
+
+ def test_draft_202012(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft202012Validator,
+ )
+
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft202012Validator,
+ )
+
+ def test_True(self):
+ self.assertIs(
+ validators.validator_for(True),
+ validators._LATEST_VERSION,
+ )
+
+ def test_False(self):
+ self.assertIs(
+ validators.validator_for(False),
+ validators._LATEST_VERSION,
+ )
+
+ def test_custom_validator(self):
+ Validator = validators.create(
+ meta_schema={"id": "meta schema id"},
+ version="12",
+ id_of=lambda s: s.get("id", ""),
+ )
+ schema = {"$schema": "meta schema id"}
+ self.assertIs(
+ validators.validator_for(schema),
+ Validator,
+ )
+
+ def test_custom_validator_draft6(self):
+ Validator = validators.create(
+ meta_schema={"$id": "meta schema $id"},
+ version="13",
+ )
+ schema = {"$schema": "meta schema $id"}
+ self.assertIs(
+ validators.validator_for(schema),
+ Validator,
+ )
+
+ def test_validator_for_jsonschema_default(self):
+ self.assertIs(validators.validator_for({}), validators._LATEST_VERSION)
+
+ def test_validator_for_custom_default(self):
+ self.assertIs(validators.validator_for({}, default=None), None)
+
+ def test_warns_if_meta_schema_specified_was_not_found(self):
+ with self.assertWarns(DeprecationWarning) as cm:
+ validators.validator_for(schema={"$schema": "unknownSchema"})
+
+ self.assertEqual(cm.filename, __file__)
+ self.assertEqual(
+ str(cm.warning),
+ "The metaschema specified by $schema was not found. "
+ "Using the latest draft to validate, but this will raise "
+ "an error in the future.",
+ )
+
+ def test_does_not_warn_if_meta_schema_is_unspecified(self):
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ validators.validator_for(schema={}, default={})
+ self.assertFalse(w)
+
+ def test_validator_for_custom_default_with_schema(self):
+ schema, default = {"$schema": "mailto:foo@example.com"}, object()
+ self.assertIs(validators.validator_for(schema, default), default)
+
+
+class TestValidate(TestCase):
+ def assertUses(self, schema, Validator):
+ result = []
+ with mock.patch.object(Validator, "check_schema", result.append):
+ validators.validate({}, schema)
+ self.assertEqual(result, [schema])
+
+ def test_draft3_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-03/schema#"},
+ Validator=validators.Draft3Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-03/schema"},
+ Validator=validators.Draft3Validator,
+ )
+
+ def test_draft4_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-04/schema#"},
+ Validator=validators.Draft4Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-04/schema"},
+ Validator=validators.Draft4Validator,
+ )
+
+ def test_draft6_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-06/schema#"},
+ Validator=validators.Draft6Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-06/schema"},
+ Validator=validators.Draft6Validator,
+ )
+
+ def test_draft7_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-07/schema#"},
+ Validator=validators.Draft7Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-07/schema"},
+ Validator=validators.Draft7Validator,
+ )
+
+ def test_draft202012_validator_is_chosen(self):
+ self.assertUses(
+ schema={
+ "$schema": "https://json-schema.org/draft/2020-12/schema#",
+ },
+ Validator=validators.Draft202012Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ },
+ Validator=validators.Draft202012Validator,
+ )
+
+ def test_draft202012_validator_is_the_default(self):
+ self.assertUses(schema={}, Validator=validators.Draft202012Validator)
+
+ def test_validation_error_message(self):
+ with self.assertRaises(exceptions.ValidationError) as e:
+ validators.validate(12, {"type": "string"})
+ self.assertRegex(
+ str(e.exception),
+ "(?s)Failed validating '.*' in schema.*On instance",
+ )
+
+ def test_schema_error_message(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ validators.validate(12, {"type": 12})
+ self.assertRegex(
+ str(e.exception),
+ "(?s)Failed validating '.*' in metaschema.*On schema",
+ )
+
+ def test_it_uses_best_match(self):
+ schema = {
+ "oneOf": [
+ {"type": "number", "minimum": 20},
+ {"type": "array"},
+ ],
+ }
+ with self.assertRaises(exceptions.ValidationError) as e:
+ validators.validate(12, schema)
+ self.assertIn("12 is less than the minimum of 20", str(e.exception))
+
+
+class TestThreading(TestCase):
+ """
+ Threading-related functionality tests.
+
+ jsonschema doesn't promise thread safety, and its validation behavior
+ across multiple threads may change at any time, but that means it isn't
+ safe to share *validators* across threads, not that anytime one has
+ multiple threads that jsonschema won't work (it certainly is intended to).
+
+ These tests ensure that this minimal level of functionality continues to
+ work.
+ """
+
+ def test_validation_across_a_second_thread(self):
+ failed = []
+
+ def validate():
+ try:
+ validators.validate(instance=37, schema=True)
+ except: # pragma: no cover # noqa: E722
+ failed.append(sys.exc_info())
+
+ validate() # just verify it succeeds
+
+ from threading import Thread
+ thread = Thread(target=validate)
+ thread.start()
+ thread.join()
+ self.assertEqual((thread.is_alive(), failed), (False, []))
+
+
+class TestReferencing(TestCase):
+ def test_registry_with_retrieve(self):
+ def retrieve(uri):
+ return DRAFT202012.create_resource({"type": "integer"})
+
+ registry = referencing.Registry(retrieve=retrieve)
+ schema = {"$ref": "https://example.com/"}
+ validator = validators.Draft202012Validator(schema, registry=registry)
+
+ self.assertEqual(
+ (validator.is_valid(12), validator.is_valid("foo")),
+ (True, False),
+ )
+
+ def test_custom_registries_do_not_autoretrieve_remote_resources(self):
+ registry = referencing.Registry()
+ schema = {"$ref": "https://example.com/"}
+ validator = validators.Draft202012Validator(schema, registry=registry)
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ with self.assertRaises(referencing.exceptions.Unresolvable):
+ validator.validate(12)
+ self.assertFalse(w)
+
+
+class TestRefResolver(TestCase):
+
+ base_uri = ""
+ stored_uri = "foo://stored"
+ stored_schema = {"stored": "schema"}
+
+ def setUp(self):
+ self.referrer = {}
+ self.store = {self.stored_uri: self.stored_schema}
+ self.resolver = validators._RefResolver(
+ self.base_uri, self.referrer, self.store,
+ )
+
+ def test_it_does_not_retrieve_schema_urls_from_the_network(self):
+ ref = validators.Draft3Validator.META_SCHEMA["id"]
+ with mock.patch.object(self.resolver, "resolve_remote") as patched: # noqa: SIM117
+ with self.resolver.resolving(ref) as resolved:
+ pass
+ self.assertEqual(resolved, validators.Draft3Validator.META_SCHEMA)
+ self.assertFalse(patched.called)
+
+ def test_it_resolves_local_refs(self):
+ ref = "#/properties/foo"
+ self.referrer["properties"] = {"foo": object()}
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, self.referrer["properties"]["foo"])
+
+ def test_it_resolves_local_refs_with_id(self):
+ schema = {"id": "http://bar/schema#", "a": {"foo": "bar"}}
+ resolver = validators._RefResolver.from_schema(
+ schema,
+ id_of=lambda schema: schema.get("id", ""),
+ )
+ with resolver.resolving("#/a") as resolved:
+ self.assertEqual(resolved, schema["a"])
+ with resolver.resolving("http://bar/schema#/a") as resolved:
+ self.assertEqual(resolved, schema["a"])
+
+ def test_it_retrieves_stored_refs(self):
+ with self.resolver.resolving(self.stored_uri) as resolved:
+ self.assertIs(resolved, self.stored_schema)
+
+ self.resolver.store["cached_ref"] = {"foo": 12}
+ with self.resolver.resolving("cached_ref#/foo") as resolved:
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_unstored_refs_via_requests(self):
+ ref = "http://bar#baz"
+ schema = {"baz": 12}
+
+ if "requests" in sys.modules: # pragma: no cover
+ self.addCleanup(
+ sys.modules.__setitem__, "requests", sys.modules["requests"],
+ )
+ sys.modules["requests"] = ReallyFakeRequests({"http://bar": schema})
+
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_unstored_refs_via_urlopen(self):
+ ref = "http://bar#baz"
+ schema = {"baz": 12}
+
+ if "requests" in sys.modules: # pragma: no cover
+ self.addCleanup(
+ sys.modules.__setitem__, "requests", sys.modules["requests"],
+ )
+ sys.modules["requests"] = None
+
+ @contextmanager
+ def fake_urlopen(url):
+ self.assertEqual(url, "http://bar")
+ yield BytesIO(json.dumps(schema).encode("utf8"))
+
+ self.addCleanup(setattr, validators, "urlopen", validators.urlopen)
+ validators.urlopen = fake_urlopen
+
+ with self.resolver.resolving(ref) as resolved:
+ pass
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_local_refs_via_urlopen(self):
+ with tempfile.NamedTemporaryFile(delete=False, mode="wt") as tempf:
+ self.addCleanup(os.remove, tempf.name)
+ json.dump({"foo": "bar"}, tempf)
+
+ ref = f"file://{pathname2url(tempf.name)}#foo"
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, "bar")
+
+ def test_it_can_construct_a_base_uri_from_a_schema(self):
+ schema = {"id": "foo"}
+ resolver = validators._RefResolver.from_schema(
+ schema,
+ id_of=lambda schema: schema.get("id", ""),
+ )
+ self.assertEqual(resolver.base_uri, "foo")
+ self.assertEqual(resolver.resolution_scope, "foo")
+ with resolver.resolving("") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("#") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("foo") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("foo#") as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_it_can_construct_a_base_uri_from_a_schema_without_id(self):
+ schema = {}
+ resolver = validators._RefResolver.from_schema(schema)
+ self.assertEqual(resolver.base_uri, "")
+ self.assertEqual(resolver.resolution_scope, "")
+ with resolver.resolving("") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("#") as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_custom_uri_scheme_handlers(self):
+ def handler(url):
+ self.assertEqual(url, ref)
+ return schema
+
+ schema = {"foo": "bar"}
+ ref = "foo://bar"
+ resolver = validators._RefResolver("", {}, handlers={"foo": handler})
+ with resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_cache_remote_on(self):
+ response = [object()]
+
+ def handler(url):
+ try:
+ return response.pop()
+ except IndexError: # pragma: no cover
+ self.fail("Response must not have been cached!")
+
+ ref = "foo://bar"
+ resolver = validators._RefResolver(
+ "", {}, cache_remote=True, handlers={"foo": handler},
+ )
+ with resolver.resolving(ref):
+ pass
+ with resolver.resolving(ref):
+ pass
+
+ def test_cache_remote_off(self):
+ response = [object()]
+
+ def handler(url):
+ try:
+ return response.pop()
+ except IndexError: # pragma: no cover
+ self.fail("Handler called twice!")
+
+ ref = "foo://bar"
+ resolver = validators._RefResolver(
+ "", {}, cache_remote=False, handlers={"foo": handler},
+ )
+ with resolver.resolving(ref):
+ pass
+
+ def test_if_you_give_it_junk_you_get_a_resolution_error(self):
+ error = ValueError("Oh no! What's this?")
+
+ def handler(url):
+ raise error
+
+ ref = "foo://bar"
+ resolver = validators._RefResolver("", {}, handlers={"foo": handler})
+ with self.assertRaises(exceptions._RefResolutionError) as err: # noqa: SIM117
+ with resolver.resolving(ref):
+ self.fail("Shouldn't get this far!") # pragma: no cover
+ self.assertEqual(err.exception, exceptions._RefResolutionError(error))
+
+ def test_helpful_error_message_on_failed_pop_scope(self):
+ resolver = validators._RefResolver("", {})
+ resolver.pop_scope()
+ with self.assertRaises(exceptions._RefResolutionError) as exc:
+ resolver.pop_scope()
+ self.assertIn("Failed to pop the scope", str(exc.exception))
+
+ def test_pointer_within_schema_with_different_id(self):
+ """
+ See #1085.
+ """
+ schema = validators.Draft7Validator.META_SCHEMA
+ one = validators._RefResolver("", schema)
+ validator = validators.Draft7Validator(schema, resolver=one)
+ self.assertFalse(validator.is_valid({"maxLength": "foo"}))
+
+ another = {
+ "allOf": [{"$ref": validators.Draft7Validator.META_SCHEMA["$id"]}],
+ }
+ two = validators._RefResolver("", another)
+ validator = validators.Draft7Validator(another, resolver=two)
+ self.assertFalse(validator.is_valid({"maxLength": "foo"}))
+
+ def test_newly_created_validator_with_ref_resolver(self):
+ """
+ See https://github.com/python-jsonschema/jsonschema/issues/1061#issuecomment-1624266555.
+ """
+
+ def handle(uri):
+ self.assertEqual(uri, "http://example.com/foo")
+ return {"type": "integer"}
+
+ resolver = validators._RefResolver("", {}, handlers={"http": handle})
+ Validator = validators.create(
+ meta_schema={},
+ validators=validators.Draft4Validator.VALIDATORS,
+ )
+ schema = {"$id": "http://example.com/bar", "$ref": "foo"}
+ validator = Validator(schema, resolver=resolver)
+ self.assertEqual(
+ (validator.is_valid({}), validator.is_valid(37)),
+ (False, True),
+ )
+
+ def test_refresolver_with_pointer_in_schema_with_no_id(self):
+ """
+ See https://github.com/python-jsonschema/jsonschema/issues/1124#issuecomment-1632574249.
+ """
+
+ schema = {
+ "properties": {"x": {"$ref": "#/definitions/x"}},
+ "definitions": {"x": {"type": "integer"}},
+ }
+
+ validator = validators.Draft202012Validator(
+ schema,
+ resolver=validators._RefResolver("", schema),
+ )
+ self.assertEqual(
+ (validator.is_valid({"x": "y"}), validator.is_valid({"x": 37})),
+ (False, True),
+ )
+
+
+
+def sorted_errors(errors):
+ def key(error):
+ return (
+ [str(e) for e in error.path],
+ [str(e) for e in error.schema_path],
+ )
+ return sorted(errors, key=key)
+
+
+@define
+class ReallyFakeRequests:
+
+ _responses: dict[str, Any]
+
+ def get(self, url):
+ response = self._responses.get(url)
+ if url is None: # pragma: no cover
+ raise ValueError("Unknown URL: " + repr(url))
+ return _ReallyFakeJSONResponse(json.dumps(response))
+
+
+@define
+class _ReallyFakeJSONResponse:
+
+ _response: str
+
+ def json(self):
+ return json.loads(self._response)
diff --git a/venv/lib/python3.10/site-packages/jsonschema/validators.py b/venv/lib/python3.10/site-packages/jsonschema/validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8ca3bd451e2da42da8f7c926cffd5da59697621
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/jsonschema/validators.py
@@ -0,0 +1,1410 @@
+"""
+Creation and extension of validators, with implementations for existing drafts.
+"""
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Iterable, Mapping, Sequence
+from functools import lru_cache
+from operator import methodcaller
+from typing import TYPE_CHECKING
+from urllib.parse import unquote, urldefrag, urljoin, urlsplit
+from urllib.request import urlopen
+from warnings import warn
+import contextlib
+import json
+import reprlib
+import warnings
+
+from attrs import define, field, fields
+from jsonschema_specifications import REGISTRY as SPECIFICATIONS
+from rpds import HashTrieMap
+import referencing.exceptions
+import referencing.jsonschema
+
+from jsonschema import (
+ _format,
+ _keywords,
+ _legacy_keywords,
+ _types,
+ _typing,
+ _utils,
+ exceptions,
+)
+
+if TYPE_CHECKING:
+ from jsonschema.protocols import Validator
+
+_UNSET = _utils.Unset()
+
+_VALIDATORS: dict[str, Validator] = {}
+_META_SCHEMAS = _utils.URIDict()
+
+
+def __getattr__(name):
+ if name == "ErrorTree":
+ warnings.warn(
+ "Importing ErrorTree from jsonschema.validators is deprecated. "
+ "Instead import it from jsonschema.exceptions.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from jsonschema.exceptions import ErrorTree
+ return ErrorTree
+ elif name == "validators":
+ warnings.warn(
+ "Accessing jsonschema.validators.validators is deprecated. "
+ "Use jsonschema.validators.validator_for with a given schema.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _VALIDATORS
+ elif name == "meta_schemas":
+ warnings.warn(
+ "Accessing jsonschema.validators.meta_schemas is deprecated. "
+ "Use jsonschema.validators.validator_for with a given schema.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _META_SCHEMAS
+ elif name == "RefResolver":
+ warnings.warn(
+ _RefResolver._DEPRECATION_MESSAGE,
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _RefResolver
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+def validates(version):
+ """
+ Register the decorated validator for a ``version`` of the specification.
+
+ Registered validators and their meta schemas will be considered when
+ parsing :kw:`$schema` keywords' URIs.
+
+ Arguments:
+
+ version (str):
+
+ An identifier to use as the version's name
+
+ Returns:
+
+ collections.abc.Callable:
+
+ a class decorator to decorate the validator with the version
+
+ """
+
+ def _validates(cls):
+ _VALIDATORS[version] = cls
+ meta_schema_id = cls.ID_OF(cls.META_SCHEMA)
+ _META_SCHEMAS[meta_schema_id] = cls
+ return cls
+ return _validates
+
+
+def _warn_for_remote_retrieve(uri: str):
+ from urllib.request import Request, urlopen
+ headers = {"User-Agent": "python-jsonschema (deprecated $ref resolution)"}
+ request = Request(uri, headers=headers) # noqa: S310
+ with urlopen(request) as response: # noqa: S310
+ warnings.warn(
+ "Automatically retrieving remote references can be a security "
+ "vulnerability and is discouraged by the JSON Schema "
+ "specifications. Relying on this behavior is deprecated "
+ "and will shortly become an error. If you are sure you want to "
+ "remotely retrieve your reference and that it is safe to do so, "
+ "you can find instructions for doing so via referencing.Registry "
+ "in the referencing documentation "
+ "(https://referencing.readthedocs.org).",
+ DeprecationWarning,
+ stacklevel=9, # Ha ha ha ha magic numbers :/
+ )
+ return referencing.Resource.from_contents(
+ json.load(response),
+ default_specification=referencing.jsonschema.DRAFT202012,
+ )
+
+
+_REMOTE_WARNING_REGISTRY = SPECIFICATIONS.combine(
+ referencing.Registry(retrieve=_warn_for_remote_retrieve), # type: ignore[call-arg]
+)
+
+
+def create(
+ meta_schema: referencing.jsonschema.ObjectSchema,
+ validators: (
+ Mapping[str, _typing.SchemaKeywordValidator]
+ | Iterable[tuple[str, _typing.SchemaKeywordValidator]]
+ ) = (),
+ version: str | None = None,
+ type_checker: _types.TypeChecker = _types.draft202012_type_checker,
+ format_checker: _format.FormatChecker = _format.draft202012_format_checker,
+ id_of: _typing.id_of = referencing.jsonschema.DRAFT202012.id_of,
+ applicable_validators: _typing.ApplicableValidators = methodcaller(
+ "items",
+ ),
+):
+ """
+ Create a new validator class.
+
+ Arguments:
+
+ meta_schema:
+
+ the meta schema for the new validator class
+
+ validators:
+
+ a mapping from names to callables, where each callable will
+ validate the schema property with the given name.
+
+ Each callable should take 4 arguments:
+
+ 1. a validator instance,
+ 2. the value of the property being validated within the
+ instance
+ 3. the instance
+ 4. the schema
+
+ version:
+
+ an identifier for the version that this validator class will
+ validate. If provided, the returned validator class will
+ have its ``__name__`` set to include the version, and also
+ will have `jsonschema.validators.validates` automatically
+ called for the given version.
+
+ type_checker:
+
+ a type checker, used when applying the :kw:`type` keyword.
+
+ If unprovided, a `jsonschema.TypeChecker` will be created
+ with a set of default types typical of JSON Schema drafts.
+
+ format_checker:
+
+ a format checker, used when applying the :kw:`format` keyword.
+
+ If unprovided, a `jsonschema.FormatChecker` will be created
+ with a set of default formats typical of JSON Schema drafts.
+
+ id_of:
+
+ A function that given a schema, returns its ID.
+
+ applicable_validators:
+
+ A function that, given a schema, returns the list of
+ applicable schema keywords and associated values
+ which will be used to validate the instance.
+ This is mostly used to support pre-draft 7 versions of JSON Schema
+ which specified behavior around ignoring keywords if they were
+ siblings of a ``$ref`` keyword. If you're not attempting to
+ implement similar behavior, you can typically ignore this argument
+ and leave it at its default.
+
+ Returns:
+
+ a new `jsonschema.protocols.Validator` class
+
+ """
+ # preemptively don't shadow the `Validator.format_checker` local
+ format_checker_arg = format_checker
+
+ specification = referencing.jsonschema.specification_with(
+ dialect_id=id_of(meta_schema) or "urn:unknown-dialect",
+ default=referencing.Specification.OPAQUE,
+ )
+
+ @define
+ class Validator:
+
+ VALIDATORS = dict(validators) # noqa: RUF012
+ META_SCHEMA = dict(meta_schema) # noqa: RUF012
+ TYPE_CHECKER = type_checker
+ FORMAT_CHECKER = format_checker_arg
+ ID_OF = staticmethod(id_of)
+
+ _APPLICABLE_VALIDATORS = applicable_validators
+ _validators = field(init=False, repr=False, eq=False)
+
+ schema: referencing.jsonschema.Schema = field(repr=reprlib.repr)
+ _ref_resolver = field(default=None, repr=False, alias="resolver")
+ format_checker: _format.FormatChecker | None = field(default=None)
+ # TODO: include new meta-schemas added at runtime
+ _registry: referencing.jsonschema.SchemaRegistry = field(
+ default=_REMOTE_WARNING_REGISTRY,
+ kw_only=True,
+ repr=False,
+ )
+ _resolver = field(
+ alias="_resolver",
+ default=None,
+ kw_only=True,
+ repr=False,
+ )
+
+ def __init_subclass__(cls):
+ warnings.warn(
+ (
+ "Subclassing validator classes is not intended to "
+ "be part of their public API. A future version "
+ "will make doing so an error, as the behavior of "
+ "subclasses isn't guaranteed to stay the same "
+ "between releases of jsonschema. Instead, prefer "
+ "composition of validators, wrapping them in an object "
+ "owned entirely by the downstream library."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ def evolve(self, **changes):
+ cls = self.__class__
+ schema = changes.setdefault("schema", self.schema)
+ NewValidator = validator_for(schema, default=cls)
+
+ for field in fields(cls): # noqa: F402
+ if not field.init:
+ continue
+ attr_name = field.name
+ init_name = field.alias
+ if init_name not in changes:
+ changes[init_name] = getattr(self, attr_name)
+
+ return NewValidator(**changes)
+
+ cls.evolve = evolve
+
+ def __attrs_post_init__(self):
+ if self._resolver is None:
+ registry = self._registry
+ if registry is not _REMOTE_WARNING_REGISTRY:
+ registry = SPECIFICATIONS.combine(registry)
+ resource = specification.create_resource(self.schema)
+ self._resolver = registry.resolver_with_root(resource)
+
+ if self.schema is True or self.schema is False:
+ self._validators = []
+ else:
+ self._validators = [
+ (self.VALIDATORS[k], k, v)
+ for k, v in applicable_validators(self.schema)
+ if k in self.VALIDATORS
+ ]
+
+ # REMOVEME: Legacy ref resolution state management.
+ push_scope = getattr(self._ref_resolver, "push_scope", None)
+ if push_scope is not None:
+ id = id_of(self.schema)
+ if id is not None:
+ push_scope(id)
+
+ @classmethod
+ def check_schema(cls, schema, format_checker=_UNSET):
+ Validator = validator_for(cls.META_SCHEMA, default=cls)
+ if format_checker is _UNSET:
+ format_checker = Validator.FORMAT_CHECKER
+ validator = Validator(
+ schema=cls.META_SCHEMA,
+ format_checker=format_checker,
+ )
+ for error in validator.iter_errors(schema):
+ raise exceptions.SchemaError.create_from(error)
+
+ @property
+ def resolver(self):
+ warnings.warn(
+ (
+ f"Accessing {self.__class__.__name__}.resolver is "
+ "deprecated as of v4.18.0, in favor of the "
+ "https://github.com/python-jsonschema/referencing "
+ "library, which provides more compliant referencing "
+ "behavior as well as more flexible APIs for "
+ "customization."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ if self._ref_resolver is None:
+ self._ref_resolver = _RefResolver.from_schema(
+ self.schema,
+ id_of=id_of,
+ )
+ return self._ref_resolver
+
+ def evolve(self, **changes):
+ schema = changes.setdefault("schema", self.schema)
+ NewValidator = validator_for(schema, default=self.__class__)
+
+ for (attr_name, init_name) in evolve_fields:
+ if init_name not in changes:
+ changes[init_name] = getattr(self, attr_name)
+
+ return NewValidator(**changes)
+
+ def iter_errors(self, instance, _schema=None):
+ if _schema is not None:
+ warnings.warn(
+ (
+ "Passing a schema to Validator.iter_errors "
+ "is deprecated and will be removed in a future "
+ "release. Call validator.evolve(schema=new_schema)."
+ "iter_errors(...) instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ validators = [
+ (self.VALIDATORS[k], k, v)
+ for k, v in applicable_validators(_schema)
+ if k in self.VALIDATORS
+ ]
+ else:
+ _schema, validators = self.schema, self._validators
+
+ if _schema is True:
+ return
+ elif _schema is False:
+ yield exceptions.ValidationError(
+ f"False schema does not allow {instance!r}",
+ validator=None,
+ validator_value=None,
+ instance=instance,
+ schema=_schema,
+ )
+ return
+
+ for validator, k, v in validators:
+ errors = validator(self, v, instance, _schema) or ()
+ for error in errors:
+ # set details if not already set by the called fn
+ error._set(
+ validator=k,
+ validator_value=v,
+ instance=instance,
+ schema=_schema,
+ type_checker=self.TYPE_CHECKER,
+ )
+ if k not in {"if", "$ref"}:
+ error.schema_path.appendleft(k)
+ yield error
+
+ def descend(
+ self,
+ instance,
+ schema,
+ path=None,
+ schema_path=None,
+ resolver=None,
+ ):
+ if schema is True:
+ return
+ elif schema is False:
+ yield exceptions.ValidationError(
+ f"False schema does not allow {instance!r}",
+ validator=None,
+ validator_value=None,
+ instance=instance,
+ schema=schema,
+ )
+ return
+
+ if self._ref_resolver is not None:
+ evolved = self.evolve(schema=schema)
+ else:
+ if resolver is None:
+ resolver = self._resolver.in_subresource(
+ specification.create_resource(schema),
+ )
+ evolved = self.evolve(schema=schema, _resolver=resolver)
+
+ for k, v in applicable_validators(schema):
+ validator = evolved.VALIDATORS.get(k)
+ if validator is None:
+ continue
+
+ errors = validator(evolved, v, instance, schema) or ()
+ for error in errors:
+ # set details if not already set by the called fn
+ error._set(
+ validator=k,
+ validator_value=v,
+ instance=instance,
+ schema=schema,
+ type_checker=evolved.TYPE_CHECKER,
+ )
+ if k not in {"if", "$ref"}:
+ error.schema_path.appendleft(k)
+ if path is not None:
+ error.path.appendleft(path)
+ if schema_path is not None:
+ error.schema_path.appendleft(schema_path)
+ yield error
+
+ def validate(self, *args, **kwargs):
+ for error in self.iter_errors(*args, **kwargs):
+ raise error
+
+ def is_type(self, instance, type):
+ try:
+ return self.TYPE_CHECKER.is_type(instance, type)
+ except exceptions.UndefinedTypeCheck:
+ exc = exceptions.UnknownType(type, instance, self.schema)
+ raise exc from None
+
+ def _validate_reference(self, ref, instance):
+ if self._ref_resolver is None:
+ try:
+ resolved = self._resolver.lookup(ref)
+ except referencing.exceptions.Unresolvable as err:
+ raise exceptions._WrappedReferencingError(err) from err
+
+ return self.descend(
+ instance,
+ resolved.contents,
+ resolver=resolved.resolver,
+ )
+ else:
+ resolve = getattr(self._ref_resolver, "resolve", None)
+ if resolve is None:
+ with self._ref_resolver.resolving(ref) as resolved:
+ return self.descend(instance, resolved)
+ else:
+ scope, resolved = resolve(ref)
+ self._ref_resolver.push_scope(scope)
+
+ try:
+ return list(self.descend(instance, resolved))
+ finally:
+ self._ref_resolver.pop_scope()
+
+ def is_valid(self, instance, _schema=None):
+ if _schema is not None:
+ warnings.warn(
+ (
+ "Passing a schema to Validator.is_valid is deprecated "
+ "and will be removed in a future release. Call "
+ "validator.evolve(schema=new_schema).is_valid(...) "
+ "instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self = self.evolve(schema=_schema)
+
+ error = next(self.iter_errors(instance), None)
+ return error is None
+
+ evolve_fields = [
+ (field.name, field.alias)
+ for field in fields(Validator)
+ if field.init
+ ]
+
+ if version is not None:
+ safe = version.title().replace(" ", "").replace("-", "")
+ Validator.__name__ = Validator.__qualname__ = f"{safe}Validator"
+ Validator = validates(version)(Validator) # type: ignore[misc]
+
+ return Validator
+
+
+def extend(
+ validator,
+ validators=(),
+ version=None,
+ type_checker=None,
+ format_checker=None,
+):
+ """
+ Create a new validator class by extending an existing one.
+
+ Arguments:
+
+ validator (jsonschema.protocols.Validator):
+
+ an existing validator class
+
+ validators (collections.abc.Mapping):
+
+ a mapping of new validator callables to extend with, whose
+ structure is as in `create`.
+
+ .. note::
+
+ Any validator callables with the same name as an
+ existing one will (silently) replace the old validator
+ callable entirely, effectively overriding any validation
+ done in the "parent" validator class.
+
+ If you wish to instead extend the behavior of a parent's
+ validator callable, delegate and call it directly in
+ the new validator function by retrieving it using
+ ``OldValidator.VALIDATORS["validation_keyword_name"]``.
+
+ version (str):
+
+ a version for the new validator class
+
+ type_checker (jsonschema.TypeChecker):
+
+ a type checker, used when applying the :kw:`type` keyword.
+
+ If unprovided, the type checker of the extended
+ `jsonschema.protocols.Validator` will be carried along.
+
+ format_checker (jsonschema.FormatChecker):
+
+ a format checker, used when applying the :kw:`format` keyword.
+
+ If unprovided, the format checker of the extended
+ `jsonschema.protocols.Validator` will be carried along.
+
+ Returns:
+
+ a new `jsonschema.protocols.Validator` class extending the one
+ provided
+
+ .. note:: Meta Schemas
+
+ The new validator class will have its parent's meta schema.
+
+ If you wish to change or extend the meta schema in the new
+ validator class, modify ``META_SCHEMA`` directly on the returned
+ class. Note that no implicit copying is done, so a copy should
+ likely be made before modifying it, in order to not affect the
+ old validator.
+
+ """
+ all_validators = dict(validator.VALIDATORS)
+ all_validators.update(validators)
+
+ if type_checker is None:
+ type_checker = validator.TYPE_CHECKER
+ if format_checker is None:
+ format_checker = validator.FORMAT_CHECKER
+ return create(
+ meta_schema=validator.META_SCHEMA,
+ validators=all_validators,
+ version=version,
+ type_checker=type_checker,
+ format_checker=format_checker,
+ id_of=validator.ID_OF,
+ applicable_validators=validator._APPLICABLE_VALIDATORS,
+ )
+
+
+Draft3Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "http://json-schema.org/draft-03/schema#",
+ ),
+ validators={
+ "$ref": _keywords.ref,
+ "additionalItems": _legacy_keywords.additionalItems,
+ "additionalProperties": _keywords.additionalProperties,
+ "dependencies": _legacy_keywords.dependencies_draft3,
+ "disallow": _legacy_keywords.disallow_draft3,
+ "divisibleBy": _keywords.multipleOf,
+ "enum": _keywords.enum,
+ "extends": _legacy_keywords.extends_draft3,
+ "format": _keywords.format,
+ "items": _legacy_keywords.items_draft3_draft4,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maximum": _legacy_keywords.maximum_draft3_draft4,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minimum": _legacy_keywords.minimum_draft3_draft4,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "properties": _legacy_keywords.properties_draft3,
+ "type": _legacy_keywords.type_draft3,
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft3_type_checker,
+ format_checker=_format.draft3_format_checker,
+ version="draft3",
+ id_of=referencing.jsonschema.DRAFT3.id_of,
+ applicable_validators=_legacy_keywords.ignore_ref_siblings,
+)
+
+Draft4Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "http://json-schema.org/draft-04/schema#",
+ ),
+ validators={
+ "$ref": _keywords.ref,
+ "additionalItems": _legacy_keywords.additionalItems,
+ "additionalProperties": _keywords.additionalProperties,
+ "allOf": _keywords.allOf,
+ "anyOf": _keywords.anyOf,
+ "dependencies": _legacy_keywords.dependencies_draft4_draft6_draft7,
+ "enum": _keywords.enum,
+ "format": _keywords.format,
+ "items": _legacy_keywords.items_draft3_draft4,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maxProperties": _keywords.maxProperties,
+ "maximum": _legacy_keywords.maximum_draft3_draft4,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minProperties": _keywords.minProperties,
+ "minimum": _legacy_keywords.minimum_draft3_draft4,
+ "multipleOf": _keywords.multipleOf,
+ "not": _keywords.not_,
+ "oneOf": _keywords.oneOf,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "properties": _keywords.properties,
+ "required": _keywords.required,
+ "type": _keywords.type,
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft4_type_checker,
+ format_checker=_format.draft4_format_checker,
+ version="draft4",
+ id_of=referencing.jsonschema.DRAFT4.id_of,
+ applicable_validators=_legacy_keywords.ignore_ref_siblings,
+)
+
+Draft6Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "http://json-schema.org/draft-06/schema#",
+ ),
+ validators={
+ "$ref": _keywords.ref,
+ "additionalItems": _legacy_keywords.additionalItems,
+ "additionalProperties": _keywords.additionalProperties,
+ "allOf": _keywords.allOf,
+ "anyOf": _keywords.anyOf,
+ "const": _keywords.const,
+ "contains": _legacy_keywords.contains_draft6_draft7,
+ "dependencies": _legacy_keywords.dependencies_draft4_draft6_draft7,
+ "enum": _keywords.enum,
+ "exclusiveMaximum": _keywords.exclusiveMaximum,
+ "exclusiveMinimum": _keywords.exclusiveMinimum,
+ "format": _keywords.format,
+ "items": _legacy_keywords.items_draft6_draft7_draft201909,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maxProperties": _keywords.maxProperties,
+ "maximum": _keywords.maximum,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minProperties": _keywords.minProperties,
+ "minimum": _keywords.minimum,
+ "multipleOf": _keywords.multipleOf,
+ "not": _keywords.not_,
+ "oneOf": _keywords.oneOf,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "properties": _keywords.properties,
+ "propertyNames": _keywords.propertyNames,
+ "required": _keywords.required,
+ "type": _keywords.type,
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft6_type_checker,
+ format_checker=_format.draft6_format_checker,
+ version="draft6",
+ id_of=referencing.jsonschema.DRAFT6.id_of,
+ applicable_validators=_legacy_keywords.ignore_ref_siblings,
+)
+
+Draft7Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "http://json-schema.org/draft-07/schema#",
+ ),
+ validators={
+ "$ref": _keywords.ref,
+ "additionalItems": _legacy_keywords.additionalItems,
+ "additionalProperties": _keywords.additionalProperties,
+ "allOf": _keywords.allOf,
+ "anyOf": _keywords.anyOf,
+ "const": _keywords.const,
+ "contains": _legacy_keywords.contains_draft6_draft7,
+ "dependencies": _legacy_keywords.dependencies_draft4_draft6_draft7,
+ "enum": _keywords.enum,
+ "exclusiveMaximum": _keywords.exclusiveMaximum,
+ "exclusiveMinimum": _keywords.exclusiveMinimum,
+ "format": _keywords.format,
+ "if": _keywords.if_,
+ "items": _legacy_keywords.items_draft6_draft7_draft201909,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maxProperties": _keywords.maxProperties,
+ "maximum": _keywords.maximum,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minProperties": _keywords.minProperties,
+ "minimum": _keywords.minimum,
+ "multipleOf": _keywords.multipleOf,
+ "not": _keywords.not_,
+ "oneOf": _keywords.oneOf,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "properties": _keywords.properties,
+ "propertyNames": _keywords.propertyNames,
+ "required": _keywords.required,
+ "type": _keywords.type,
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft7_type_checker,
+ format_checker=_format.draft7_format_checker,
+ version="draft7",
+ id_of=referencing.jsonschema.DRAFT7.id_of,
+ applicable_validators=_legacy_keywords.ignore_ref_siblings,
+)
+
+Draft201909Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "https://json-schema.org/draft/2019-09/schema",
+ ),
+ validators={
+ "$recursiveRef": _legacy_keywords.recursiveRef,
+ "$ref": _keywords.ref,
+ "additionalItems": _legacy_keywords.additionalItems,
+ "additionalProperties": _keywords.additionalProperties,
+ "allOf": _keywords.allOf,
+ "anyOf": _keywords.anyOf,
+ "const": _keywords.const,
+ "contains": _keywords.contains,
+ "dependentRequired": _keywords.dependentRequired,
+ "dependentSchemas": _keywords.dependentSchemas,
+ "enum": _keywords.enum,
+ "exclusiveMaximum": _keywords.exclusiveMaximum,
+ "exclusiveMinimum": _keywords.exclusiveMinimum,
+ "format": _keywords.format,
+ "if": _keywords.if_,
+ "items": _legacy_keywords.items_draft6_draft7_draft201909,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maxProperties": _keywords.maxProperties,
+ "maximum": _keywords.maximum,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minProperties": _keywords.minProperties,
+ "minimum": _keywords.minimum,
+ "multipleOf": _keywords.multipleOf,
+ "not": _keywords.not_,
+ "oneOf": _keywords.oneOf,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "properties": _keywords.properties,
+ "propertyNames": _keywords.propertyNames,
+ "required": _keywords.required,
+ "type": _keywords.type,
+ "unevaluatedItems": _legacy_keywords.unevaluatedItems_draft2019,
+ "unevaluatedProperties": (
+ _legacy_keywords.unevaluatedProperties_draft2019
+ ),
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft201909_type_checker,
+ format_checker=_format.draft201909_format_checker,
+ version="draft2019-09",
+)
+
+Draft202012Validator = create(
+ meta_schema=SPECIFICATIONS.contents(
+ "https://json-schema.org/draft/2020-12/schema",
+ ),
+ validators={
+ "$dynamicRef": _keywords.dynamicRef,
+ "$ref": _keywords.ref,
+ "additionalProperties": _keywords.additionalProperties,
+ "allOf": _keywords.allOf,
+ "anyOf": _keywords.anyOf,
+ "const": _keywords.const,
+ "contains": _keywords.contains,
+ "dependentRequired": _keywords.dependentRequired,
+ "dependentSchemas": _keywords.dependentSchemas,
+ "enum": _keywords.enum,
+ "exclusiveMaximum": _keywords.exclusiveMaximum,
+ "exclusiveMinimum": _keywords.exclusiveMinimum,
+ "format": _keywords.format,
+ "if": _keywords.if_,
+ "items": _keywords.items,
+ "maxItems": _keywords.maxItems,
+ "maxLength": _keywords.maxLength,
+ "maxProperties": _keywords.maxProperties,
+ "maximum": _keywords.maximum,
+ "minItems": _keywords.minItems,
+ "minLength": _keywords.minLength,
+ "minProperties": _keywords.minProperties,
+ "minimum": _keywords.minimum,
+ "multipleOf": _keywords.multipleOf,
+ "not": _keywords.not_,
+ "oneOf": _keywords.oneOf,
+ "pattern": _keywords.pattern,
+ "patternProperties": _keywords.patternProperties,
+ "prefixItems": _keywords.prefixItems,
+ "properties": _keywords.properties,
+ "propertyNames": _keywords.propertyNames,
+ "required": _keywords.required,
+ "type": _keywords.type,
+ "unevaluatedItems": _keywords.unevaluatedItems,
+ "unevaluatedProperties": _keywords.unevaluatedProperties,
+ "uniqueItems": _keywords.uniqueItems,
+ },
+ type_checker=_types.draft202012_type_checker,
+ format_checker=_format.draft202012_format_checker,
+ version="draft2020-12",
+)
+
+_LATEST_VERSION: type[Validator] = Draft202012Validator
+
+
+class _RefResolver:
+ """
+ Resolve JSON References.
+
+ Arguments:
+
+ base_uri (str):
+
+ The URI of the referring document
+
+ referrer:
+
+ The actual referring document
+
+ store (dict):
+
+ A mapping from URIs to documents to cache
+
+ cache_remote (bool):
+
+ Whether remote refs should be cached after first resolution
+
+ handlers (dict):
+
+ A mapping from URI schemes to functions that should be used
+ to retrieve them
+
+ urljoin_cache (:func:`functools.lru_cache`):
+
+ A cache that will be used for caching the results of joining
+ the resolution scope to subscopes.
+
+ remote_cache (:func:`functools.lru_cache`):
+
+ A cache that will be used for caching the results of
+ resolved remote URLs.
+
+ Attributes:
+
+ cache_remote (bool):
+
+ Whether remote refs should be cached after first resolution
+
+ .. deprecated:: v4.18.0
+
+ ``RefResolver`` has been deprecated in favor of `referencing`.
+
+ """
+
+ _DEPRECATION_MESSAGE = (
+ "jsonschema.RefResolver is deprecated as of v4.18.0, in favor of the "
+ "https://github.com/python-jsonschema/referencing library, which "
+ "provides more compliant referencing behavior as well as more "
+ "flexible APIs for customization. A future release will remove "
+ "RefResolver. Please file a feature request (on referencing) if you "
+ "are missing an API for the kind of customization you need."
+ )
+
+ def __init__(
+ self,
+ base_uri,
+ referrer,
+ store=HashTrieMap(),
+ cache_remote=True,
+ handlers=(),
+ urljoin_cache=None,
+ remote_cache=None,
+ ):
+ if urljoin_cache is None:
+ urljoin_cache = lru_cache(1024)(urljoin)
+ if remote_cache is None:
+ remote_cache = lru_cache(1024)(self.resolve_from_url)
+
+ self.referrer = referrer
+ self.cache_remote = cache_remote
+ self.handlers = dict(handlers)
+
+ self._scopes_stack = [base_uri]
+
+ self.store = _utils.URIDict(
+ (uri, each.contents) for uri, each in SPECIFICATIONS.items()
+ )
+ self.store.update(
+ (id, each.META_SCHEMA) for id, each in _META_SCHEMAS.items()
+ )
+ self.store.update(store)
+ self.store.update(
+ (schema["$id"], schema)
+ for schema in store.values()
+ if isinstance(schema, Mapping) and "$id" in schema
+ )
+ self.store[base_uri] = referrer
+
+ self._urljoin_cache = urljoin_cache
+ self._remote_cache = remote_cache
+
+ @classmethod
+ def from_schema( # noqa: D417
+ cls,
+ schema,
+ id_of=referencing.jsonschema.DRAFT202012.id_of,
+ *args,
+ **kwargs,
+ ):
+ """
+ Construct a resolver from a JSON schema object.
+
+ Arguments:
+
+ schema:
+
+ the referring schema
+
+ Returns:
+
+ `_RefResolver`
+
+ """
+ return cls(base_uri=id_of(schema) or "", referrer=schema, *args, **kwargs) # noqa: B026, E501
+
+ def push_scope(self, scope):
+ """
+ Enter a given sub-scope.
+
+ Treats further dereferences as being performed underneath the
+ given scope.
+ """
+ self._scopes_stack.append(
+ self._urljoin_cache(self.resolution_scope, scope),
+ )
+
+ def pop_scope(self):
+ """
+ Exit the most recent entered scope.
+
+ Treats further dereferences as being performed underneath the
+ original scope.
+
+ Don't call this method more times than `push_scope` has been
+ called.
+ """
+ try:
+ self._scopes_stack.pop()
+ except IndexError:
+ raise exceptions._RefResolutionError(
+ "Failed to pop the scope from an empty stack. "
+ "`pop_scope()` should only be called once for every "
+ "`push_scope()`",
+ ) from None
+
+ @property
+ def resolution_scope(self):
+ """
+ Retrieve the current resolution scope.
+ """
+ return self._scopes_stack[-1]
+
+ @property
+ def base_uri(self):
+ """
+ Retrieve the current base URI, not including any fragment.
+ """
+ uri, _ = urldefrag(self.resolution_scope)
+ return uri
+
+ @contextlib.contextmanager
+ def in_scope(self, scope):
+ """
+ Temporarily enter the given scope for the duration of the context.
+
+ .. deprecated:: v4.0.0
+ """
+ warnings.warn(
+ "jsonschema.RefResolver.in_scope is deprecated and will be "
+ "removed in a future release.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ self.push_scope(scope)
+ try:
+ yield
+ finally:
+ self.pop_scope()
+
+ @contextlib.contextmanager
+ def resolving(self, ref):
+ """
+ Resolve the given ``ref`` and enter its resolution scope.
+
+ Exits the scope on exit of this context manager.
+
+ Arguments:
+
+ ref (str):
+
+ The reference to resolve
+
+ """
+ url, resolved = self.resolve(ref)
+ self.push_scope(url)
+ try:
+ yield resolved
+ finally:
+ self.pop_scope()
+
+ def _find_in_referrer(self, key):
+ return self._get_subschemas_cache()[key]
+
+ @lru_cache # noqa: B019
+ def _get_subschemas_cache(self):
+ cache = {key: [] for key in _SUBSCHEMAS_KEYWORDS}
+ for keyword, subschema in _search_schema(
+ self.referrer, _match_subschema_keywords,
+ ):
+ cache[keyword].append(subschema)
+ return cache
+
+ @lru_cache # noqa: B019
+ def _find_in_subschemas(self, url):
+ subschemas = self._get_subschemas_cache()["$id"]
+ if not subschemas:
+ return None
+ uri, fragment = urldefrag(url)
+ for subschema in subschemas:
+ id = subschema["$id"]
+ if not isinstance(id, str):
+ continue
+ target_uri = self._urljoin_cache(self.resolution_scope, id)
+ if target_uri.rstrip("/") == uri.rstrip("/"):
+ if fragment:
+ subschema = self.resolve_fragment(subschema, fragment)
+ self.store[url] = subschema
+ return url, subschema
+ return None
+
+ def resolve(self, ref):
+ """
+ Resolve the given reference.
+ """
+ url = self._urljoin_cache(self.resolution_scope, ref).rstrip("/")
+
+ match = self._find_in_subschemas(url)
+ if match is not None:
+ return match
+
+ return url, self._remote_cache(url)
+
+ def resolve_from_url(self, url):
+ """
+ Resolve the given URL.
+ """
+ url, fragment = urldefrag(url)
+ if not url:
+ url = self.base_uri
+
+ try:
+ document = self.store[url]
+ except KeyError:
+ try:
+ document = self.resolve_remote(url)
+ except Exception as exc:
+ raise exceptions._RefResolutionError(exc) from exc
+
+ return self.resolve_fragment(document, fragment)
+
+ def resolve_fragment(self, document, fragment):
+ """
+ Resolve a ``fragment`` within the referenced ``document``.
+
+ Arguments:
+
+ document:
+
+ The referent document
+
+ fragment (str):
+
+ a URI fragment to resolve within it
+
+ """
+ fragment = fragment.lstrip("/")
+
+ if not fragment:
+ return document
+
+ if document is self.referrer:
+ find = self._find_in_referrer
+ else:
+
+ def find(key):
+ yield from _search_schema(document, _match_keyword(key))
+
+ for keyword in ["$anchor", "$dynamicAnchor"]:
+ for subschema in find(keyword):
+ if fragment == subschema[keyword]:
+ return subschema
+ for keyword in ["id", "$id"]:
+ for subschema in find(keyword):
+ if "#" + fragment == subschema[keyword]:
+ return subschema
+
+ # Resolve via path
+ parts = unquote(fragment).split("/") if fragment else []
+ for part in parts:
+ part = part.replace("~1", "/").replace("~0", "~")
+
+ if isinstance(document, Sequence):
+ try: # noqa: SIM105
+ part = int(part)
+ except ValueError:
+ pass
+ try:
+ document = document[part]
+ except (TypeError, LookupError) as err:
+ raise exceptions._RefResolutionError(
+ f"Unresolvable JSON pointer: {fragment!r}",
+ ) from err
+
+ return document
+
+ def resolve_remote(self, uri):
+ """
+ Resolve a remote ``uri``.
+
+ If called directly, does not check the store first, but after
+ retrieving the document at the specified URI it will be saved in
+ the store if :attr:`cache_remote` is True.
+
+ .. note::
+
+ If the requests_ library is present, ``jsonschema`` will use it to
+ request the remote ``uri``, so that the correct encoding is
+ detected and used.
+
+ If it isn't, or if the scheme of the ``uri`` is not ``http`` or
+ ``https``, UTF-8 is assumed.
+
+ Arguments:
+
+ uri (str):
+
+ The URI to resolve
+
+ Returns:
+
+ The retrieved document
+
+ .. _requests: https://pypi.org/project/requests/
+
+ """
+ try:
+ import requests
+ except ImportError:
+ requests = None
+
+ scheme = urlsplit(uri).scheme
+
+ if scheme in self.handlers:
+ result = self.handlers[scheme](uri)
+ elif scheme in ["http", "https"] and requests:
+ # Requests has support for detecting the correct encoding of
+ # json over http
+ result = requests.get(uri).json()
+ else:
+ # Otherwise, pass off to urllib and assume utf-8
+ with urlopen(uri) as url: # noqa: S310
+ result = json.loads(url.read().decode("utf-8"))
+
+ if self.cache_remote:
+ self.store[uri] = result
+ return result
+
+
+_SUBSCHEMAS_KEYWORDS = ("$id", "id", "$anchor", "$dynamicAnchor")
+
+
+def _match_keyword(keyword):
+
+ def matcher(value):
+ if keyword in value:
+ yield value
+
+ return matcher
+
+
+def _match_subschema_keywords(value):
+ for keyword in _SUBSCHEMAS_KEYWORDS:
+ if keyword in value:
+ yield keyword, value
+
+
+def _search_schema(schema, matcher):
+ """Breadth-first search routine."""
+ values = deque([schema])
+ while values:
+ value = values.pop()
+ if not isinstance(value, dict):
+ continue
+ yield from matcher(value)
+ values.extendleft(value.values())
+
+
+def validate(instance, schema, cls=None, *args, **kwargs): # noqa: D417
+ """
+ Validate an instance under the given schema.
+
+ >>> validate([2, 3, 4], {"maxItems": 2})
+ Traceback (most recent call last):
+ ...
+ ValidationError: [2, 3, 4] is too long
+
+ :func:`~jsonschema.validators.validate` will first verify that the
+ provided schema is itself valid, since not doing so can lead to less
+ obvious error messages and fail in less obvious or consistent ways.
+
+ If you know you have a valid schema already, especially
+ if you intend to validate multiple instances with
+ the same schema, you likely would prefer using the
+ `jsonschema.protocols.Validator.validate` method directly on a
+ specific validator (e.g. ``Draft202012Validator.validate``).
+
+
+ Arguments:
+
+ instance:
+
+ The instance to validate
+
+ schema:
+
+ The schema to validate with
+
+ cls (jsonschema.protocols.Validator):
+
+ The class that will be used to validate the instance.
+
+ If the ``cls`` argument is not provided, two things will happen
+ in accordance with the specification. First, if the schema has a
+ :kw:`$schema` keyword containing a known meta-schema [#]_ then the
+ proper validator will be used. The specification recommends that
+ all schemas contain :kw:`$schema` properties for this reason. If no
+ :kw:`$schema` property is found, the default validator class is the
+ latest released draft.
+
+ Any other provided positional and keyword arguments will be passed
+ on when instantiating the ``cls``.
+
+ Raises:
+
+ `jsonschema.exceptions.ValidationError`:
+
+ if the instance is invalid
+
+ `jsonschema.exceptions.SchemaError`:
+
+ if the schema itself is invalid
+
+ .. rubric:: Footnotes
+ .. [#] known by a validator registered with
+ `jsonschema.validators.validates`
+
+ """
+ if cls is None:
+ cls = validator_for(schema)
+
+ cls.check_schema(schema)
+ validator = cls(schema, *args, **kwargs)
+ error = exceptions.best_match(validator.iter_errors(instance))
+ if error is not None:
+ raise error
+
+
+def validator_for(
+ schema,
+ default: type[Validator] | _utils.Unset = _UNSET,
+) -> type[Validator]:
+ """
+ Retrieve the validator class appropriate for validating the given schema.
+
+ Uses the :kw:`$schema` keyword that should be present in the given
+ schema to look up the appropriate validator class.
+
+ Arguments:
+
+ schema (collections.abc.Mapping or bool):
+
+ the schema to look at
+
+ default:
+
+ the default to return if the appropriate validator class
+ cannot be determined.
+
+ If unprovided, the default is to return the latest supported
+ draft.
+
+ Examples:
+
+ The :kw:`$schema` JSON Schema keyword will control which validator
+ class is returned:
+
+ >>> schema = {
+ ... "$schema": "https://json-schema.org/draft/2020-12/schema",
+ ... "type": "integer",
+ ... }
+ >>> jsonschema.validators.validator_for(schema)
+
+
+
+ Here, a draft 7 schema instead will return the draft 7 validator:
+
+ >>> schema = {
+ ... "$schema": "http://json-schema.org/draft-07/schema#",
+ ... "type": "integer",
+ ... }
+ >>> jsonschema.validators.validator_for(schema)
+
+
+
+ Schemas with no ``$schema`` keyword will fallback to the default
+ argument:
+
+ >>> schema = {"type": "integer"}
+ >>> jsonschema.validators.validator_for(
+ ... schema, default=Draft7Validator,
+ ... )
+
+
+ or if none is provided, to the latest version supported.
+ Always including the keyword when authoring schemas is highly
+ recommended.
+
+ """
+ DefaultValidator = _LATEST_VERSION if default is _UNSET else default
+
+ if schema is True or schema is False or "$schema" not in schema:
+ return DefaultValidator # type: ignore[return-value]
+ if schema["$schema"] not in _META_SCHEMAS and default is _UNSET:
+ warn(
+ (
+ "The metaschema specified by $schema was not found. "
+ "Using the latest draft to validate, but this will raise "
+ "an error in the future."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _META_SCHEMAS.get(schema["$schema"], DefaultValidator)
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/LICENSE b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..6464b02629b651454fd31f98dda5fab8fdc1da34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/LICENSE
@@ -0,0 +1,13 @@
+ Copyright 2014-2015 Michal "Mimino" Danilak
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/METADATA b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..897c4e05d6f026b5750aa1f8685a3bb382f14650
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/METADATA
@@ -0,0 +1,114 @@
+Metadata-Version: 2.1
+Name: langdetect
+Version: 1.0.9
+Summary: Language detection library ported from Google's language-detection.
+Home-page: https://github.com/Mimino666/langdetect
+Author: Michal Mimino Danilak
+Author-email: michal.danilak@gmail.com
+License: MIT
+Keywords: language detection library
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Description-Content-Type: text/markdown
+License-File: LICENSE
+License-File: NOTICE
+Requires-Dist: six
+
+langdetect
+==========
+
+[](https://travis-ci.org/Mimino666/langdetect)
+
+Port of Nakatani Shuyo's [language-detection](https://github.com/shuyo/language-detection) library (version from 03/03/2014) to Python.
+
+
+Installation
+============
+
+ $ pip install langdetect
+
+Supported Python versions 2.7, 3.4+.
+
+
+Languages
+=========
+
+``langdetect`` supports 55 languages out of the box ([ISO 639-1 codes](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)):
+
+ af, ar, bg, bn, ca, cs, cy, da, de, el, en, es, et, fa, fi, fr, gu, he,
+ hi, hr, hu, id, it, ja, kn, ko, lt, lv, mk, ml, mr, ne, nl, no, pa, pl,
+ pt, ro, ru, sk, sl, so, sq, sv, sw, ta, te, th, tl, tr, uk, ur, vi, zh-cn, zh-tw
+
+
+Basic usage
+===========
+
+To detect the language of the text:
+
+```python
+>>> from langdetect import detect
+>>> detect("War doesn't show who's right, just who's left.")
+'en'
+>>> detect("Ein, zwei, drei, vier")
+'de'
+```
+
+To find out the probabilities for the top languages:
+
+```python
+>>> from langdetect import detect_langs
+>>> detect_langs("Otec matka syn.")
+[sk:0.572770823327, pl:0.292872522702, cs:0.134356653968]
+```
+
+**NOTE**
+
+Language detection algorithm is non-deterministic, which means that if you try to run it on a text which is either too short or too ambiguous, you might get different results everytime you run it.
+
+To enforce consistent results, call following code before the first language detection:
+
+```python
+from langdetect import DetectorFactory
+DetectorFactory.seed = 0
+```
+
+How to add new language?
+========================
+
+You need to create a new language profile. The easiest way to do it is to use the [langdetect.jar](https://github.com/shuyo/language-detection/raw/master/lib/langdetect.jar) tool, which can generate language profiles from Wikipedia abstract database files or plain text.
+
+Wikipedia abstract database files can be retrieved from "Wikipedia Downloads" ([http://download.wikimedia.org/](http://download.wikimedia.org/)). They form '(language code)wiki-(version)-abstract.xml' (e.g. 'enwiki-20101004-abstract.xml' ).
+
+usage: ``java -jar langdetect.jar --genprofile -d [directory path] [language codes]``
+
+- Specify the directory which has abstract databases by -d option.
+- This tool can handle gzip compressed file.
+
+Remark: The database filename in Chinese is like 'zhwiki-(version)-abstract-zh-cn.xml' or zhwiki-(version)-abstract-zh-tw.xml', so that it must be modified 'zh-cnwiki-(version)-abstract.xml' or 'zh-twwiki-(version)-abstract.xml'.
+
+To generate language profile from a plain text, use the genprofile-text command.
+
+usage: ``java -jar langdetect.jar --genprofile-text -l [language code] [text file path]``
+
+For more details see [language-detection Wiki](https://code.google.com/archive/p/language-detection/wikis/Tools.wiki).
+
+
+Original project
+================
+
+This library is a direct port of Google's [language-detection](https://code.google.com/p/language-detection/) library from Java to Python. All the classes and methods are unchanged, so for more information see the project's website or wiki.
+
+Presentation of the language detection algorithm: [http://www.slideshare.net/shuyo/language-detection-library-for-java](http://www.slideshare.net/shuyo/language-detection-library-for-java).
+
+
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/NOTICE b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..426e35240bae5dce14757d772569a8fd94a33652
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/NOTICE
@@ -0,0 +1,10 @@
+language-detection license
+==========================
+
+ Copyright (c) 2010-2014 Cybozu Labs, Inc. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/RECORD b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..f0771ca43353f91617ef4c0d74b4cf3293b60d47
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/RECORD
@@ -0,0 +1,90 @@
+langdetect-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+langdetect-1.0.9.dist-info/LICENSE,sha256=nFOf3Ef6ThlbiO-qZJXxFGPeJx9ZyN6W_ri8nIq6sas,599
+langdetect-1.0.9.dist-info/METADATA,sha256=3XFADv7nIwyoYaRoULDMF7_V4zVGN9raOqaznxP5YP0,4355
+langdetect-1.0.9.dist-info/NOTICE,sha256=vCK61ZBzOeEoNNkfeAnsNcPET6S4EvJ06_76ON4ICGk,655
+langdetect-1.0.9.dist-info/RECORD,,
+langdetect-1.0.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+langdetect-1.0.9.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
+langdetect-1.0.9.dist-info/top_level.txt,sha256=LvrLnEzJSvBcvH6N_EyWBZh2qqP7XvpnVQEzZSpFWr8,11
+langdetect/__init__.py,sha256=-PWd_KOAfDOFbg0VvhRXlsIUBQhoHuiE_js4zaSTO8k,143
+langdetect/__pycache__/__init__.cpython-310.pyc,,
+langdetect/__pycache__/detector.cpython-310.pyc,,
+langdetect/__pycache__/detector_factory.cpython-310.pyc,,
+langdetect/__pycache__/lang_detect_exception.cpython-310.pyc,,
+langdetect/__pycache__/language.cpython-310.pyc,,
+langdetect/detector.py,sha256=XE37Ljm1QoT7NMbt-L1saiT1yF-FH1pBWrBQs7Hn_xI,8658
+langdetect/detector_factory.py,sha256=tC3yHy2LppBG6k2gid02A76A1KUkdJzk8tUOA8S4nOI,4368
+langdetect/lang_detect_exception.py,sha256=Nf6m4StZRubREdx3hDFxtkwNhM1_3JV8RwopMOoK_l4,519
+langdetect/language.py,sha256=bMhYktIJZQe-sT2xwP1nmdXdNpalB6PGmbNZU9Ef9gs,430
+langdetect/profiles/af,sha256=R_KhZPKdsCLCOskssj5e3AhYoO1c2jYaYyAzP_wsoOc,21532
+langdetect/profiles/ar,sha256=-DuS1np_ivpoeJAYlmkulm6IJHvy94tBdcjIIcUccko,35182
+langdetect/profiles/bg,sha256=sjCjH2DoBy1wFAldQUrATl575tj1NhEO9TVK1fTxERo,33520
+langdetect/profiles/bn,sha256=XR1U94BV5Zv7MyCKXm6YqVJC90qJlRQ3n1uTb91q8ik,40800
+langdetect/profiles/ca,sha256=u3cXnd3xaQKMc577Z5_slAcs6yNsvE4vyXYqj-8QqGw,69365
+langdetect/profiles/cs,sha256=yG6kFoz7MNH6agmJLs8j8HpbNs4rtmyrKbXoytDE20E,33176
+langdetect/profiles/cy,sha256=qCaiaZsUa4AAlCbAlxT17optXqmms7kfIbPlwRfTSMM,55195
+langdetect/profiles/da,sha256=xlWdr48yWutsAHhRLUkwPbeO61CBhYsGy_Glu-FReSQ,25478
+langdetect/profiles/de,sha256=m5z-FobEzjpIe5hFoWy9HDH77992hDS5WFTDUPsccqo,27502
+langdetect/profiles/el,sha256=gvIoGs9ed3CCOKaKLHsU7W2GT7JhtZyebho_y8IKMAA,35031
+langdetect/profiles/en,sha256=hX3MrlFJOSPd_c3b91cXXcA9fMq1Erm9IcW9gZEBa6Q,28154
+langdetect/profiles/es,sha256=FzWiKwinlI_rAd_Oa35cNLwAjV9oe0Crd0Z63496Zn8,25211
+langdetect/profiles/et,sha256=kOqLMxtQIUzQl2PQgi2bPS7zDJMHG853lWdeTs-cPuI,70548
+langdetect/profiles/fa,sha256=V_ScsbIOwdxyIIIP25WC4b_NpnpiySbK0LwBIngvJw0,28603
+langdetect/profiles/fi,sha256=kp0qYD4jikCTTjvbxHy7fkG6x4XNfST9s1oNZ0_WUF4,25539
+langdetect/profiles/fr,sha256=ZPsWX0xUsp9giq3GJirQi6asCcj_giciWIkcH3eFwQI,26303
+langdetect/profiles/gu,sha256=X6b-ZyiUTuzUgNkSWSr2NZPd6kq5q4EETN4F_nypfPs,21484
+langdetect/profiles/he,sha256=xC8P6DSMwT8kPZh7XamDBFpPkAnC2IRL5hL1v4dSMEU,36134
+langdetect/profiles/hi,sha256=x41iox2Pj4UkWjX1Sijdv_rufDLGJbLWBE35X6tiSsg,35727
+langdetect/profiles/hr,sha256=sjn7bIsgJilzfo00o4sHfGtmpJW-LnoHOuuuw5yC1pI,25807
+langdetect/profiles/hu,sha256=lB0gDqqBzLTj1648ktpM7y1HTOBNn43GggW09wAc4DI,31466
+langdetect/profiles/id,sha256=ba3mnT1xh7TPZGPXk_OfpsOHnDCFcPkFMfHaajNlUgQ,21559
+langdetect/profiles/it,sha256=7xB9gIwPmbQ6N6aop7xC1Ro2pOoTOiIkIp3tXgl8jHc,22799
+langdetect/profiles/ja,sha256=CozKjrOh2OcPNJPUdJYYrb5RiVSdA7-BlvGhTyRT61A,25792
+langdetect/profiles/kn,sha256=oE1TqNgoaj4sxD1x_6MT_GaHiTzcXwGJHMLiOu6-SgM,39903
+langdetect/profiles/ko,sha256=datiYixz1Ym9A0kdkTvvQt4tk0CRv52-Az4dQCF9be4,307193
+langdetect/profiles/lt,sha256=TDaVnxyYxNTmCNAvtCW60sa4TYMaVSgW1wgNYfctQfM,67770
+langdetect/profiles/lv,sha256=tR8RuNG9jWMk40DUoIF_iSp_7DFKPvK5lFgaritNMiY,74760
+langdetect/profiles/mk,sha256=nqPNjGuBMP1CbpYZ45_vWuREdh2akdXkI03CF-qVGhs,30026
+langdetect/profiles/ml,sha256=f_PX8TSCx0Tm9PqXyHmvdK44-9fFJunydk1Rzg77FUY,39692
+langdetect/profiles/mr,sha256=LdB14o1_-lRMOIuAeoQrc9XyxCkxKHVPiIdIDgI0xVA,36522
+langdetect/profiles/ne,sha256=L0NJ8eO6kmKvZrsYf0qMZ2pA0dN2prTLS1wHh4kELLc,33856
+langdetect/profiles/nl,sha256=tlDta2Oo4lX9yI7oAJMTGBmJTzjlKmm4L3t6XPLnM78,25049
+langdetect/profiles/no,sha256=R2u5lufR4gr-Xo9g8vFhzdcMyMAT1TAuZ2wZNX4v7w4,25502
+langdetect/profiles/pa,sha256=DrdTzoCZn6psP3Kq8vim6DdQ3wUfgAKYQHquqd9V3Pw,29336
+langdetect/profiles/pl,sha256=ez3sOUBkEx0jFMjlOkctAIEsqYpjIp6MHhrCOSjoI_E,30392
+langdetect/profiles/pt,sha256=jVEttZUSqcPjmCsdcgqyA5FUQOBgn7dlJOGI4y85v-k,25054
+langdetect/profiles/ro,sha256=qcyG2IAXbcEgj1sI8ziBaX8cm_iJZhP3-mQg-U48y1E,62779
+langdetect/profiles/ru,sha256=Qes9OcEukCJQ2sg91wZxEZzRXIKSm_cvv52n2cGaQ18,37609
+langdetect/profiles/sk,sha256=nhm39mmiorXls5YLY1KiM62pinQu_QiFYm64Xnxu9m4,30756
+langdetect/profiles/sl,sha256=ZOfXelP0NwvvIVE3Ps6fSmEXndMNDFc9X40ADqT1hTo,64837
+langdetect/profiles/so,sha256=rB5ucB-u207ZLCe_B_hKtBjnugi5SCwVpyyKjSfI-u4,16786
+langdetect/profiles/sq,sha256=pchluNoTeAFQixuDpGsUrngnrZNLBgE7nZUdOTWfgo4,23469
+langdetect/profiles/sv,sha256=A8N50G4b1yJclBESgpCOHTr_I23rv34Wu1YaOCMbseU,27347
+langdetect/profiles/sw,sha256=dC1vwEuEcx4Og6VtZKFQu7THrbrDADKXTRSlPrbgvHU,17714
+langdetect/profiles/ta,sha256=L3wkwPoj7PyQ39O47TrkI23BOagqNvc8kweRGLbu_8s,33182
+langdetect/profiles/te,sha256=wCXXTgivSlJBPexArdCFlQx-YCsaqZ5Tm3dRcJoc7PU,39696
+langdetect/profiles/th,sha256=iitCt8TTmHGMT87owtNKR23aKsrJu5WDvTD1CKvldkc,51598
+langdetect/profiles/tl,sha256=qT7pCw81_RTDUFDN2Y2exd_AP8sFU5N-Ca2TgAYIBs0,19009
+langdetect/profiles/tr,sha256=IY8zKLIONZ8x9dQL_zwOgIdvoe9I_qiBJF7kzhAluNY,28752
+langdetect/profiles/uk,sha256=yphYroYNbDWQDzeyRs_iP8HSzVCvXVRK5zOXaT8NeC4,33663
+langdetect/profiles/ur,sha256=MaH8gCCbNbdWS5ATgF5yIMYLrmoMlss-RlSXED66eKw,28532
+langdetect/profiles/vi,sha256=U3TzN_YKKATjPHEXzNnnbvfXKWwBE7o_YS8RKSjfKZA,67736
+langdetect/profiles/zh-cn,sha256=2hRtAvoiN2ZoGedupfmfG28NW2WI-cX4dSynmAVIa4c,27340
+langdetect/profiles/zh-tw,sha256=OypUIuhOpdUc_wFiSwhPv0pA9cZRxVB4wiE82uG51xo,27184
+langdetect/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+langdetect/tests/__pycache__/__init__.cpython-310.pyc,,
+langdetect/tests/__pycache__/test_detector.cpython-310.pyc,,
+langdetect/tests/__pycache__/test_language.cpython-310.pyc,,
+langdetect/tests/test_detector.py,sha256=H-lpXWmfZr2ndFAALKtmPMnhxq7s6tfPRvnOdj_Ob8Q,2359
+langdetect/tests/test_language.py,sha256=dj_0RrKR_-CbQvKgVEk5hdCnDkiOgY2u3sRW8qSIIGs,680
+langdetect/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+langdetect/utils/__pycache__/__init__.cpython-310.pyc,,
+langdetect/utils/__pycache__/lang_profile.cpython-310.pyc,,
+langdetect/utils/__pycache__/messages.cpython-310.pyc,,
+langdetect/utils/__pycache__/ngram.cpython-310.pyc,,
+langdetect/utils/__pycache__/unicode_block.cpython-310.pyc,,
+langdetect/utils/lang_profile.py,sha256=FV9ffbbjz-EUuYMXYsfof6lutFuni9HVNTeZiwWKMcQ,2118
+langdetect/utils/messages.properties,sha256=CyHI1zKeUKzz3cs5BvpBLNwPfatrRJBaJ3Ft_ghu9ew,43334
+langdetect/utils/messages.py,sha256=Kyz7qFzVjO1TscjcHxL0R7DWUJMn_fMxWuna-MtIPqg,635
+langdetect/utils/ngram.py,sha256=M9AegNxoCzB7nRcY98qB7NCi1zzqgiDE-TnYkzqn9GY,10431
+langdetect/utils/unicode_block.py,sha256=bxqMT6mxRca_qQsZLr0tLGHsvE99BtrfOwvqYCy3UVg,17954
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/WHEEL b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..79d5c89a71989389294854aa34e329701325f8b0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.45.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7f42284c9dd2954b17960fbccb4c395d02ea9f47
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/langdetect-1.0.9.dist-info/top_level.txt
@@ -0,0 +1 @@
+langdetect
diff --git a/venv/lib/python3.10/site-packages/olmo/__init__.py b/venv/lib/python3.10/site-packages/olmo/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e149347650c351059dd0c49c8b2edb5c8c3ff88d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/__init__.py
@@ -0,0 +1,15 @@
+from .config import *
+from .model import *
+from .tokenizer import *
+
+
+def check_install(cuda: bool = False):
+ import torch
+
+ from .version import VERSION
+
+ if cuda:
+ assert torch.cuda.is_available(), "CUDA is not available!"
+ print("CUDA available")
+
+ print(f"OLMo v{VERSION} installed")
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9487e776049c55610415b114f15c301cb5ef74c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/aliases.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c0eb66a645a3b3035f58f8549d85332f5280b3d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/aliases.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/beam_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/beam_search.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2cf0cc43ec587fb160a9b420d585845b6ccf698a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/beam_search.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/checkpoint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67a1fb8c4d402c132354521e5591902283c9c2a2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/checkpoint.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/config.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..749823e9adcb65062031d919db3d8a596d74b2fa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/config.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/exceptions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d4113ff4a46258fa3534d264d431b680432d4f9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/exceptions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/initialization.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/initialization.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..887fbd07d41206ad75c064b83ff5088a3cafc33c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/initialization.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/model.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/model.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..981e8cd404fd128f21912e3baf1b03dde4bee94e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/model.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/optim.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/optim.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cc3d0c0e3b43b64d06369525358614aad0bb35e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/optim.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/tokenizer.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/tokenizer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17a065d90e72b6600a9ece75d1fd3d12bf57c2b0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/tokenizer.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/torch_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/torch_util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5653e390b57d3e77c7a26e109f76fc8946ac7eee
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/torch_util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/train.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/train.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bb6207950b132229d84219fc90b72c2e688d552
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/train.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..923abe503229344d5caf30eaafccd2f6d6332945
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/__pycache__/version.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..deaebfb9f311e95f0f9d166c1954da3945b54b73
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/__pycache__/version.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/aliases.py b/venv/lib/python3.10/site-packages/olmo/aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcf75db2bb63f1755803aa502320911f10d1183f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/aliases.py
@@ -0,0 +1,7 @@
+from os import PathLike
+from typing import Union
+
+__all__ = ["PathOrStr"]
+
+
+PathOrStr = Union[str, PathLike]
diff --git a/venv/lib/python3.10/site-packages/olmo/beam_search.py b/venv/lib/python3.10/site-packages/olmo/beam_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..6328bdb5dec0a924e9f926b123b68a3c8ddcf305
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/beam_search.py
@@ -0,0 +1,1078 @@
+"""
+This is a self-contained and flexible beam search implementation adapted from
+AllenNLP's beam search: https://github.com/allenai/allennlp/blob/main/allennlp/nn/beam_search.py
+"""
+
+import copy
+import warnings
+from abc import abstractmethod
+from inspect import signature
+from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, cast
+
+import torch
+
+__all__ = [
+ "Sampler",
+ "DeterministicSampler",
+ "MultinomialSampler",
+ "TopKSampler",
+ "TopPSampler",
+ "GumbelSampler",
+ "FinalSequenceScorer",
+ "SequenceLogProbabilityScorer",
+ "LengthNormalizedSequenceLogProbabilityScorer",
+ "Constraint",
+ "RepeatedNGramBlockingConstraint",
+ "BeamSearch",
+]
+
+StateType = Dict[str, torch.Tensor]
+StepFunctionTypeWithTimestep = Callable[[torch.Tensor, StateType, int], Tuple[torch.Tensor, StateType]]
+StepFunctionTypeNoTimestep = Callable[[torch.Tensor, StateType], Tuple[torch.Tensor, StateType]]
+
+StepFunctionType = TypeVar("StepFunctionType", StepFunctionTypeWithTimestep, StepFunctionTypeNoTimestep)
+"""
+The type of step function that can be passed to [`BeamSearch.search`](#search).
+
+This can either be [`StepFunctionTypeWithTimestep`](#stepfunctiontypewithtimestep)
+or [`StepFunctionTypeNoTimestep`](#stepfunctiontypenotimestep).
+"""
+
+ConstraintStateType = List[List[Dict[str, Any]]]
+
+
+class Sampler:
+ """
+ An abstract class that can be used to sample candidates (either nodes or beams)
+ within `BeamSearch`.
+
+ A `Sampler` just has three methods, `init_state()`, `sample_nodes()` and `sample_beams()`.
+
+ `init_state()` takes three arguments:
+
+ - a tensor of starting log probs with shape `(batch_size,, num_classes)`,
+ - the batch size, an int,
+ - and the number of classes, also an int.
+
+ It returns a state dictionary with any state tensors needed for subsequent
+ calls to `sample_nodes()` and `sample_beams()`.
+
+ By default this method just returns an empty dictionary.
+
+ Both `sample_nodes()` and `sample_beams()` should take three arguments:
+
+ - tensor of normalized log probabilities with shape `(batch_size, num_examples)`,
+ - an integer representing the number of samples to take for each example in the batch,
+ - and a state dictionary which could contain any tensors needed for the `Sampler` to keep
+ track of state.
+
+ For `sample_nodes()`, `num_examples = num_classes`, but for `sample_beams`,
+ `num_examples = beam_size * per_node_beam_size`.
+
+ The return value should be a tuple containing:
+
+ - a tensor of log probabilities of the sampled examples with shape `(batch_size, num_samples)`,
+ - a tensor of indices of the sampled examples with shape `(batch_size, num_samples)`,
+ - and the updated state dictionary.
+
+ A default implementation of `sample_beams` is provided, which just deterministically
+ picks the `k` examples with highest log probability.
+ """
+
+ def init_state(
+ self, start_class_log_probabilities: torch.Tensor, batch_size: int, num_classes: int
+ ) -> StateType:
+ del start_class_log_probabilities, batch_size, num_classes
+ return {}
+
+ @abstractmethod
+ def sample_nodes(
+ self, log_probs: torch.Tensor, per_node_beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ raise NotImplementedError
+
+ def sample_beams(
+ self, log_probs: torch.Tensor, beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ del state
+ selected_log_probs, selected_indices = torch.topk(log_probs, beam_size, dim=-1)
+ return selected_log_probs, selected_indices, {}
+
+
+class DeterministicSampler(Sampler):
+ """
+ A `Sampler` that just deterministically returns the `k` nodes or beams with highest
+ log probability.
+ """
+
+ def sample_nodes(
+ self, log_probs: torch.Tensor, per_node_beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ del state
+ selected_log_probs, selected_indices = torch.topk(log_probs, per_node_beam_size, dim=-1)
+ return selected_log_probs, selected_indices, {}
+
+
+class MultinomialSampler(Sampler):
+ """
+ A `Sampler` which samples nodes from the given multinomial distribution. Beams are sampled
+ in the default, non-deterministic way.
+
+ :param temperature: A `temperature` below 1.0 produces a sharper probability distribution and a `temperature`
+ above 1.0 produces a flatter probability distribution.
+ :param with_replacement: Whether to sample with replacement.
+
+ """
+
+ def __init__(
+ self,
+ temperature: float = 1.0,
+ with_replacement: bool = False,
+ ) -> None:
+ self.temperature = temperature
+ self.with_replacement = with_replacement
+
+ def sample_nodes(
+ self, log_probs: torch.Tensor, per_node_beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ if self.temperature != 1.0:
+ _probabilities = torch.nn.functional.softmax(log_probs / self.temperature, dim=-1)
+ else:
+ _probabilities = log_probs.exp()
+
+ selected_indices = torch.multinomial(_probabilities, per_node_beam_size, replacement=self.with_replacement)
+
+ return torch.gather(log_probs, 1, selected_indices), selected_indices, state
+
+
+class TopKSampler(Sampler):
+ """
+ A `Sampler` which redistributes the probability mass function for nodes among the
+ top `k` choices, then samples from that subset after re-normalizing the probabilities.
+
+ Beams are sampled in the default, deterministic way.
+
+ :param k: The number of top choices to be selected from.
+ :param temperature: A `temperature` below 1.0 produces a sharper probability distribution and a `temperature`
+ above 1.0 produces a flatter probability distribution.
+ :param with_replacement: If set to `True`, samples will be selected with replacement from the top k choices.
+ """
+
+ def __init__(
+ self,
+ k: int = 1,
+ temperature: float = 1.0,
+ with_replacement: bool = False,
+ ):
+ self.k = k
+ self.temperature = temperature or 1.0
+ self.with_replacement = with_replacement
+
+ def sample_nodes(
+ self, log_probs: torch.Tensor, per_node_beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ if not per_node_beam_size <= self.k <= log_probs.size()[1]:
+ raise ValueError(
+ "k must be a postive integer no less than per_node_beam_size and no greater than vocabulary size"
+ )
+
+ # shape (both): (batch_size, k)
+ top_k_log_probs, top_k_indices = log_probs.topk(self.k, dim=-1)
+
+ # Apply temperature if necessary.
+ # shape: (batch_size, k)
+ if self.temperature != 1.0:
+ top_k_log_probs = top_k_log_probs / self.temperature
+
+ # Re-normalize the subset.
+ # shape: (batch_size, k)
+ normalized_top_k_probs = torch.nn.functional.softmax(top_k_log_probs, dim=-1)
+
+ # Sample from the re-normalized subset.
+ # NOTE: These indices are not indices into `log_probs`, they are indices into `top_k_log_probs`.
+ # shape: (batch_size, per_node_beam_size)
+ sampled_indices = torch.multinomial(
+ normalized_top_k_probs, per_node_beam_size, replacement=self.with_replacement
+ )
+
+ # Convert `sampled_indices` back to indices in the original `log_probs` tensor.
+ # shape: (batch_size, per_node_beam_size)
+ indices = top_k_indices.gather(-1, sampled_indices)
+
+ return log_probs.gather(1, indices), indices, state
+
+
+class TopPSampler(Sampler):
+ """
+ A `Sampler` which redistributes the probability mass function for nodes among
+ the top choices with a cumulative probability of at least `p`, then samples from that subset
+ after re-normalizing the probabilities.
+
+ Beams are sampled in the default, deterministic way.
+
+ :param p:
+ The cumulative probability cutoff threshold. A higher value of `p` will result in more possible
+ examples to sample from. If `with_replacement` is `False` and the number of possible samples is
+ insufficient to sample without replacement from when calling `sample_nodes`, then the top
+ `per_node_beam_size` examples will be chosen.
+ :param temperature:
+ A `temperature` below 1.0 produces a sharper probability distribution and a `temperature`
+ above 1.0 produces a flatter probability distribution.
+ :param with_replacement:
+ If set to `True`, samples will be selected with replacement from the top choices.
+
+ """
+
+ def __init__(
+ self,
+ p: float = 0.9,
+ temperature: float = 1.0,
+ with_replacement: bool = False,
+ ):
+ if p < 0.0 or p > 1.0:
+ raise ValueError("p must be a positive float no greater than 1.0")
+ self.p = p
+ self.temperature = temperature or 1.0
+ self.with_replacement = with_replacement
+
+ def sample_nodes(
+ self, log_probs: torch.Tensor, per_node_beam_size: int, state: StateType
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ if not per_node_beam_size <= log_probs.size()[1]:
+ raise ValueError("per_node_beam_size cannot be greater than vocabulary size")
+
+ # First apply temperature coefficient:
+ if self.temperature != 1.0:
+ _log_probs = torch.nn.functional.log_softmax(log_probs / self.temperature, dim=-1)
+ else:
+ _log_probs = log_probs
+
+ # Sort the probabilities in descending order to then find cumulative sum
+ log_probs_descending, sorting_indices = torch.sort(_log_probs, descending=True)
+
+ # shape: (batch_size, num_classes)
+ probabilities_descending = log_probs_descending.exp()
+ probabilities_summed = torch.cumsum(probabilities_descending, dim=-1)
+
+ # Create a mask for filtering out probabilities that don't make the top `p`.
+ # shape: (batch_size, num_classes)
+ exclusion_mask = probabilities_summed >= self.p
+
+ # We want to include the first index where probabilities_summed >= p, so we shift over one.
+ exclusion_mask[..., 1:] = exclusion_mask[..., :-1].clone()
+ exclusion_mask[..., 0] = False
+
+ # Make sure there's at least `per_node_beam_size` options to be selected.
+ if not self.with_replacement:
+ exclusion_mask[..., :per_node_beam_size] = False
+
+ log_probs_descending[exclusion_mask] = torch.finfo(log_probs.dtype).min
+
+ # Now re-normalized the included log probs.
+ # shape: (batch_size, num_classes)
+ filtered_probabilities = torch.nn.functional.softmax(log_probs_descending, dim=-1)
+
+ # Sample from the re-normalized subset.
+ # NOTE: These indices are not indices into `log_probs`, they are indices into `log_probs_descending`.
+ # shape: (batch_size, per_node_beam_size)
+ sampled_indices = torch.multinomial(
+ filtered_probabilities, per_node_beam_size, replacement=self.with_replacement
+ )
+
+ # Convert `sampled_indices` back to indices in the original `log_probs` tensor.
+ # shape: (batch_size, per_node_beam_size)
+ selected_indices = sorting_indices.gather(-1, sampled_indices)
+
+ # Return (selected log probabilities, selected classes)
+ # shape: (len(log_probs),1) , (len(log_probs), 1)
+ return torch.gather(log_probs, 1, selected_indices), selected_indices, state
+
+
+class GumbelSampler(Sampler):
+ """
+ A `Sampler` which uses the Gumbel-Top-K trick to sample without replacement. See
+ [*Stochastic Beams and Where to Find Them: The Gumbel-Top-k Trick for Sampling
+ Sequences Without Replacement*, W Kool, H Van Hoof and M Welling, 2010]
+ (https://api.semanticscholar.org/CorpusID:76662039).
+
+ :param temperature: A `temperature` below 1.0 produces a sharper probability distribution and a `temperature`
+ above 1.0 produces a flatter probability distribution.
+ """
+
+ def __init__(self, temperature: float = 1.0):
+ self.temperature = temperature
+
+ def init_state(
+ self, start_class_log_probabilities: torch.Tensor, batch_size: int, num_classes: int
+ ) -> StateType:
+ # shape: (batch_size, num_classes)
+ zeros = start_class_log_probabilities.new_zeros((batch_size, num_classes))
+
+ # shape: (batch_size, num_classes)
+ G_phi_S = self.gumbel_with_max(start_class_log_probabilities, zeros)
+
+ return {"G_phi_S": G_phi_S}
+
+ def sample_nodes(
+ self,
+ log_probs: torch.Tensor,
+ per_node_beam_size: int,
+ state: StateType,
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ # First apply temperature coefficient:
+ # shape: (batch_size * beam_size, num_classes)
+ if self.temperature != 1.0:
+ _log_probs = torch.nn.functional.log_softmax(log_probs / self.temperature, dim=-1)
+ else:
+ _log_probs = log_probs
+
+ # shape: (group_size,)
+ phi_S = state["phi_S"]
+
+ # shape: (group_size, num_classes)
+ phi_S = phi_S.unsqueeze(-1).expand_as(_log_probs)
+
+ # shape: (group_size, num_classes)
+ phi_S_new = phi_S + _log_probs
+
+ # shape: (group_size, 1)
+ G_phi_S = state["G_phi_S"].unsqueeze(-1)
+
+ # shape: (group_size, num_classes)
+ G_phi_S_new = self.gumbel_with_max(phi_S_new, G_phi_S)
+
+ # Replace NaNs with very negative number.
+ # shape: (group_size, num_classes)
+ # G_phi_S_new[G_phi_S_new.isnan()] = torch.finfo(G_phi_S_new.dtype).min
+
+ # shape (both): (group_size, per_node_beam_size)
+ top_G_phi_S_new, top_indices = torch.topk(G_phi_S_new, per_node_beam_size, dim=-1)
+
+ # shape: (group_size, per_node_beam_size)
+ top_log_probs = log_probs.gather(1, top_indices)
+
+ return top_log_probs, top_indices, {"G_phi_S": top_G_phi_S_new}
+
+ def sample_beams(
+ self,
+ log_probs: torch.Tensor,
+ beam_size: int,
+ state: StateType,
+ ) -> Tuple[torch.Tensor, torch.Tensor, StateType]:
+ """
+ Returns the beams with the highest perturbed log probabilities.
+ """
+ # shape (log_probs): (batch_size, beam_size * per_node_beam_size)
+
+ batch_size = log_probs.size()[0]
+
+ # shape: (batch_size * beam_size, per_node_beam_size)
+ G_phi_S = state["G_phi_S"]
+
+ # shape: (batch_size, beam_size * per_node_beam_size)
+ G_phi_S = G_phi_S.reshape_as(log_probs)
+
+ # shape (both): (batch_size, beam_size)
+ G_phi_S_new, selected_indices = torch.topk(G_phi_S, beam_size, dim=-1)
+
+ # shape: (batch_size, beam_size)
+ selected_log_probs = log_probs.gather(1, selected_indices)
+
+ # Now sort the selected beams by their true log prob.
+ # shape (all): (batch_size, beam_size)
+ selected_log_probs, sort_indices = selected_log_probs.sort(dim=-1, descending=True)
+ selected_indices = selected_indices.gather(1, sort_indices)
+ G_phi_S_new = G_phi_S_new.gather(1, sort_indices)
+
+ # shape: (batch_size * beam_size,)
+ G_phi_S_new = G_phi_S_new.reshape(batch_size * beam_size)
+
+ # shape: (batch_size * beam_size,)
+ phi_S = selected_log_probs.reshape(batch_size * beam_size)
+
+ return selected_log_probs, selected_indices, {"G_phi_S": G_phi_S_new, "phi_S": phi_S}
+
+ def gumbel(self, phi) -> torch.Tensor:
+ """
+ Sample `Gumbel(phi)`.
+
+ `phi` should have shape `(batch_size, num_classes)`.
+ """
+ return -torch.log(-torch.log(torch.rand_like(phi))) + phi
+
+ def gumbel_with_max(self, phi, T) -> torch.Tensor:
+ """
+ Sample `Gumbel(phi)` conditioned on the maximum value being equal to `T`.
+
+ `phi` should have shape `(batch_size, num_classes)` and `T` should have
+ shape `(batch_size, 1)`.
+ """
+ # Shape: (batch_size, num_classes)
+ G_phi = self.gumbel(phi)
+
+ # Now we find the maximum from these samples.
+ # Shape: (batch_size, )
+ Z, _ = G_phi.max(dim=-1)
+
+ # Shape: (batch_size, num_classes)
+ v = T - G_phi + torch.log1p(-torch.exp(G_phi - Z.unsqueeze(-1)))
+
+ # Shape: (batch_size, num_classes)
+ return T - torch.nn.functional.relu(v) - torch.log1p(torch.exp(-v.abs()))
+
+
+class FinalSequenceScorer:
+ """
+ An abstract class that can be used to score the final generated sequences found
+ by beam search. Given the predicted sequences and the corresponding log probabilities of
+ those sequences, the class calculates and returns the final score of the sequences.
+
+ The default implementation scores the sequences using the sum of the log probabilities of
+ the sequence, which is passed as input.
+ """
+
+ @abstractmethod
+ def score(self, predictions: torch.Tensor, log_probabilities: torch.Tensor, end_index: int) -> torch.Tensor:
+ """
+ Score the final predictions found by beam search.
+ Returns a tensor of the final sequence scores of shape `(batch_size, beam_size)`.
+
+ :param predictions: A tensor containing the initial predictions with shape `(batch_size, beam_size, max_steps)`.
+ :param log_probabilities: A tensor containing the log probabilities of the sequence, defined as the sum
+ of the log probabilities per token, with shape `(batch_size, beam_size)`.
+ :param end_index: The index of the end symbol.
+
+ """
+ raise NotImplementedError
+
+
+class SequenceLogProbabilityScorer(FinalSequenceScorer):
+ """
+ A :class:`FinalSequenceScorer` which scores the sequences by the sum of the log probabilities
+ across the sequence's tokens.
+ """
+
+ def score(self, predictions: torch.Tensor, log_probabilities: torch.Tensor, end_index: int) -> torch.Tensor:
+ del predictions, end_index
+ # The sum of the sequence log probabilities is the input parameter, so just
+ # return it.
+ return log_probabilities
+
+
+class LengthNormalizedSequenceLogProbabilityScorer(FinalSequenceScorer):
+ """
+ A :class:`FinalSequenceScorer` which scores the sequences by the average log probability of the
+ tokens in the sequence. It optionally includes a length penalty which promotes
+ or demotes sequences based on their lengths. The final score for a sequence will
+ be `(sequence_log_probability) / (sequence_length ** length_penalty)`. The sequence length
+ here includes the end token.
+
+ :param length_penalty: The length penalty to use. A value of 1.0 means no length penalty is used.
+ A value > 1.0 favors longer sequences, and < 1.0 favors shorter sequences.
+ """
+
+ def __init__(self, length_penalty: float = 1.0):
+ super().__init__()
+ self.length_penalty = length_penalty
+
+ def score(self, predictions: torch.Tensor, log_probabilities: torch.Tensor, end_index: int) -> torch.Tensor:
+ # shape: (batch_size, beam_size)
+ lengths = (predictions != end_index).long().sum(dim=2)
+
+ # If the sequence ended during beam search, the `log_probabilities` will include
+ # the transition to the end token. Therefore, in such situations, `lengths` is
+ # actually off by 1. This corrects for that.
+ # shape: (batch_size, beam_size)
+ is_end_token = predictions[:, :, -1] == end_index
+ lengths += is_end_token.long()
+
+ # shape: (batch_size, beam_size)
+ average_log_probs = log_probabilities / (lengths**self.length_penalty)
+ return average_log_probs
+
+
+class Constraint:
+ """
+ An abstract class that can be used to enforce constraints on the output predictions
+ by manipulating the class log probabilities during beam search.
+
+ A `Constraint` just has three methods that need to be implemented by subclasses:
+ `init_state()`, `apply()` and `_update_state()`.
+
+ `init_state()` takes one argument:
+
+ - the batch size, an int
+
+ It returns a constraint state, which is a nested list of dictionaries, with any state needed for subsequent
+ calls to `apply()` and `update_state()`. The length of the outer list should be equal to `batch_size`.
+ Each inner list should be of length 1.
+
+ `apply()` takes two arguments:
+
+ - the constraint state, which is a nested list of dictionaries. The length of the outer list is `batch_size`
+ and the length of each inner list is `beam_size` except on the first time `apply()` is called when it is 1.
+ - `class_log_probabilities`, a tensor of shape `(batch_size, beam_size, num_classes)` that contains the
+ log probabilities for the classes during search. The first time `apply()` is called, `beam_size = 1`.
+
+ The `apply()` method should return new `class_log_probabilities` that enforce the constraint
+ for this step of beam search. For instance, it may prevent a specific class from being selected by setting
+ the corresponding log probability to a negligible value such as `float("-inf")` or
+ `torch.finfo(class_log_probabilities.dtype).min`.
+
+ `_update_state()` takes two arguments:
+
+ - the copied parent constraint state, which is a nested list of dictionaries. `state[i][j]` contains the
+ copied state for the parent of `last_prediction[i, j]`. It is unique to that batch and beam, so it can be
+ directly edited in-place without affecting the others.
+ - last_prediction, a tensor of shape `(batch_size, beam_size)` containing the predictions from the last
+ step of beam search.
+
+ The `_update_state()` function should return a new constraint state, a nested list of dictionaries of
+ length `batch_size` and inner list of length `beam_size`, one for each of the predictions in `last_prediction`.
+
+ """
+
+ @abstractmethod
+ def init_state(
+ self,
+ batch_size: int,
+ ) -> ConstraintStateType:
+ raise NotImplementedError
+
+ @abstractmethod
+ def apply(
+ self,
+ state: ConstraintStateType,
+ class_log_probabilities: torch.Tensor,
+ ) -> torch.Tensor:
+ raise NotImplementedError
+
+ @staticmethod
+ def _copy_state(
+ state: ConstraintStateType,
+ batch_size: int,
+ beam_size: int,
+ last_backpointer: Optional[torch.Tensor] = None,
+ ) -> ConstraintStateType:
+ """
+ Copies the `state` . This method copies the data in `state` using `copy.deepcopy()`. If this
+ is not appropriate for your constraint, you will need to implement the copying yourself.
+ """
+ new_state = []
+ for i in range(batch_size):
+ batch_state = []
+ for j in range(beam_size):
+ if last_backpointer is None:
+ # This is the first prediction, so the backpointer is 0
+ backpointer = 0
+ else:
+ backpointer = last_backpointer[i, j].item()
+ batch_state.append(copy.deepcopy(state[i][backpointer])) # type: ignore
+ new_state.append(batch_state)
+ return new_state
+
+ def update_state(
+ self,
+ state: ConstraintStateType,
+ last_prediction: torch.Tensor,
+ last_backpointer: Optional[torch.Tensor] = None,
+ ) -> ConstraintStateType:
+ batch_size, beam_size = last_prediction.size()
+ new_state = self._copy_state(state, batch_size, beam_size, last_backpointer)
+ return self._update_state(new_state, last_prediction)
+
+ @abstractmethod
+ def _update_state(
+ self,
+ state: ConstraintStateType,
+ last_prediction: torch.Tensor,
+ ) -> ConstraintStateType:
+ raise NotImplementedError
+
+
+class RepeatedNGramBlockingConstraint(Constraint):
+ def __init__(self, ngram_size: int, **kwargs) -> None:
+ super().__init__(**kwargs)
+ self.ngram_size = ngram_size
+
+ def init_state(
+ self,
+ batch_size: int,
+ ) -> ConstraintStateType:
+ return [[{"seen_ngrams": {}, "current_prefix": []}] for _ in range(batch_size)]
+
+ def apply(
+ self,
+ state: ConstraintStateType,
+ class_log_probabilities: torch.Tensor,
+ ) -> torch.Tensor:
+ for i, batch in enumerate(state):
+ for j, beam in enumerate(batch):
+ current_prefix = tuple(beam["current_prefix"])
+ seen_ngrams = beam["seen_ngrams"]
+ try:
+ disallowed_indices = seen_ngrams[current_prefix]
+ class_log_probabilities[i, j, disallowed_indices] = torch.finfo(
+ class_log_probabilities.dtype
+ ).min
+ except KeyError:
+ # We have not seen this prefix before, so there is no index
+ # that needs to be blocked
+ pass
+ return class_log_probabilities
+
+ def _update_state(
+ self,
+ state: ConstraintStateType,
+ last_prediction: torch.Tensor,
+ ) -> ConstraintStateType:
+ for i, batch in enumerate(state):
+ for j, beam in enumerate(batch):
+ prediction = last_prediction[i, j].item()
+ prefix = beam["current_prefix"]
+ seen_ngrams = beam["seen_ngrams"]
+
+ if len(prefix) == self.ngram_size - 1:
+ # This is a new ngram that we have to remember
+ if tuple(prefix) not in seen_ngrams:
+ seen_ngrams[tuple(prefix)] = []
+ seen_ngrams[tuple(prefix)].append(prediction)
+
+ # Create the new prefix, removing the oldest index if the prefix
+ # is too long
+ prefix.append(prediction)
+ if len(prefix) == self.ngram_size:
+ prefix.pop(0)
+ return state
+
+
+class BeamSearch:
+ """
+ Implements the beam search algorithm for decoding the most likely sequences.
+
+ :param end_index: The index of the "stop" or "end" token in the vocabulary. Usually the EOS token ID.
+
+ :param max_steps: The maximum number of decoding steps to take, i.e. the maximum length
+ of the predicted sequences.
+
+ :param beam_size: The width of the beam used.
+
+ :param per_node_beam_size: The maximum number of candidates to consider per node, at each step in the search.
+ If not given, this just defaults to `beam_size`. Setting this parameter
+ to a number smaller than `beam_size` may give better results, as it can introduce
+ more diversity into the search. See
+ [*Beam Search Strategies for Neural Machine Translation*, Freitag and Al-Onaizan, 2017]
+ (https://api.semanticscholar.org/CorpusID:2229477).
+
+ :param sampler: An optional `Sampler` which is used to pick next candidate nodes and beams.
+ If not specified, `DeterministicSampler` will be used, which just takes the
+ `per_node_beam_size` most likely nodes and the `beam_size` most likely beams.
+
+ Using the [`GumbelSampler`](#gumbelsampler), on the other hand, will give you
+ [Stochastic Beam Search](https://api.semanticscholar.org/CorpusID:76662039).
+
+ :param min_steps: The minimum number of decoding steps to take, i.e. the minimum length of
+ the predicted sequences. This does not include the start or end tokens. If `None`,
+ no minimum is enforced.
+
+ :param final_sequence_scorer: An optional `FinalSequenceScorer` which is used to score the final generated sequences.
+ The output from this module is what is returned by the `search` method. If not
+ specified, `SequenceLogProbabilityScorer` will be used, which scores the sequences
+ by the sum of the token log probabilities.
+
+ :param constraints: An optional list of `Constraint`s which should be applied during beam search. If not
+ provided, no constraints will be enforced.
+
+ """
+
+ def __init__(
+ self,
+ end_index: int,
+ *,
+ max_steps: int = 50,
+ beam_size: int = 10,
+ per_node_beam_size: Optional[int] = None,
+ sampler: Optional[Sampler] = None,
+ min_steps: Optional[int] = None,
+ final_sequence_scorer: Optional[FinalSequenceScorer] = None,
+ constraints: Optional[List[Constraint]] = None,
+ ) -> None:
+ if not max_steps > 0:
+ raise ValueError("max_steps must be positive")
+ if not beam_size > 0:
+ raise ValueError("beam_size must be positive")
+ if per_node_beam_size is not None and not per_node_beam_size > 0:
+ raise ValueError("per_node_beam_size must be positive")
+ if min_steps is not None:
+ if not min_steps >= 0:
+ raise ValueError("min_steps must be non-negative")
+ if not min_steps <= max_steps:
+ raise ValueError("min_steps must be less than or equal to max_steps")
+
+ self._end_index = end_index
+ self.max_steps = max_steps
+ self.beam_size = beam_size
+ self.per_node_beam_size = per_node_beam_size or beam_size
+ self.sampler = sampler or DeterministicSampler()
+ self.min_steps = min_steps or 0
+ self.final_sequence_scorer = final_sequence_scorer or SequenceLogProbabilityScorer()
+ self.constraints = constraints or []
+
+ @staticmethod
+ def _reconstruct_sequences(predictions, backpointers):
+ # Reconstruct the sequences.
+ # shape: [(batch_size, beam_size, 1)]
+ reconstructed_predictions = [predictions[-1].unsqueeze(2)]
+
+ if not backpointers:
+ return reconstructed_predictions
+
+ # shape: (batch_size, beam_size)
+ cur_backpointers = backpointers[-1]
+
+ for timestep in range(len(predictions) - 2, 0, -1):
+ # shape: (batch_size, beam_size, 1)
+ cur_preds = predictions[timestep].gather(1, cur_backpointers).unsqueeze(2)
+
+ reconstructed_predictions.append(cur_preds)
+
+ # shape: (batch_size, beam_size)
+ cur_backpointers = backpointers[timestep - 1].gather(1, cur_backpointers)
+
+ # shape: (batch_size, beam_size, 1)
+ final_preds = predictions[0].gather(1, cur_backpointers).unsqueeze(2)
+
+ reconstructed_predictions.append(final_preds)
+
+ return reconstructed_predictions
+
+ def search(
+ self,
+ start_predictions: torch.Tensor,
+ start_state: StateType,
+ step: StepFunctionType,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Given a starting state and a step function, apply beam search to find the
+ most likely target sequences.
+
+ Returns a tuple of `(predictions, final_scores)`, where `predictions`
+ has shape `(batch_size, beam_size, max_steps)` and `final_scores`
+ has shape `(batch_size, beam_size)`.
+
+ .. note::
+ If your step function returns `-inf` for some log probabilities
+ (like if you're using a masked log-softmax) then some of the "best"
+ sequences returned may also have `-inf` log probability. Specifically
+ this happens when the beam size is smaller than the number of actions
+ with finite log probability (non-zero probability) returned by the step function.
+ Therefore if you're using a mask you may want to check the results from `search`
+ and potentially discard sequences with non-finite log probability.
+
+ :param start_predictions: A tensor containing the initial predictions with shape `(batch_size,)`.
+ Usually the initial predictions are just the index of the "start" token
+ in the target vocabulary.
+
+ :param start_state: The initial state passed to the `step` function. Each value of the state dict
+ should be a tensor of shape `(batch_size, *)`, where `*` means any other
+ number of dimensions.
+
+ :param step: A function that is responsible for computing the next most likely tokens,
+ given the current state and the predictions from the last time step.
+ The function should accept two or three arguments:
+
+ - a tensor of shape `(group_size,)` or representing the index of the predicted
+ tokens from the last time step,
+ - the current state, a `StateType`, and
+ - optionally, the timestep, an `int`.
+
+ The `group_size` will be `batch_size * beam_size`, except in the initial
+ step, for which it will just be `batch_size`.
+
+ The function is expected to return a tuple, where the first element
+ is a tensor of shape `(group_size, vocab_size)` containing
+ the log probabilities of the tokens for the next step, and the second
+ element is the updated state. The tensor in the state should have shape
+ `(group_size, *)`, where `*` means any other number of dimensions.
+
+ """
+ step_signature = signature(step)
+ if len(step_signature.parameters) < 3:
+ # If the step function we're given does not take the time step argument, wrap it
+ # in one that does.
+ old_step = cast(StepFunctionTypeNoTimestep, step)
+
+ def new_step(last_predictions: torch.Tensor, state: Dict[str, torch.Tensor], time_step: int):
+ del time_step
+ return old_step(last_predictions, state)
+
+ return self._search(start_predictions, start_state, new_step)
+ else:
+ return self._search(start_predictions, start_state, cast(StepFunctionTypeWithTimestep, step))
+
+ def _search(
+ self,
+ start_predictions: torch.Tensor,
+ start_state: StateType,
+ step: StepFunctionTypeWithTimestep,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ batch_size = start_predictions.size()[0]
+
+ # List of (batch_size, beam_size) tensors. One for each time step. Does not
+ # include the start symbols, which are implicit.
+ predictions: List[torch.Tensor] = []
+
+ # List of (batch_size, beam_size) tensors. One for each time step. None for
+ # the first. Stores the index n for the parent prediction, i.e.
+ # predictions[t-1][i][n], that it came from.
+ backpointers: List[torch.Tensor] = []
+
+ constraint_states = [constraint.init_state(batch_size) for constraint in self.constraints]
+
+ # Calculate the first timestep. This is done outside the main loop
+ # because we are going from a single decoder input (the output from the
+ # encoder) to the top `beam_size` decoder outputs. On the other hand,
+ # within the main loop we are going from the `beam_size` elements of the
+ # beam to `beam_size`^2 candidates from which we will select the top
+ # `beam_size` elements for the next iteration.
+ # shape: (batch_size, num_classes)
+ start_class_log_probabilities, state = step(start_predictions, start_state, 0)
+
+ num_classes = start_class_log_probabilities.size()[1]
+
+ # Make sure `per_node_beam_size` is not larger than `num_classes`.
+ if self.per_node_beam_size > num_classes:
+ raise ValueError(
+ f"Vocab size ({num_classes:d}) too small "
+ f"relative to per_node_beam_size ({self.per_node_beam_size:d}).\n"
+ f"Please decrease beam_size or per_node_beam_size."
+ )
+
+ sampler_state = self.sampler.init_state(start_class_log_probabilities, batch_size, num_classes)
+
+ # Apply all constraints.
+ if self.constraints:
+ # shape: (batch_size, 1, num_classes)
+ expanded_start_class_log_probabilities = start_class_log_probabilities.unsqueeze(1)
+ for constraint, constraint_state in zip(self.constraints, constraint_states):
+ expanded_start_class_log_probabilities = constraint.apply(
+ constraint_state, expanded_start_class_log_probabilities
+ )
+ start_class_log_probabilities = expanded_start_class_log_probabilities.squeeze(1)
+
+ # Prevent selecting the end symbol if there is any min_steps constraint
+ if self.min_steps >= 1:
+ start_class_log_probabilities[:, self._end_index] = torch.finfo(
+ start_class_log_probabilities.dtype
+ ).min
+
+ # Get the initial predicted classed and their log probabilities.
+ # shape: (batch_size, beam_size), (batch_size, beam_size)
+ (
+ start_top_log_probabilities,
+ start_predicted_classes,
+ sampler_state,
+ ) = self.sampler.sample_beams(start_class_log_probabilities, self.beam_size, sampler_state)
+
+ if self.beam_size == 1 and (start_predicted_classes == self._end_index).all():
+ warnings.warn(
+ "Empty sequences predicted. You may want to increase the beam size or ensure "
+ "your step function is working properly.",
+ RuntimeWarning,
+ )
+ return start_predicted_classes.unsqueeze(-1), start_top_log_probabilities
+
+ # The log probabilities for the last time step.
+ # shape: (batch_size, beam_size)
+ last_log_probabilities = start_top_log_probabilities
+
+ # shape: [(batch_size, beam_size)]
+ predictions.append(start_predicted_classes)
+
+ # Log probability tensor that mandates that the end token is selected.
+ # shape: (batch_size * beam_size, num_classes)
+ log_probs_after_end = start_class_log_probabilities.new_full(
+ (batch_size * self.beam_size, num_classes),
+ torch.finfo(start_class_log_probabilities.dtype).min,
+ )
+ log_probs_after_end[:, self._end_index] = 0.0
+
+ # Set the same state for each element in the beam.
+ self._update_initial_state(state, batch_size)
+
+ for i, constraint in enumerate(self.constraints):
+ constraint_states[i] = constraint.update_state(constraint_states[i], start_predicted_classes)
+
+ for timestep in range(self.max_steps - 1):
+ # shape: (batch_size * beam_size,)
+ last_predictions = predictions[-1].reshape(batch_size * self.beam_size)
+
+ # If every predicted token from the last step is `self._end_index`,
+ # then we can stop early.
+ if (last_predictions == self._end_index).all():
+ break
+ # Take a step. This get the predicted log probs of the next classes
+ # and updates the state.
+ # shape: (batch_size * beam_size, num_classes)
+ class_log_probabilities, state = step(last_predictions, state, timestep + 1)
+
+ # Apply all constraints.
+ if self.constraints:
+ # shape: (batch_size, beam_size, num_classes)
+ reshaped_class_log_probabilities = class_log_probabilities.view(batch_size, self.beam_size, -1)
+ for constraint, constraint_state in zip(self.constraints, constraint_states):
+ reshaped_class_log_probabilities = constraint.apply(
+ constraint_state, reshaped_class_log_probabilities
+ )
+ # shape: (batch_size * beam_size, num_classes)
+ class_log_probabilities = reshaped_class_log_probabilities.view(batch_size * self.beam_size, -1)
+
+ # The `timestep`-th iteration of the for loop is generating the `timestep + 2`-th token
+ # of the sequence (because `timestep` is 0-indexed and we generated the first token
+ # before the for loop). Here we block the end index if the search is not allowed to
+ # terminate on this iteration.
+ if timestep + 2 <= self.min_steps:
+ class_log_probabilities[:, self._end_index] = torch.finfo(class_log_probabilities.dtype).min
+
+ # shape: (batch_size * beam_size, num_classes)
+ last_predictions_expanded = last_predictions.unsqueeze(-1).expand(
+ batch_size * self.beam_size, num_classes
+ )
+
+ # Here we are finding any beams where we predicted the end token in
+ # the previous timestep and replacing the distribution with a
+ # one-hot distribution, forcing the beam to predict the end token
+ # this timestep as well.
+ # shape: (batch_size * beam_size, num_classes)
+ cleaned_log_probabilities = torch.where(
+ last_predictions_expanded == self._end_index,
+ log_probs_after_end,
+ class_log_probabilities,
+ )
+
+ # shape (both): (batch_size * beam_size, per_node_beam_size)
+ top_log_probabilities, predicted_classes, sampler_state = self.sampler.sample_nodes(
+ cleaned_log_probabilities, self.per_node_beam_size, sampler_state
+ )
+
+ # Here we expand the last log probabilities to (batch_size * beam_size, per_node_beam_size)
+ # so that we can add them to the current log probs for this timestep.
+ # This lets us maintain the log probability of each element on the beam.
+ # shape: (batch_size * beam_size, per_node_beam_size)
+ expanded_last_log_probabilities = (
+ last_log_probabilities.unsqueeze(2)
+ .expand(batch_size, self.beam_size, self.per_node_beam_size)
+ .reshape(batch_size * self.beam_size, self.per_node_beam_size)
+ )
+
+ # shape: (batch_size * beam_size, per_node_beam_size)
+ summed_top_log_probabilities = top_log_probabilities + expanded_last_log_probabilities
+
+ # shape: (batch_size, beam_size * per_node_beam_size)
+ reshaped_summed = summed_top_log_probabilities.reshape(
+ batch_size, self.beam_size * self.per_node_beam_size
+ )
+
+ # shape: (batch_size, beam_size * per_node_beam_size)
+ reshaped_predicted_classes = predicted_classes.reshape(
+ batch_size, self.beam_size * self.per_node_beam_size
+ )
+
+ # Keep only the top `beam_size` beam indices.
+ # shape (both): (batch_size, beam_size)
+ (
+ restricted_beam_log_probs,
+ restricted_beam_indices,
+ sampler_state,
+ ) = self.sampler.sample_beams(reshaped_summed, self.beam_size, sampler_state)
+
+ # Use the beam indices to extract the corresponding classes.
+ # shape: (batch_size, beam_size)
+ restricted_predicted_classes = reshaped_predicted_classes.gather(1, restricted_beam_indices)
+
+ predictions.append(restricted_predicted_classes)
+
+ # shape: (batch_size, beam_size)
+ last_log_probabilities = restricted_beam_log_probs
+
+ # The beam indices come from a `beam_size * per_node_beam_size` dimension where the
+ # indices with a common ancestor are grouped together. Hence
+ # dividing by per_node_beam_size gives the ancestor. (Note that this is integer
+ # division as the tensor is a LongTensor.)
+ # shape: (batch_size, beam_size)
+ backpointer = torch.divide(restricted_beam_indices, self.per_node_beam_size, rounding_mode="trunc")
+ backpointers.append(backpointer)
+
+ # Keep only the pieces of the state tensors corresponding to the
+ # ancestors created this iteration.
+ self._update_state(state, backpointer)
+
+ for i, constraint in enumerate(self.constraints):
+ constraint_states[i] = constraint.update_state(
+ constraint_states[i], restricted_predicted_classes, last_backpointer=backpointer
+ )
+
+ # Warn about "-inf" log probabilities if not using any constraints (negligible
+ # log probabilities are expected when using constraints).
+ if not self.constraints and (
+ not torch.isfinite(last_log_probabilities).all()
+ or (last_log_probabilities == torch.finfo(last_log_probabilities.dtype).min).any()
+ ):
+ warnings.warn(
+ "Negligible log probabilities encountered ('-inf' or equivalent). "
+ "Some final sequences may not make sense. "
+ "This can happen when the beam size is larger than the number of valid (non-zero "
+ "probability) transitions that the step function produces.",
+ RuntimeWarning,
+ )
+
+ reconstructed_predictions = self._reconstruct_sequences(predictions, backpointers)
+
+ # shape: (batch_size, beam_size, max_steps)
+ all_predictions = torch.cat(list(reversed(reconstructed_predictions)), 2)
+
+ # Calculate the final sequence scores
+ # shape: (batch_size, beam_size)
+ final_scores = self.final_sequence_scorer.score(all_predictions, last_log_probabilities, self._end_index)
+
+ # Sort the sequences based on the final scores so the best scoring
+ # sequence is at index 0
+ sorted_final_scores, sorted_indices = torch.sort(final_scores, dim=1, descending=True)
+ sorted_all_predictions = torch.gather(
+ all_predictions, 1, sorted_indices.unsqueeze(-1).expand_as(all_predictions)
+ )
+
+ return sorted_all_predictions, sorted_final_scores
+
+ def _update_initial_state(self, state: StateType, batch_size: int):
+ """
+ Expand tensors in a state dictionary from `(batch_size, *)` to `(batch_size * beam_size, *)`.
+ """
+ for key, state_tensor in state.items():
+ if state_tensor is None:
+ continue
+ # shape: (batch_size * beam_size, *)
+ _, *last_dims = state_tensor.size()
+ state[key] = (
+ state_tensor.unsqueeze(1)
+ .expand(batch_size, self.beam_size, *last_dims)
+ .reshape(batch_size * self.beam_size, *last_dims)
+ )
+
+ def _update_state(self, state: StateType, backpointer: torch.Tensor):
+ batch_size = backpointer.size()[0]
+
+ for key, state_tensor in state.items():
+ if state_tensor is None:
+ continue
+ _, *last_dims = state_tensor.size()
+ # shape: (batch_size, beam_size, *)
+ expanded_backpointer = backpointer.view(batch_size, self.beam_size, *([1] * len(last_dims))).expand(
+ batch_size, self.beam_size, *last_dims
+ )
+ # shape: (batch_size * beam_size, *)
+ state[key] = (
+ state_tensor.reshape(batch_size, self.beam_size, *last_dims)
+ .gather(1, expanded_backpointer)
+ .reshape(batch_size * self.beam_size, *last_dims)
+ )
diff --git a/venv/lib/python3.10/site-packages/olmo/checkpoint.py b/venv/lib/python3.10/site-packages/olmo/checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0ce9ded41d51e659cbdd1b987507040f08fea89
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/checkpoint.py
@@ -0,0 +1,1474 @@
+import gc
+import io
+import logging
+import pickle
+import shutil
+from abc import ABCMeta, abstractmethod
+from collections import defaultdict
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import dataclass, field, replace
+from functools import reduce
+from pathlib import Path
+from typing import Any, Dict, Generator, List, Optional, Set, Tuple, cast
+
+import numpy as np
+import torch
+import torch.distributed.checkpoint as dist_cp
+from numpy import ndarray
+from packaging import version
+from torch.distributed import _remote_device
+from torch.distributed._shard._utils import narrow_tensor_by_index
+from torch.distributed._shard.metadata import ShardMetadata
+from torch.distributed._shard.sharded_tensor import ShardedTensor
+from torch.distributed.checkpoint.filesystem import WriteResult, _StorageInfo
+from torch.distributed.checkpoint.metadata import Metadata, MetadataIndex
+from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
+from torch.distributed.checkpoint.planner import LoadItemType, ReadItem
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+from torch.distributed.fsdp import StateDictType
+from torch.distributed.fsdp.api import (
+ FullOptimStateDictConfig,
+ FullStateDictConfig,
+ ShardedOptimStateDictConfig,
+ ShardedStateDictConfig,
+)
+from torch.distributed.fsdp.flat_param import FlatParamHandle
+from torch.futures import Future
+
+from .aliases import PathOrStr
+from .config import BaseConfig, ShardedCheckpointerType, TrainConfig
+from .optim import Optimizer, fix_optim_state_dict
+from .torch_util import (
+ barrier,
+ get_fs_local_rank,
+ get_global_rank,
+ get_local_rank,
+ get_local_world_size,
+ get_world_size,
+)
+from .util import (
+ default_thread_count,
+ dir_is_empty,
+ get_bytes_range,
+ get_progress_bar,
+ resource_path,
+ upload,
+ wait_for,
+)
+
+__all__ = [
+ "save_fsdp_model_and_optim_state",
+ "load_fsdp_model_and_optim_state",
+ "load_fsdp_optim_state",
+ "save_state_dict",
+ "load_state_dict",
+ "load_model_state",
+ "RemoteFileSystemWriter",
+ "RemoteFileSystemReader",
+ "Checkpointer",
+ "FullCheckpointer",
+ "TorchNewStyleShardedCheckpointer",
+ "TorchLegacyShardedCheckpointer",
+ "LocalShardedCheckpointer",
+ "build_sharded_checkpointer",
+]
+
+
+log = logging.getLogger(__name__)
+
+MODEL_AND_OPTIM_FOLDER = "model_and_optim"
+
+
+def save_fsdp_model_and_optim_state(
+ checkpoint_dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ upload_to: Optional[str] = None,
+ save_overwrite: bool = False,
+):
+ """
+ Use this to save a state dict for an FSDP model and its optimizer via :module:`torch.distributed.checkpoint`
+ functions. This should be used during distributed training and should be called by all ranks.
+
+ :param checkpoint_dir: The directory to save to.
+ :param fsdp_model: The FSDP model.
+ :param optim: The FSDP model's optimizer.
+ :param upload_to: Optional, a remote "directory" to upload the checkpoint files to.
+ :param save_overwrite: Overwrite existing files.
+
+ :raises FileExistsError: If a model and optim checkpoint already exists in ``checkpoint_dir`` and ``save_overwrite=False``.
+ """
+ checkpoint_dir = Path(checkpoint_dir)
+ target_dir = checkpoint_dir / MODEL_AND_OPTIM_FOLDER
+ if save_overwrite:
+ if get_fs_local_rank() == 0:
+ shutil.rmtree(target_dir, ignore_errors=True)
+ elif not dir_is_empty(target_dir):
+ raise FileExistsError(target_dir)
+ barrier()
+ if get_fs_local_rank() == 0:
+ target_dir.mkdir(exist_ok=True, parents=True)
+ barrier()
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.SHARDED_STATE_DICT,
+ state_dict_config=ShardedStateDictConfig(offload_to_cpu=True),
+ optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True),
+ ):
+ model_and_optim_state = {
+ "model": fsdp_model.state_dict(),
+ "optim": FSDP.optim_state_dict(fsdp_model, optim),
+ }
+ dist_cp.save_state_dict(
+ model_and_optim_state,
+ RemoteFileSystemWriter(
+ target_dir,
+ upload_to=None if upload_to is None else f"{upload_to.rstrip('/')}/{MODEL_AND_OPTIM_FOLDER}",
+ save_overwrite=save_overwrite,
+ ),
+ )
+
+
+def load_fsdp_model_and_optim_state(
+ checkpoint_dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+):
+ """
+ Use this to load a state dict for an FSDP model and its optimizer via :module:`torch.distributed.checkpoint`
+ functions. This should be used during distributed training and should be called by all ranks.
+
+ :param checkpoint_dir: The checkpoint directory to load from. This can be a local or remote directory.
+ :param fsdp_model: The FSDP model.
+ :param optim: The FSDP model's optimizer.
+ :param local_cache: A local cache of the checkpoint directory. Use this when the ``checkpoint_dir`` is a
+ remote "directory" but there might be a cached version of the same artifacts.
+ :param load_optimizer_state: Set to ``False`` to skip loading the optimizer state.
+
+ :raises FileNotFoundError: If the ``checkpoint_dir`` doesn't contain a model and optimizer checkpoint.
+ """
+ load_path = str(checkpoint_dir).rstrip("/")
+ local_cache = None if local_cache is None else Path(local_cache)
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.SHARDED_STATE_DICT,
+ state_dict_config=ShardedStateDictConfig(offload_to_cpu=True),
+ optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True),
+ ):
+ # Load the model state dict in place.
+ log.info("Loading model state...")
+ model_state = {"model": fsdp_model.state_dict()}
+ dist_cp.load_state_dict(
+ model_state,
+ RemoteFileSystemReader(
+ f"{load_path}/{MODEL_AND_OPTIM_FOLDER}",
+ local_cache=None if local_cache is None else local_cache / MODEL_AND_OPTIM_FOLDER,
+ ),
+ )
+ fsdp_model.load_state_dict(model_state["model"])
+
+ if not load_optimizer_state:
+ return
+
+ # Load optim state dict in place.
+ log.info("Loading sharded optimizer state...")
+ optim_state = load_sharded_optimizer_state_dict(
+ model_state_dict=model_state["model"],
+ optimizer_key="optim",
+ storage_reader=RemoteFileSystemReader(
+ f"{load_path}/{MODEL_AND_OPTIM_FOLDER}",
+ local_cache=None if local_cache is None else local_cache / MODEL_AND_OPTIM_FOLDER,
+ ),
+ )
+ del model_state
+ torch.cuda.empty_cache()
+ load_fsdp_optim_state(fsdp_model, optim, optim_state["optim"])
+
+
+def load_fsdp_optim_state(fsdp_model: FSDP, optim: Optimizer, optim_state: Dict[str, Any]):
+ log.info("Flattening sharded optimizer state...")
+ # NOTE: Careful! The order of the these arguments has changed from 2.0 to 2.1... ¯\_(ツ)_/¯
+ if version.parse(torch.__version__) < version.parse("2.1.0"):
+ flattened_osd = FSDP.optim_state_dict_to_load(optim_state, fsdp_model, optim) # type: ignore
+ else:
+ flattened_osd = FSDP.optim_state_dict_to_load(fsdp_model, optim, optim_state) # type: ignore
+ del optim_state
+ gc.collect()
+ log.info("Loading flattened optimizer state...")
+ # Put optim state on CPU since `Optimizer.load_state_dict()` will create a deepcopy of the whole state dict,
+ # which takes up unnecessary GPU memory.
+ for state in flattened_osd["state"].values():
+ for k in state.keys():
+ v = state[k]
+ if isinstance(v, torch.Tensor):
+ state[k] = v.to(device="cpu")
+ torch.cuda.empty_cache()
+ optim.load_state_dict(fix_optim_state_dict(optim, flattened_osd))
+
+
+def save_state_dict(
+ checkpoint_dir: PathOrStr,
+ fname: str,
+ state_dict: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ save_overwrite: bool = False,
+ synchronize: bool = True,
+):
+ """
+ Save a regular state dict to the file ``fname`` within ``checkpoint_dir`` using :func:`torch.save()`.
+ This can be used during distributed training or not. If during distributed training the ``fname`` should be unique
+ for each rank.
+
+ :param checkpoint_dir: The directory to save to.
+ :param fname: The target file within ``checkpoint_dir`` to save to. This should be a path relative to the ``checkpoint_dir``.
+ :param state_dict: The state dict to save.
+ :param upload_to: Optional, a remote "directory" to upload the file to.
+ :param save_overwrite: Overwrite existing files.
+ :param synchronize: If ``False``, don't do any distributed synchronization. Use this when only calling
+ this function from a single rank.
+
+ :raises FileExistsError: If the ``fname`` already exists within ``checkpoint_dir`` and ``save_overwrite=False``.
+ """
+ checkpoint_dir = Path(checkpoint_dir)
+ target_path = checkpoint_dir / fname
+ if save_overwrite:
+ target_path.unlink(missing_ok=True)
+ elif target_path.is_file():
+ raise FileExistsError(target_path)
+ if synchronize:
+ barrier()
+ target_path.parent.mkdir(exist_ok=True, parents=True)
+ if synchronize:
+ barrier()
+ torch.save(state_dict, target_path)
+ if upload_to is not None:
+ upload_target = f"{upload_to.rstrip('/')}/{fname}"
+ log.info(f"Uploading {target_path} to {upload_target}...")
+ upload(target_path, upload_target, save_overwrite=save_overwrite)
+
+
+def load_state_dict(
+ checkpoint_dir: PathOrStr,
+ fname: str,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ map_location: Optional[str] = None,
+):
+ """
+ Load a regular state dict from the file ``fname`` within ``checkpoint_dir`` using :func:`torch.load()`.
+ This can be used during distributed training or not.
+
+ :param checkpoint_dir: A local or remote checkpoint directory.
+ :param fname: The target file within the ``checkpoint_dir``. This should be a path relative to the ``checkpoint_dir``.
+ :param local_cache: A local cache of the checkpoint directory. Use this when the ``checkpoint_dir`` is a
+ remote "directory" but there might be a cached version of the same artifacts.
+
+ :raises FileNotFoundError: If ``fname`` doesn't exist in the ``checkpoint_dir`` or the local cache.
+ """
+ return torch.load(
+ resource_path(str(checkpoint_dir).rstrip("/"), fname, local_cache=local_cache), map_location=map_location
+ )
+
+
+def load_model_state(checkpoint_dir: PathOrStr, model: torch.nn.Module):
+ """
+ Load model state from a distributed FSDP model checkpoint created from :func:`save_fsdp_model_and_optim_state()`.
+ Note that ``model`` should not be wrapped with FSDP.
+ """
+ state_dict = {"model": model.state_dict()}
+ dist_cp.load_state_dict(
+ state_dict,
+ RemoteFileSystemReader(f"{str(checkpoint_dir).rstrip('/')}/{MODEL_AND_OPTIM_FOLDER}"),
+ no_dist=True,
+ )
+ model.load_state_dict(state_dict["model"])
+
+
+class RemoteFileSystemWriter(dist_cp.FileSystemWriter):
+ """
+ A subclass of :class:`~torch.distributed.checkpoint.FileSystemWriter` that can upload files
+ directly to a cloud bucket when ``upload_to`` is specified.
+ """
+
+ def __init__(
+ self,
+ path: PathOrStr,
+ single_file_per_rank: bool = True,
+ sync_files: bool = True,
+ thread_count: Optional[int] = None,
+ per_thread_copy_ahead: int = 10_000_000,
+ upload_to: Optional[str] = None,
+ save_overwrite: bool = False,
+ ) -> None:
+ if thread_count is not None and thread_count <= 0:
+ raise ValueError("thread count must be at least 1")
+ super().__init__(
+ path,
+ single_file_per_rank=single_file_per_rank,
+ sync_files=sync_files,
+ thread_count=thread_count or default_thread_count(),
+ per_thread_copy_ahead=per_thread_copy_ahead,
+ )
+ self.upload_to = None if upload_to is None else upload_to.rstrip("/")
+ self.save_overwrite = save_overwrite
+
+ def write_data(
+ self,
+ plan: dist_cp.SavePlan,
+ planner: dist_cp.SavePlanner,
+ ) -> Future[List[WriteResult]]:
+ fut = super().write_data(plan, planner)
+ if self.upload_to is not None:
+ files_to_upload = set()
+ for write_result in fut.wait():
+ files_to_upload.add(write_result.storage_data.relative_path)
+
+ with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
+ futures = []
+ for fname in files_to_upload:
+ source = self.path / fname
+ target = f"{self.upload_to}/{fname}"
+ log.info(f"Uploading {source} to {target}...")
+ futures.append(executor.submit(upload, source, target, save_overwrite=self.save_overwrite))
+ for f in as_completed(futures):
+ f.result()
+ return fut
+
+ def finish(self, metadata: Metadata, results: List[List[WriteResult]]) -> None:
+ super().finish(metadata, results)
+ if self.upload_to is not None:
+ source = self.path / ".metadata"
+ target = f"{self.upload_to}/.metadata"
+ log.info(f"Uploading {source} to {target}...")
+ upload(source, target, save_overwrite=self.save_overwrite)
+
+
+class RemoteFileSystemReader(dist_cp.StorageReader):
+ """
+ A :class:`~torch.distributed.checkpoint.StorageReader` based on :class:`~torch.distributed.checkpoint.FileSystemReader`
+ that can read data directly from cloud storage as well as a local directory.
+ """
+
+ def __init__(
+ self, path: PathOrStr, *, local_cache: Optional[PathOrStr] = None, thread_count: Optional[int] = None
+ ):
+ super().__init__()
+ if thread_count is not None and thread_count <= 0:
+ raise ValueError("thread count must be at least 1")
+ self.path = str(path).rstrip("/")
+ self.cache = None if local_cache is None else Path(local_cache)
+ self.thread_count = thread_count or default_thread_count()
+ self.storage_data: Dict[MetadataIndex, _StorageInfo] = dict()
+ self._metadata: Optional[Metadata] = None
+
+ def _get_bytes(self, relative_path: str, offset: int, length: int) -> bytes:
+ if self.cache is not None and (path := self.cache / relative_path).is_file():
+ return get_bytes_range(path, offset, length)
+ else:
+ return get_bytes_range(f"{self.path}/{relative_path}", offset, length)
+
+ def _get_content_for_read(self, read_item: ReadItem) -> Tuple[ReadItem, bytes]:
+ sinfo = self.storage_data[read_item.storage_index]
+ content = self._get_bytes(sinfo.relative_path, sinfo.offset, sinfo.length)
+ return (read_item, content)
+
+ def read_data(self, plan: dist_cp.LoadPlan, planner: dist_cp.LoadPlanner) -> Future[None]:
+ with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
+ read_item_content_futures = []
+ for read_item in plan.items:
+ read_item_content_futures.append(executor.submit(self._get_content_for_read, read_item))
+ read_item_content_results = []
+ for f in as_completed(read_item_content_futures):
+ read_item_content_results.append(f.result())
+
+ # Modified from `FileSystemReader.read_data()`
+ for read_item, content in read_item_content_results:
+ bytes = io.BytesIO(content)
+ bytes.seek(0)
+ if read_item.type == LoadItemType.BYTE_IO:
+ planner.load_bytes(read_item, bytes)
+ else:
+ tensor = cast(torch.Tensor, torch.load(bytes, map_location="cpu"))
+ tensor = narrow_tensor_by_index(tensor, read_item.storage_offsets, read_item.lengths)
+ target_tensor = planner.resolve_tensor(read_item).detach()
+
+ assert (
+ target_tensor.size() == tensor.size()
+ ), f"req {read_item.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
+ target_tensor.copy_(tensor)
+ planner.commit_tensor(read_item, target_tensor)
+
+ fut: Future = Future()
+ fut.set_result(None)
+ return fut
+
+ def read_metadata(self) -> Metadata:
+ if self._metadata is None:
+ with resource_path(self.path, ".metadata", local_cache=self.cache).open("rb") as metadata_file:
+ self._metadata = pickle.load(metadata_file)
+ return self._metadata
+
+ def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
+ del is_coordinator
+ self.storage_data = metadata.storage_data
+ assert self.storage_data is not None
+
+ def prepare_local_plan(self, plan: dist_cp.LoadPlan) -> dist_cp.LoadPlan:
+ return plan
+
+ def prepare_global_plan(self, global_plan: List[dist_cp.LoadPlan]) -> List[dist_cp.LoadPlan]:
+ return global_plan
+
+
+class Checkpointer(metaclass=ABCMeta):
+ def __init__(self, cfg: TrainConfig, thread_count: Optional[int] = None):
+ self.cfg = cfg
+ self.thread_count = thread_count or default_thread_count()
+
+ @abstractmethod
+ def save_checkpoint(
+ self,
+ dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ train_state: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ ) -> None:
+ raise NotImplementedError
+
+ @abstractmethod
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ ) -> Dict[str, Any]:
+ """
+ Restores a checkpoint to the model and optimizer. Returns the remaining trainer state.
+ """
+ raise NotImplementedError
+
+ def unshard_checkpoint(
+ self,
+ load_path: PathOrStr,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ load_trainer_state: bool = True,
+ device: Optional[torch.device] = None,
+ ) -> Tuple[Dict[str, torch.Tensor], Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
+ """
+ Unshard a checkpoint.
+
+ Note this is not marked abstract because child classes are not required to implemented this.
+ """
+ del load_path, local_cache, load_optimizer_state, load_trainer_state, device
+ raise NotImplementedError
+
+ @contextmanager
+ def _temporary_wd(self, dir: PathOrStr) -> Generator[Path, None, None]:
+ # Make sure checkpoint directory doesn't exist unless it's okay to overwrite it.
+ checkpoint_dir = Path(dir)
+ if not dir_is_empty(checkpoint_dir):
+ if self.cfg.save_overwrite:
+ if get_fs_local_rank() == 0:
+ shutil.rmtree(checkpoint_dir, ignore_errors=True)
+ else:
+ raise FileExistsError(checkpoint_dir)
+ # No need to mkdir here since we'll directly replace the temporary directory with
+ # this directory below.
+ barrier()
+
+ # Prepare temporary directory. We don't have to be as careful here, we can
+ # just remove it if it already exists.
+ checkpoint_dir_tmp = checkpoint_dir.with_name(checkpoint_dir.name + "-tmp")
+ if get_fs_local_rank() == 0:
+ shutil.rmtree(checkpoint_dir_tmp, ignore_errors=True)
+ barrier()
+
+ # Yield temporary directory for `.save_checkpoint()` to use.
+ yield checkpoint_dir_tmp
+
+ barrier()
+
+ # Finally if all went well replace the temporary directory with the actual
+ # checkpoint directory.
+ if get_fs_local_rank() == 0:
+ # Replace temp directory with target checkpoint directory.
+ try:
+ checkpoint_dir_tmp.replace(checkpoint_dir)
+ except FileNotFoundError:
+ # Caught when another (file-system) local rank 0 has already replaced the tmp directory.
+ # This can happen when nodes are saving to a common NFS drive but otherwise have distinct
+ # file-systems.
+ if not checkpoint_dir.exists():
+ raise
+
+ # In the cases where we're using a shared NFS drive between ranks to save checkpoints,
+ # replacing the temp directory with the final directory from rank 0 might not be immediately
+ # realized in the file systems of the other ranks.
+ # So we wait here across all ranks until that final checkpoint directory is visible.
+ wait_for(lambda: checkpoint_dir.exists(), "Waiting for checkpoint directory", timeout=10.0)
+
+ barrier()
+
+ def _save_config(self, dir: PathOrStr, *, upload_to: Optional[str] = None) -> None:
+ if get_global_rank() == 0:
+ log.info("Saving config...")
+ self.cfg.save(config_path := Path(dir) / "config.yaml")
+ if upload_to is not None:
+ upload_target = f"{upload_to}/config.yaml"
+ log.info(f"Uploading {config_path} to {upload_target}")
+ upload(config_path, upload_target, save_overwrite=self.cfg.save_overwrite)
+
+
+class FullCheckpointer(Checkpointer):
+ """
+ A :class:`Checkpointer` that saves a single full model and optimizer state dictionary.
+ """
+
+ def save_checkpoint(
+ self,
+ dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ trainer_state: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ ) -> None:
+ with self._temporary_wd(dir) as checkpoint_dir:
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.FULL_STATE_DICT,
+ state_dict_config=FullStateDictConfig(rank0_only=True, offload_to_cpu=True),
+ optim_state_dict_config=FullOptimStateDictConfig(rank0_only=True, offload_to_cpu=True),
+ ):
+ # We'll write the model and optimizer state dicts individually to reduce (CPU) memory consumption.
+ # First the model state.
+ model_state_dict = fsdp_model.state_dict()
+ if get_global_rank() == 0:
+ log.info("Saving model state...")
+ save_state_dict(
+ checkpoint_dir,
+ "model.pt",
+ model_state_dict,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ synchronize=False,
+ )
+ del model_state_dict
+ barrier()
+
+ # Then the optimizer state.
+ optim_state_dict = FSDP.optim_state_dict(fsdp_model, optim)
+ if get_global_rank() == 0:
+ log.info("Saving optim state...")
+ save_state_dict(
+ checkpoint_dir,
+ "optim.pt",
+ optim_state_dict,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ synchronize=False,
+ )
+ del optim_state_dict
+ barrier()
+
+ # Save trainer state.
+ if get_global_rank() == 0:
+ log.info("Saving trainer state...")
+ save_state_dict(
+ checkpoint_dir,
+ "train.pt",
+ trainer_state,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ synchronize=False,
+ )
+ # Save config.
+ self._save_config(checkpoint_dir, upload_to=upload_to)
+
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ ) -> Dict[str, Any]:
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.FULL_STATE_DICT,
+ state_dict_config=FullStateDictConfig(rank0_only=True, offload_to_cpu=True),
+ optim_state_dict_config=FullOptimStateDictConfig(rank0_only=False, offload_to_cpu=True),
+ ):
+ # Load model state.
+ log.info("Loading model state...")
+ state_dict_to_load, og_keys_to_new = fsdp_model._fsdp_wrapped_module._make_state_dict_compatible(
+ load_state_dict(load_path, "model.pt", local_cache=local_cache, map_location="cpu")
+ )
+ fsdp_model.load_state_dict(state_dict_to_load)
+ del state_dict_to_load
+
+ # Load optimizer state.
+ if load_optimizer_state:
+ gc.collect()
+ for turn in range(get_local_world_size()):
+ log.info("Loading optimizer state turn %d ...", turn)
+ if turn == get_local_rank():
+ optim_state_dict_to_load = self._make_optim_state_dict_compatible(
+ load_state_dict(load_path, "optim.pt", local_cache=local_cache, map_location="cpu"),
+ og_keys_to_new,
+ )
+ load_fsdp_optim_state(fsdp_model, optim, optim_state_dict_to_load)
+ del optim_state_dict_to_load
+ gc.collect()
+ torch.cuda.empty_cache()
+ barrier()
+
+ # Load other state.
+ try:
+ trainer_state = load_state_dict(load_path, "train.pt", local_cache=local_cache)
+ except FileNotFoundError:
+ # for backwards compatibility
+ trainer_state = load_state_dict(load_path, "other.pt", local_cache=local_cache)
+ barrier()
+ return trainer_state
+
+ def _make_optim_state_dict_compatible(
+ self, optim_state_dict: Dict[str, Any], og_keys_to_new: Dict[str, Set[str]]
+ ) -> Dict[str, Any]:
+ # This state dict comes in two forms: one where the state keys are integers and one where the
+ # keys are fully qualified parameter names. The latter case is easier to deal with here so we
+ # first transform the integer key form into the FQN key form.
+ if isinstance(next(iter(optim_state_dict["state"].keys())), int):
+ id_to_fqn: Dict[int, str] = {}
+ for group in optim_state_dict["param_groups"]:
+ new_param_names = []
+ for fqn, id in zip(group["param_names"], group["params"]):
+ fqn = fqn.replace("_fsdp_wrapped_module.", "")
+ id_to_fqn[id] = fqn
+ new_param_names.append(fqn)
+ group["param_names"] = new_param_names
+ group["params"] = new_param_names
+ for id in list(optim_state_dict["state"].keys()):
+ optim_state_dict["state"][id_to_fqn[id]] = optim_state_dict["state"].pop(id)
+ else:
+ # Otherwise we still want to clean up the param names to remove the "_fsdp_wrapped_module." prefix.
+ for group in optim_state_dict["param_groups"]:
+ group["param_names"] = [fqn.replace("_fsdp_wrapped_module.", "") for fqn in group["param_names"]]
+ group["params"] = [fqn.replace("_fsdp_wrapped_module.", "") for fqn in group["params"]]
+ assert group["param_names"] == group["params"]
+ for key in list(optim_state_dict["state"].keys()):
+ optim_state_dict["state"][key.replace("_fsdp_wrapped_module.", "")] = optim_state_dict[
+ "state"
+ ].pop(key)
+
+ # Now we can transform the state dict by renaming parameters according to `og_keys_to_new`.
+ # First fix param names in the state.
+ for og_key, new_keys in og_keys_to_new.items():
+ og_state = optim_state_dict["state"].pop(og_key)
+ for i, new_key in enumerate(new_keys):
+ if i == len(new_keys) - 1:
+ optim_state_dict["state"][new_key] = og_state
+ else:
+ optim_state_dict["state"][new_key] = deepcopy(og_state)
+ # Now fix param names in the param groups.
+ for group in optim_state_dict["param_groups"]:
+ og_names = group["params"]
+ new_names = []
+ for og_key in og_names:
+ for new_key in og_keys_to_new[og_key]:
+ new_names.append(new_key)
+ group["params"] = new_names
+ group["param_names"] = new_names
+
+ return optim_state_dict
+
+ def load_checkpoint(
+ self,
+ load_path: PathOrStr,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ device: Optional[torch.device] = None,
+ ) -> Tuple[Dict[str, torch.Tensor], Optional[Dict[str, Any]]]:
+ device = device if device is not None else torch.device("cpu")
+ model_state = load_state_dict(load_path, "model.pt", local_cache=local_cache, map_location=device) # type: ignore
+ optim_state = None
+ if load_optimizer_state:
+ optim_state = load_state_dict(load_path, "optim.pt", local_cache=local_cache, map_location=device) # type: ignore
+ return model_state, optim_state
+
+
+class TorchNewStyleShardedCheckpointer(Checkpointer):
+ """
+ A sharded :class:`Checkpointer` that uses PyTorch's new distributed checkpointing functionality.
+ """
+
+ def save_checkpoint(
+ self,
+ dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ trainer_state: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ ) -> None:
+ with self._temporary_wd(dir) as checkpoint_dir:
+ # Save model and optim state.
+ save_fsdp_model_and_optim_state(
+ checkpoint_dir,
+ fsdp_model,
+ optim,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save trainer state.
+ log.info("Saving trainer state...")
+ save_state_dict(
+ checkpoint_dir,
+ f"train/rank{get_global_rank()}.pt",
+ trainer_state,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save config.
+ self._save_config(checkpoint_dir, upload_to=upload_to)
+
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ ) -> Dict[str, Any]:
+ # Load model and optimizer state in place.
+ log.info("Loading model and optimizer state...")
+ load_fsdp_model_and_optim_state(
+ load_path,
+ fsdp_model,
+ optim,
+ local_cache=local_cache,
+ load_optimizer_state=load_optimizer_state,
+ )
+
+ # Load trainer state dict.
+ log.info("Loading trainer state...")
+ try:
+ trainer_state = load_state_dict(
+ load_path, f"train/rank{get_global_rank()}.pt", local_cache=local_cache
+ )
+ except FileNotFoundError:
+ # Fall back to rank 0 train state.
+ # This can happen when we're restoring a checkpoint with a different world size.
+ trainer_state = load_state_dict(load_path, "train/rank0.pt", local_cache=local_cache)
+ barrier()
+ return trainer_state
+
+
+class TorchLegacyShardedCheckpointer(Checkpointer):
+ """
+ A sharded :class:`Checkpointer` that just uses `torch.save()` with extra logic for handling FSDP model
+ and optim state.
+
+ The world size must be kept consistent when using this checkpointer.
+ """
+
+ def save_checkpoint(
+ self,
+ dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ trainer_state: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ ) -> None:
+ with self._temporary_wd(dir) as checkpoint_dir:
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.SHARDED_STATE_DICT,
+ state_dict_config=ShardedStateDictConfig(offload_to_cpu=True),
+ optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True),
+ ):
+ state_dict = {
+ "model": fsdp_model.state_dict(),
+ "optim": FSDP.optim_state_dict(fsdp_model, optim),
+ **trainer_state,
+ }
+ save_state_dict(
+ checkpoint_dir,
+ f"rank{get_global_rank()}.pt",
+ state_dict,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save config.
+ self._save_config(checkpoint_dir, upload_to=upload_to)
+
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ ) -> Dict[str, Any]:
+ with FSDP.state_dict_type(
+ fsdp_model,
+ state_dict_type=StateDictType.SHARDED_STATE_DICT,
+ state_dict_config=ShardedStateDictConfig(offload_to_cpu=True),
+ optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True),
+ ):
+ # Deserialize state dict.
+ state_dict = load_state_dict(
+ load_path, f"rank{get_global_rank()}.pt", local_cache=local_cache, map_location="cpu"
+ )
+
+ # Load model and optimizer state.
+ log.info("Loading model state...")
+ fsdp_model.load_state_dict(state_dict["model"])
+ del state_dict["model"]
+ if load_optimizer_state:
+ log.info("Loading optimizer state...")
+ load_fsdp_optim_state(fsdp_model, optim, state_dict["optim"])
+ del state_dict["optim"]
+
+ barrier()
+ return state_dict
+
+ def unshard_checkpoint(
+ self,
+ load_path: PathOrStr,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ load_trainer_state: bool = True,
+ device: Optional[torch.device] = None,
+ ) -> Tuple[Dict[str, torch.Tensor], Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
+ assert local_cache is None, "this method currently only supports local files"
+ full_state_dict = self._unshard(load_path, device or torch.device("cpu"), skip_keys={"rng"})
+ model_state = full_state_dict.pop("model")
+ optim_state = full_state_dict.pop("optim")
+ return (
+ model_state,
+ optim_state if load_optimizer_state else None,
+ full_state_dict if load_trainer_state else None,
+ )
+
+ def _unshard(self, input_dir: PathOrStr, device: torch.device, skip_keys: Optional[Set[str]] = None):
+ input_dir = Path(input_dir)
+ skip_keys = skip_keys or set()
+
+ # Monkeypatch torch's ShardedTensor, so we can unpickle without having torch.distributed set up.
+ def _rebuild_from_type_v2_monkey(func, new_type, args, state):
+ ret = func(*args)
+ if type(ret) is not new_type:
+ ret = ret.as_subclass(new_type)
+
+ # Shortcut the construction of ShardedTensor
+ # This is in the top 5 of my worst hacks.
+ if isinstance(ret, ShardedTensor):
+ ret._local_shards, ret._metadata, _, ret._sharding_spec, ret._init_rrefs = state
+ return ret
+
+ # The rest of this function ought to be in the top 5 of somebody else's worst hacks.
+ # Tensor does define __setstate__ even though it doesn't define
+ # __getstate__. So only use __setstate__ if it is NOT the one defined
+ # on Tensor
+ if getattr(ret.__class__, "__setstate__", torch.Tensor.__setstate__) is not torch.Tensor.__setstate__:
+ ret.__setstate__(state)
+ else:
+ ret = torch._utils._set_obj_state(ret, state)
+ return ret
+
+ torch._tensor._rebuild_from_type_v2 = _rebuild_from_type_v2_monkey
+
+ # We load in threads because it's faster.
+ executor = ThreadPoolExecutor()
+ shards_dict = {}
+ for shard_name in input_dir.glob("rank*.pt"):
+ log.info("Loading %s ...", shard_name)
+ shard_number = int(shard_name.name[4:-3]) # shard names look like "rankXX.pt"
+ shards_dict[shard_number] = executor.submit(torch.load, shard_name, map_location="cpu")
+ shards = [None] * len(shards_dict)
+ for rank, shard_future in shards_dict.items():
+ shard = shard_future.result()
+ for key in skip_keys:
+ if key in shard:
+ del shard[key]
+ shards[rank] = shard
+ assert all(shard is not None for shard in shards)
+ executor.shutdown()
+ del shards_dict
+
+ log.info("Unsharding from %d shards ...", len(shards))
+
+ unsharded_state_dict = self._unshard_object(shards, device=device)
+ # At this point in time we need 2x memory :-(
+ del shards
+
+ return unsharded_state_dict
+
+ def _unshard_object(self, os: List[Any], device: torch.device) -> Any:
+ rank0_item = os[0]
+ assert all(type(o) is type(rank0_item) for o in os)
+ if isinstance(rank0_item, str):
+ assert all(o == rank0_item for o in os)
+ return rank0_item
+ elif isinstance(rank0_item, (list, tuple, set)):
+ assert all(len(o) == len(rank0_item) for o in os)
+ return rank0_item.__class__(self._unshard_object(o, device=device) for o in zip(*os))
+ elif isinstance(rank0_item, dict):
+ assert all(o.keys() == rank0_item.keys() for o in os)
+ return {key: self._unshard_object([o[key] for o in os], device=device) for key in rank0_item.keys()}
+ elif isinstance(rank0_item, ShardedTensor):
+ return self._gather(os, device=device)
+ else:
+ assert all(self._objects_are_equal(o, rank0_item) for o in os)
+ return rank0_item
+
+ def _gather(self, shards: List[ShardedTensor], device: torch.device) -> torch.Tensor:
+ world_size = len(shards)
+ shard0_md = shards[0].metadata()
+ # Make sure all shards agree on the metadata
+ assert all(shard.metadata() == shard0_md for shard in shards)
+ # Make sure the nth shard expects to be the nth shard.
+ assert all(
+ shard_md.placement.rank() == rank # type: ignore
+ for rank, shard_md in enumerate(shard0_md.shards_metadata)
+ )
+
+ def shard_size(shard_md):
+ return reduce((lambda x, y: x * y), shard_md.shard_sizes) # type: ignore[attr-defined]
+
+ rank_sizes = [0 for _ in range(world_size)]
+ max_rank_size = 0
+ shard_placement: Dict[ShardMetadata, Tuple[int, int]] = {}
+ for shard_md in shard0_md.shards_metadata:
+ shard_rank = cast(_remote_device, shard_md.placement).rank()
+ assert shard_rank is not None
+
+ shard_placement[shard_md] = (shard_rank, rank_sizes[shard_rank])
+ rank_sizes[shard_rank] += shard_size(shard_md)
+ max_rank_size = max(max_rank_size, rank_sizes[shard_rank])
+
+ gather_list: List[torch.Tensor] = [torch.empty((max_rank_size,)) for _ in range(world_size)]
+
+ datas = []
+ with torch.no_grad():
+ for shard in shards:
+ data = torch.empty(max_rank_size)
+
+ for local_shard in shard.local_shards():
+ src = local_shard.tensor.flatten()
+ shard_offset = shard_placement[local_shard.metadata][1]
+ data[shard_offset : shard_offset + src.numel()].copy_(src)
+
+ datas.append(data)
+
+ # torch.gather in a nutshell
+ for rank, data in enumerate(datas):
+ gather_list[rank].copy_(data)
+
+ full_size = shard0_md.size
+ out = torch.empty(*full_size, dtype=shard0_md.tensor_properties.dtype, device=device)
+ dims = len(full_size)
+ for shard_md in shard0_md.shards_metadata:
+ rank, rank_offset = shard_placement[shard_md]
+ tensor = gather_list[rank]
+ tensor = tensor[rank_offset : rank_offset + shard_size(shard_md)]
+ tensor = tensor.view(shard_md.shard_sizes)
+
+ out_narrow_view = out
+ for dim in range(dims):
+ out_narrow_view = out_narrow_view.narrow(
+ dim,
+ shard_md.shard_offsets[dim],
+ shard_md.shard_sizes[dim],
+ )
+
+ out_narrow_view.copy_(tensor)
+
+ return out
+
+ def _objects_are_equal(self, a: Any, b: Any) -> bool:
+ if type(a) is not type(b):
+ return False
+ if isinstance(a, ndarray):
+ return np.array_equal(a, b)
+ elif isinstance(a, torch.Tensor):
+ return torch.equal(a, b)
+ else:
+ return a == b
+
+
+@dataclass
+class _LocalShardedCheckpointerMetadata(BaseConfig):
+ world_size: int = field(default_factory=get_world_size)
+
+
+@dataclass
+class _FlatParamShard:
+ full_shape: torch.Size
+ shard_offsets: Tuple[int, int]
+ shard_data: Optional[torch.Tensor]
+
+ def copy_into(self, full_tensor: torch.Tensor) -> None:
+ assert self.shard_data is not None
+ full_tensor_shard_view = full_tensor.view(-1)[self.shard_offsets[0] : self.shard_offsets[1] + 1]
+ assert self.shard_data.shape == full_tensor_shard_view.shape
+ full_tensor_shard_view.copy_(self.shard_data)
+
+
+class LocalShardedCheckpointer(Checkpointer):
+ """
+ A sharded :class:`Checkpointer` that directly saves the local FSDP flat params data.
+ The optimizer state is saved directly with `torch.save()` without reformatting via FSDP methods.
+
+ The world size must be kept consistent when using this checkpointer. However, you can easily
+ reconstruct a full unsharded model and/or optimizer state dictionary from a single Python process
+ using :meth:`unshard_checkpoint()` (no distributed initialization required).
+ """
+
+ # These correspond to metadata attributes on `torch.distributed.fsdp.flat_param.FlatParameter`.
+ _FLAT_PARAM_METADATA_TO_SAVE = (
+ "_fqns",
+ "_shard_param_offsets",
+ "_shard_indices",
+ "_numels",
+ "_numels_with_padding",
+ "_shapes",
+ "_shard_numel_padded",
+ "_shard_param_infos",
+ )
+
+ def _fsdp_modules(self, fsdp_model: FSDP) -> List[Tuple[str, FSDP]]:
+ """
+ Returns a list of FSDP modules with their FQN.
+ """
+ modules = []
+ for name, module in fsdp_model.named_modules():
+ if isinstance(module, FSDP):
+ modules.append((name, module))
+ return modules
+
+ def _prepare_fsdp_model(self, fsdp_model: FSDP) -> None:
+ from torch.distributed.fsdp._runtime_utils import _lazy_init
+
+ # TODO (epwalsh): I'm not sure if this is necessary, but this is what PyTorch does before saving/loading
+ # an FSDP state dict through the built-in methods.
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+ _lazy_init(fsdp_model, fsdp_model)
+
+ def _fsdp_handles(self, fsdp_model: FSDP) -> List[FlatParamHandle]:
+ if version.parse(torch.__version__) < version.parse("2.1.0"):
+ return fsdp_model._handles # type: ignore
+ elif version.parse(torch.__version__) < version.parse("2.2.0"):
+ return [fsdp_model._handle] # type: ignore
+ else:
+ # Need to verify FSDP internals with newer versions.
+ raise NotImplementedError
+
+ @torch.no_grad()
+ def _get_flat_param_state_to_save(self, fsdp_model: FSDP) -> Dict[str, Any]:
+ self._prepare_fsdp_model(fsdp_model)
+ module_data = []
+ for module_fqn, fsdp_module in self._fsdp_modules(fsdp_model):
+ handle_data = []
+ for handle in self._fsdp_handles(fsdp_module):
+ data: Dict[str, Any] = {}
+ # This is a `FlatParameter` instance.
+ # See `torch.distributed.fsdp.flat_param` for the API.
+ flat_param = handle.flat_param
+ data["flat_param.data"] = flat_param.detach()
+ for key in self._FLAT_PARAM_METADATA_TO_SAVE:
+ if hasattr(flat_param, key):
+ data[f"flat_param.{key}"] = getattr(flat_param, key)
+ handle_data.append(data)
+ module_data.append({"handles": handle_data, "name": module_fqn})
+ return {"modules": module_data}
+
+ @torch.no_grad()
+ def _load_flat_param_state(self, fsdp_model: FSDP, model_state: Dict[str, Any]):
+ """Load the state produced from `self._get_flat_param_state_to_save()`."""
+ self._prepare_fsdp_model(fsdp_model)
+ fsdp_modules = self._fsdp_modules(fsdp_model)
+ assert len(model_state["modules"]) == len(fsdp_modules)
+ for (_, fsdp_module), module_data in zip(fsdp_modules, model_state["modules"]):
+ handles = self._fsdp_handles(fsdp_module)
+ assert len(handles) == len(module_data["handles"])
+ for handle, data in zip(handles, module_data["handles"]):
+ flat_param = handle.flat_param
+ # Make sure metadata matches.
+ for key in self._FLAT_PARAM_METADATA_TO_SAVE:
+ if hasattr(flat_param, key):
+ assert getattr(flat_param, key) == data[f"flat_param.{key}"]
+ # Load the flat sharded data.
+ flat_param.copy_(data["flat_param.data"])
+
+ def _save_metadata(self, dir: PathOrStr, *, upload_to: Optional[str] = None) -> None:
+ if get_fs_local_rank() == 0:
+ log.info("Saving metadata...")
+ metadata = _LocalShardedCheckpointerMetadata()
+ metadata.save(metadata_path := Path(dir) / "metadata.yaml")
+ if upload_to is not None and get_global_rank() == 0:
+ upload_target = f"{upload_to}/metadata.yaml"
+ log.info(f"Uploading {metadata_path} to {upload_target}")
+ upload(metadata_path, upload_target, save_overwrite=self.cfg.save_overwrite)
+
+ def _load_metadata(
+ self, load_path: PathOrStr, *, local_cache: Optional[PathOrStr] = None
+ ) -> _LocalShardedCheckpointerMetadata:
+ metadata_path = resource_path(load_path, "metadata.yaml", local_cache=local_cache)
+ return _LocalShardedCheckpointerMetadata.load(metadata_path)
+
+ def save_checkpoint(
+ self,
+ dir: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ trainer_state: Dict[str, Any],
+ *,
+ upload_to: Optional[str] = None,
+ ) -> None:
+ with self._temporary_wd(dir) as checkpoint_dir:
+ # Gather local FSDP flat params data to save.
+ # We also save some flat param metadata like the corresponding fully qualified names (fqns)
+ # of each original parameter so we can validate that the sharding is the same when loading
+ # one of these checkpoints.
+ log.info("Saving local FSDP flat params data...")
+ save_state_dict(
+ checkpoint_dir,
+ f"model/rank{get_global_rank()}.pt",
+ self._get_flat_param_state_to_save(fsdp_model),
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save optimizer state.
+ log.info("Saving local optimizer state...")
+ save_state_dict(
+ checkpoint_dir,
+ f"optim/rank{get_global_rank()}.pt",
+ optim.state_dict(),
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save trainer state.
+ log.info("Saving trainer state...")
+ save_state_dict(
+ checkpoint_dir,
+ f"train/rank{get_global_rank()}.pt",
+ trainer_state,
+ upload_to=upload_to,
+ save_overwrite=self.cfg.save_overwrite,
+ )
+
+ # Save config.
+ self._save_config(checkpoint_dir, upload_to=upload_to)
+
+ # Save metadata.
+ self._save_metadata(checkpoint_dir, upload_to=upload_to)
+
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ fsdp_model: FSDP,
+ optim: Optimizer,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ ) -> Dict[str, Any]:
+ # Load metadata and make sure checkpoint is compatible.
+ metadata = self._load_metadata(load_path, local_cache=local_cache)
+ assert metadata.world_size == get_world_size()
+
+ # Load local FSDP flat param data.
+ log.info("Loading local FSDP flat params data...")
+ model_state = load_state_dict(
+ load_path, f"model/rank{get_global_rank()}.pt", local_cache=local_cache, map_location="cpu"
+ )
+ self._load_flat_param_state(fsdp_model, model_state)
+ del model_state
+
+ # Load local optim state.
+ if load_optimizer_state:
+ log.info("Loading local optimizer state...")
+ optim_state = load_state_dict(
+ load_path, f"optim/rank{get_global_rank()}.pt", local_cache=local_cache, map_location="cpu"
+ )
+ # HACK/TODO (epwalsh): When we use adaptive clipping we track the 'grad_norm_exp_avg' for every param
+ # in every rank, and keep this in the optimizer state. But this causes issues when loading the
+ # state since torch sees the state is non-empty for some params which would normally be empty,
+ # and then assumes it should have all of the other state tensors for that param, which is doesn't.
+ # So for now we just remove 'grad_norm_exp_avg' everywhere from the state, which resets that metric.
+ # Not the end of the world but there's probably a better way around this without resetting
+ # the metric.
+ for param_id in list(optim_state["state"].keys()):
+ state = optim_state["state"][param_id]
+ if "grad_norm_exp_avg" in state:
+ del state["grad_norm_exp_avg"]
+ if len(state) == 0:
+ del optim_state["state"][param_id]
+ optim.load_state_dict(optim_state)
+ del optim_state
+
+ # Load local trainer state.
+ log.info("Loading local trainer state...")
+ trainer_state = load_state_dict(load_path, f"train/rank{get_global_rank()}.pt", local_cache=local_cache)
+ barrier()
+ return trainer_state
+
+ def _iter_flat_param_shards(
+ self, model_state: Dict[str, Any]
+ ) -> Generator[Tuple[str, _FlatParamShard], None, None]:
+ for module_data in model_state["modules"]:
+ module_prefix = module_data["name"].replace("_fsdp_wrapped_module.", "")
+ for handle in module_data["handles"]:
+ flat_data = handle["flat_param.data"]
+ if (num_padding := handle["flat_param._shard_numel_padded"]) > 0:
+ # If there's padding in the flat param it should be on the right.
+ assert (flat_data[-num_padding:] == 0).all()
+ # NOTE: this changes depending on the torch version, but we don't do a version
+ # check since we might be trying to unshard an old checkpoint that was stored
+ # with a different torch version than we're currently running with.
+ if "flat_param._shard_indices" in handle:
+ # torch <=2.0.1
+ param_start = handle["flat_param._shard_indices"][0]
+ current_flat_index = 0
+ for relative_fqn, full_shape, (offset_start, offset_end) in zip(
+ handle["flat_param._fqns"][param_start:],
+ handle["flat_param._shapes"][param_start:],
+ handle["flat_param._shard_param_offsets"],
+ ):
+ root_fqn = relative_fqn if not module_prefix else f"{module_prefix}.{relative_fqn}"
+ numel_shard = offset_end - offset_start + 1
+ flat_param_shard = _FlatParamShard(
+ full_shape=full_shape,
+ shard_offsets=(offset_start, offset_end),
+ shard_data=flat_data[current_flat_index : current_flat_index + numel_shard],
+ )
+ current_flat_index += numel_shard
+ yield root_fqn, flat_param_shard
+ else:
+ # torch >=2.1.0
+ for relative_fqn, full_shape, shard_param_info in zip(
+ handle["flat_param._fqns"],
+ handle["flat_param._shapes"],
+ handle["flat_param._shard_param_infos"],
+ ):
+ if not shard_param_info.in_shard:
+ continue
+ root_fqn = relative_fqn if not module_prefix else f"{module_prefix}.{relative_fqn}"
+ flat_param_shard = _FlatParamShard(
+ full_shape=full_shape,
+ shard_offsets=(
+ shard_param_info.intra_param_start_idx,
+ shard_param_info.intra_param_end_idx,
+ ),
+ shard_data=flat_data[
+ shard_param_info.offset_in_shard : shard_param_info.offset_in_shard
+ + shard_param_info.numel_in_shard
+ ],
+ )
+ yield root_fqn, flat_param_shard
+
+ def unshard_checkpoint(
+ self,
+ load_path: PathOrStr,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ load_trainer_state: bool = True,
+ device: Optional[torch.device] = None,
+ ) -> Tuple[Dict[str, torch.Tensor], Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
+ device = device or torch.device("cpu")
+ metadata = self._load_metadata(load_path, local_cache=local_cache)
+
+ # Gather paths model state, potentially downloading them.
+ log.info("Gathering model state dicts...")
+ model_state_paths = self._gather_state_dict_paths(
+ load_path, "model", metadata.world_size, local_cache=local_cache
+ )
+
+ # Load model state dicts one-by-one, materializing and populating the full parameters as we go.
+ log.info("Materializing full parameters...")
+ full_model_state: Dict[str, torch.Tensor] = {}
+ # We keep a copy of the flat param metadata minus the actual tensors so we can reconstruct
+ # the full optimizer state below without having to reload the model state dicts.
+ flat_params_data: Dict[int, Dict[str, _FlatParamShard]] = defaultdict(dict)
+ for rank, path in enumerate(model_state_paths):
+ log.info(f"Loading shards from rank {rank}...")
+ model_state = torch.load(path, map_location="cpu")
+ for root_fqn, flat_param_shard in self._iter_flat_param_shards(model_state):
+ if root_fqn not in full_model_state:
+ log.info(
+ f"Materializing full parameter '{root_fqn}' with shape {flat_param_shard.full_shape}..."
+ )
+ assert flat_param_shard.shard_data is not None
+ full_model_state[root_fqn] = torch.empty(
+ flat_param_shard.full_shape, dtype=flat_param_shard.shard_data.dtype, device=device
+ )
+ # Fill with NaNs so we can validate that the whole parameter has been populated
+ # afterwards.
+ full_model_state[root_fqn].fill_(torch.nan)
+ # Copy over the local shard to the relevant part of the full parameter.
+ full_param = full_model_state[root_fqn]
+ log.info(f"Loading rank {rank} shard for '{root_fqn}'...")
+ flat_param_shard.copy_into(full_param)
+ flat_params_data[rank][root_fqn] = replace(flat_param_shard, shard_data=None)
+
+ log.info("Validating full parameters...")
+ for key, tensor in full_model_state.items():
+ if torch.isnan(tensor).any():
+ raise ValueError(f"Parameter '{key}' contains NaNs, this is likely a bug with the unsharder")
+
+ trainer_state: Optional[Dict[str, Any]] = None
+ if load_trainer_state:
+ trainer_state = load_state_dict(load_path, "train/rank0.pt", local_cache=local_cache)
+
+ if not load_optimizer_state:
+ return full_model_state, None, trainer_state
+
+ log.info("Gathering optim state dicts...")
+ optim_state_paths = self._gather_state_dict_paths(
+ load_path, "optim", metadata.world_size, local_cache=local_cache
+ )
+
+ log.info("Materializing full optim state...")
+ full_optim_state: Dict[str, Any] = {"state": defaultdict(dict)}
+ fqn_to_id: Dict[str, int] = {}
+ id_to_fqn: Dict[int, str] = {}
+ for rank, path in enumerate(optim_state_paths):
+ log.info(f"Loading sharded optim state from rank {rank}...")
+ optim_state = torch.load(path, map_location="cpu")
+
+ # Initialize param groups.
+ # We assume parameter groups are the same across all ranks.
+ # The only thing that differs across ranks is the state for each local sharded param.
+ if "param_groups" not in full_optim_state:
+ full_optim_state["param_groups"] = optim_state["param_groups"]
+ else:
+ assert full_optim_state["param_groups"] == optim_state["param_groups"]
+
+ # Generate mapping of parameter FQNs to optimizer param IDs and vice-versa.
+ if not fqn_to_id or not id_to_fqn:
+ for group in full_optim_state["param_groups"]:
+ for fqn, id in zip(group["param_names"], group["params"]):
+ fqn = fqn.replace("_fsdp_wrapped_module.", "")
+ fqn_to_id[fqn] = id
+ id_to_fqn[id] = fqn
+
+ # Iterate over local shard state and copy into the full state.
+ for id, shard_state in optim_state["state"].items():
+ fqn = id_to_fqn[id]
+ flat_param_shard = flat_params_data[rank].get(fqn) # type: ignore[assignment]
+ full_state = full_optim_state["state"][id]
+ for key, shard_value in shard_state.items():
+ assert isinstance(shard_value, torch.Tensor)
+ if shard_value.shape == torch.Size([]):
+ # Add singleton tensors directly to full state. These should be the same across
+ # all ranks.
+ assert key in ("step", "grad_norm_exp_avg") # sanity check
+ if key not in full_state:
+ full_state[key] = shard_value.to(device)
+ else:
+ assert full_state[key] == shard_value
+ else:
+ # Otherwise we have a sharded param state.
+ # If the corresponding full param state hasn't been materialized yet, do so now.
+ assert flat_param_shard is not None, f"missing flat_params_data for {fqn} from rank {rank}"
+ if key not in full_state:
+ log.info(
+ f"Materializing full state '{key}' for '{fqn}' with shape {flat_param_shard.full_shape}..."
+ )
+ full_state[key] = torch.empty(
+ flat_param_shard.full_shape, dtype=shard_value.dtype, device=device
+ )
+ full_state_value = full_state[key]
+
+ # Copy over the local shard state to the relevant part of the full parameter state.
+ log.info(f"Loading rank {rank} shard state of '{key}' for '{fqn}'...")
+ replace(flat_param_shard, shard_data=shard_value).copy_into(full_state_value)
+
+ # Lastly, clean up the parameter names in param groups.
+ for group in full_optim_state["param_groups"]:
+ group["param_names"] = [n.replace("_fsdp_wrapped_module.", "") for n in group["param_names"]]
+
+ return full_model_state, full_optim_state, trainer_state
+
+ def _get_state_dict_path(
+ self,
+ load_path: PathOrStr,
+ state_dict_type: str,
+ rank: int,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ progress=None,
+ ) -> Tuple[int, Path]:
+ fname = f"{state_dict_type}/rank{rank}.pt"
+ return rank, resource_path(str(load_path).rstrip("/"), fname, local_cache=local_cache, progress=progress)
+
+ def _gather_state_dict_paths(
+ self,
+ load_path: PathOrStr,
+ state_dict_type: str,
+ world_size: int,
+ *,
+ local_cache: Optional[PathOrStr] = None,
+ ) -> List[Path]:
+ progress = get_progress_bar()
+ with ThreadPoolExecutor(max_workers=self.thread_count) as executor:
+ futures = []
+ for rank in range(world_size):
+ future = executor.submit(
+ self._get_state_dict_path,
+ load_path,
+ state_dict_type,
+ rank,
+ local_cache=local_cache,
+ progress=progress,
+ )
+ futures.append(future)
+
+ results: Dict[int, Path] = {}
+ for future in as_completed(futures):
+ rank, path = future.result()
+ results[rank] = path
+
+ return [results[rank] for rank in range(world_size)]
+
+
+def build_sharded_checkpointer(
+ cfg: TrainConfig, *, name: Optional[ShardedCheckpointerType] = None
+) -> Checkpointer:
+ name = name or cfg.sharded_checkpointer
+ if name == ShardedCheckpointerType.torch_new:
+ return TorchNewStyleShardedCheckpointer(cfg)
+ elif name == ShardedCheckpointerType.torch_legacy:
+ return TorchLegacyShardedCheckpointer(cfg)
+ elif name == ShardedCheckpointerType.local:
+ return LocalShardedCheckpointer(cfg)
+ else:
+ raise NotImplementedError(name)
diff --git a/venv/lib/python3.10/site-packages/olmo/config.py b/venv/lib/python3.10/site-packages/olmo/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba3db47e2f169c806f184cfa5dca41e798669ecc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/config.py
@@ -0,0 +1,961 @@
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from glob import glob
+from pathlib import Path
+from typing import (
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+ cast,
+)
+
+import torch
+from omegaconf import OmegaConf as om
+from omegaconf.errors import OmegaConfBaseException
+from torch.distributed.fsdp import MixedPrecision, ShardingStrategy
+
+from .aliases import PathOrStr
+from .exceptions import OlmoConfigurationError
+from .util import StrEnum
+
+__all__ = [
+ "ActivationType",
+ "ActivationCheckpointingStrategy",
+ "BlockType",
+ "CompilerConfig",
+ "LayerNormType",
+ "InitFnType",
+ "ModelConfig",
+ "OptimizerType",
+ "OptimizerConfig",
+ "SchedulerType",
+ "SchedulerConfig",
+ "DataConfig",
+ "EvaluatorConfig",
+ "TokenizerConfig",
+ "TrainConfig",
+ "PaddingDirection",
+ "TruncationDirection",
+ "SpeedMonitorConfig",
+ "WandbConfig",
+ "CompilerConfig",
+ "WandbConfig",
+ "FSDPPrecision",
+ "FSDPWrapStrategy",
+ "FSDPConfig",
+ "CheckpointType",
+]
+
+C = TypeVar("C", bound="BaseConfig")
+
+
+class BaseConfig:
+ @classmethod
+ def _register_resolvers(cls, validate_paths: bool = True):
+ # Expands path globs into a list.
+ def path_glob(*paths) -> List[str]:
+ out = []
+ for path in paths:
+ matches = sorted(glob(path))
+ if not matches and validate_paths:
+ raise FileNotFoundError(f"{path} does not match any files or dirs")
+ out.extend(matches)
+ return out
+
+ # Chooses the first path in the arguments that exists.
+ def path_choose(*paths) -> str:
+ from .util import is_url
+
+ for path in paths:
+ if is_url(path) or Path(path).exists():
+ return path
+ if validate_paths:
+ raise FileNotFoundError(", ".join(paths))
+ else:
+ return ""
+
+ # Finds the latest checkpoint in a folder.
+ def path_last_checkpoint(path) -> str:
+ from .util import find_latest_checkpoint
+
+ latest_checkpoint = find_latest_checkpoint(path)
+ if latest_checkpoint is None:
+ if validate_paths:
+ raise FileNotFoundError(f"Could not find a latest checkpoint at {path}")
+ else:
+ return ""
+ else:
+ return str(latest_checkpoint)
+
+ om.register_new_resolver("path.glob", path_glob, replace=True)
+ om.register_new_resolver("path.choose", path_choose, replace=True)
+ om.register_new_resolver("path.last_checkpoint", path_last_checkpoint, replace=True)
+
+ @classmethod
+ def new(cls: Type[C], **kwargs) -> C:
+ cls._register_resolvers()
+ conf = om.structured(cls)
+ try:
+ if kwargs:
+ conf = om.merge(conf, kwargs)
+ return cast(C, om.to_object(conf))
+ except OmegaConfBaseException as e:
+ raise OlmoConfigurationError(str(e))
+
+ @classmethod
+ def load(
+ cls: Type[C],
+ path: PathOrStr,
+ overrides: Optional[List[str]] = None,
+ key: Optional[str] = None,
+ validate_paths: bool = True,
+ ) -> C:
+ """Load from a YAML file."""
+ cls._register_resolvers(validate_paths=validate_paths)
+ schema = om.structured(cls)
+ try:
+ raw = om.load(str(path))
+ if key is not None:
+ raw = raw[key] # type: ignore
+ conf = om.merge(schema, raw)
+ if overrides:
+ conf = om.merge(conf, om.from_dotlist(overrides))
+ return cast(C, om.to_object(conf))
+ except OmegaConfBaseException as e:
+ raise OlmoConfigurationError(str(e))
+
+ def save(self, path: PathOrStr) -> None:
+ """Save to a YAML file."""
+ om.save(config=self, f=str(path))
+
+ def asdict(self, exclude: Optional[Iterable[str]] = None) -> Dict[str, Any]:
+ out = asdict(self) # type: ignore
+ if exclude is not None:
+ for name in exclude:
+ if name in out:
+ del out[name]
+ return out
+
+
+class LayerNormType(StrEnum):
+ default = "default"
+ """
+ The default LayerNorm implementation, equivalent to PyTorch's built-in version.
+ """
+
+ low_precision = "low_precision"
+ """
+ A low-precision version of the default LayerNorm.
+ """
+
+ rms = "rms"
+ """
+ An RMSNorm implementation. When using ``torch.compile`` this is
+ probably the fastest implementation.
+ """
+
+ amd_compatible = "amd_compatible"
+ """
+ LayerNorm implemented manually to work around an issue with ROCm.
+ """
+
+
+class ActivationType(StrEnum):
+ gelu = "gelu"
+ relu = "relu"
+ swiglu = "swiglu"
+
+
+class BlockType(StrEnum):
+ sequential = "sequential"
+ parallel = "parallel"
+
+ llama = "llama"
+ """
+ A block similar to the sequential block with slightly different
+ implementations of operations like attention to imitate the behavior of Llama.
+ """
+
+
+class InitFnType(StrEnum):
+ mitchell = "mitchell"
+ """
+ The strategy suggested to us by Mitchell Wortsman from UW.
+ This uses a truncated normal distribution with an adaptive standard deviation that depends
+ on the size of the weights as well as the depth of the layer.
+ """
+
+ normal = "normal"
+ """
+ All weights are initialized from the same normal distribution.
+ """
+
+ kaiming_normal = "kaiming_normal"
+ """
+ All weights are initialized with the Kaiming method from a normal distribution.
+ Note this currently won't work with FSDP.
+ """
+
+ fan_in = "fan_in"
+ """
+ "Fan-in variance scaling", i.e. normal with a standard deviation of ``1/sqrt(d_in)`` where ``d_in``
+ is the input dimensionality of the kernel.
+ """
+
+ full_megatron = "full_megatron"
+ """
+ This is what metaseq calls "full megatron init". It is the init used for Llama 2.
+ """
+
+
+@dataclass
+class ModelConfig(BaseConfig):
+ """
+ OLMo (model) configuration.
+ """
+
+ # Note that the defaults for these attributes are equivalent to the base GPT2 model.
+
+ d_model: int = 768
+ """
+ The hidden size of the model.
+ """
+
+ n_heads: int = 12
+ """
+ The number of self-attention heads.
+ """
+
+ n_layers: int = 12
+ """
+ The number of layers/blocks.
+ """
+
+ mlp_ratio: int = 4
+ """
+ The ratio of the inner MLP dimensionality to ``d_model``.
+ This is only used when ``mlp_hidden_size`` is not set.
+ """
+
+ mlp_hidden_size: Optional[int] = None
+ """
+ Set the exact hidden size for the MLP. Otherwise the inner MLP hidden size will be set to `mlp_ratio * d_model`.
+ """
+
+ activation_type: ActivationType = ActivationType.swiglu
+ """
+ The activation function to use within the MLP layers.
+ """
+
+ block_type: BlockType = BlockType.sequential
+ """
+ The transformer block implementation.
+ """
+
+ block_group_size: int = 1
+ """
+ The number of blocks to group together into a single parent block.
+ This has no affect on the number of parameters in the model and is only used to wrap groups
+ of blocks together with a single FSDP wrapper during training.
+ """
+
+ alibi: bool = False
+ """
+ If ``True``, use ALiBi embeddings. Mutually exclusive with ``rope``.
+ """
+
+ alibi_bias_max: float = 8.0
+ """
+ Maximum absolute value of ALiBi bias.
+ """
+
+ rope: bool = False
+ """
+ Use rotary positional embeddings (RoPE). Mutually exclusive with ``alibi``.
+ """
+
+ rope_full_precision: bool = True
+ """
+ If ``True``, apply RoPE embeddings at full precision regardless of the input type. Otherwise,
+ apply RoPE at the precision of the input.
+ """
+
+ flash_attention: bool = False
+ """
+ If ``True``, use ``FlashAttention``.
+ """
+
+ attention_dropout: float = 0.1
+ """
+ The dropout probability within the attention modules.
+ """
+
+ multi_query_attention: bool = False
+ """
+ Use the Multi-Query formulation of attention used in PaLM. This reduces the number of parameters
+ and is more efficient during inference.
+ """
+
+ attention_layer_norm: bool = False
+ """
+ Apply layer norm to the keys and queries within the attention mechanism.
+ This can help stabilize training.
+ """
+
+ residual_dropout: float = 0.1
+ """
+ The dropout probability for the MLP and attention output within each block.
+ """
+
+ embedding_dropout: float = 0.1
+ """
+ The dropout probability for embeddings.
+ """
+
+ layer_norm_type: LayerNormType = LayerNormType.default
+ """
+ The layernorm implementation to use.
+ """
+
+ layer_norm_with_affine: bool = True
+ """
+ Whether to include bias and weight parameters for the layer norms.
+ This only affects layer norms that are immediately followed by a linear layer in the forward pass,
+ so everything except QK-norms. To turn off affines for QK norms as well, set :attr:`attention_layer_norm_with_affine`
+ to ``False``.
+ """
+
+ attention_layer_norm_with_affine: bool = True
+ """
+ Toggle affine transform for the QK norms.
+ """
+
+ max_sequence_length: int = 1024
+ """
+ The maximum input sequence length supported by the model.
+ """
+
+ include_bias: bool = True
+ """
+ Whether or not to include bias parameters in linear layers.
+ In PaLM, they got rid of all bias terms because they found that large
+ models tend to have near 0 bias terms anyway.
+ """
+
+ bias_for_layer_norm: Optional[bool] = None
+ """
+ Whether or not to include bias parameters in layer norm.
+ This is separate from the include_bias parameter, because of a ROCm crash when biases are disabled in
+ layer norm.
+ When this is None (the default), it inherits the setting from include_bias.
+ """
+
+ scale_logits: bool = False
+ """
+ If ``True``, scale the output logits by ``1 / sqrt(d_model)``.
+ """
+
+ vocab_size: int = 50257
+ """
+ Vocabulary size of the model.
+ """
+
+ embedding_size: Optional[int] = 50304
+ """
+ The number of embeddings, i.e. the number of tokens. If set to ``None`` it will default
+ to ``vocab_size``. If ``vocab_size`` is not a multiple of 128, setting this to the
+ next multiple of 128 that's greater than ``vocab_size`` can improve throughput
+ substantially.
+ """
+
+ weight_tying: bool = True
+ """
+ Whether to tie output linear weights to the input embedding.
+ """
+
+ eos_token_id: int = 50256
+ """
+ The ID of the end-of-sentence special token.
+ """
+
+ pad_token_id: int = 50256
+ """
+ The ID of the token to use for padding. Defaults to the ID of the EOS token.
+ """
+
+ init_device: Optional[str] = None
+ """
+ The torch device to use when initializing the model parameters, e.g. "cpu", "cuda:0", "meta".
+ """
+
+ init_fn: InitFnType = InitFnType.normal
+ """
+ The weight initialization strategy.
+ """
+
+ init_std: float = 0.02
+ """
+ The standard deviation to use when initializing weights with a "fixed distribution" ``init_fn``, such
+ as "normal".
+ """
+
+ init_cutoff_factor: Optional[float] = None
+ """
+ A positive factor used to scale the cutoff values when initializing weights with a "fixed distribution" ``init_fn``, such
+ as "normal". Setting this to None means values are not cutoff.
+ """
+
+ precision: Optional[str] = None
+ """
+ Precision used to train/evaluate with. You shouldn't set this directly.
+ See :data:`TrainConfig.precision` instead.
+ """
+
+
+class OptimizerType(StrEnum):
+ lionw = "lionw"
+ adamw = "adamw"
+
+
+@dataclass
+class OptimizerConfig(BaseConfig):
+ name: OptimizerType = OptimizerType.lionw
+ learning_rate: float = 1.0e-4
+ weight_decay: float = 0.01
+ betas: Tuple[float, float] = (0.9, 0.95)
+
+ no_decay_norm_and_bias: Optional[bool] = None
+ """
+ Deprecated. Use ``decay_norm_and_bias`` and ``decay_embeddings`` instead.
+ """
+
+ decay_norm_and_bias: bool = False
+ decay_embeddings: bool = False
+ metrics_log_interval: Optional[int] = None
+ """
+ The interval with which to collect and log detailed parameter-specific metrics.
+ This only applies when logging to W&B, since these metrics won't be logged to the console.
+ If not set, defaults to the wandb `log_interval`.
+ """
+
+ def __post_init__(self):
+ self.betas = tuple(self.betas) # type: ignore[assignment]
+
+
+class SchedulerType(StrEnum):
+ cosine_with_warmup = "cosine_with_warmup"
+ linear_with_warmup = "linear_with_warmup"
+ inverse_sqrt_with_warmup = "inverse_sqrt_with_warmup"
+ max_scheduler = "max_scheduler"
+ constant = "constant"
+
+
+@dataclass
+class SchedulerConfig(BaseConfig):
+ name: SchedulerType = SchedulerType.cosine_with_warmup
+ t_warmup: int = 100
+ t_max: Optional[int] = None
+ alpha_f: float = 0.1
+
+ grad_clip_warmup_steps: Optional[int] = None
+ """
+ The warmup period for which the max grad norm (or norm ratio) will be set to its
+ warmup value of `max_grad_norm * grad_clip_warmup_factor`.
+ """
+
+ grad_clip_warmup_factor: Optional[float] = None
+ """
+ The ratio of the max allowed gradient norm (or norm ratio) for clipping during the warmup period
+ vs after the warmup period.
+ """
+
+
+class PaddingDirection(StrEnum):
+ right = "right"
+ left = "left"
+
+
+@dataclass
+class DataConfig(BaseConfig):
+ paths: Optional[List[str]] = None
+ datasets: Optional[Dict[str, List[str]]] = None
+ pad_direction: PaddingDirection = PaddingDirection.right
+ num_workers: int = 0
+ drop_last: bool = False
+ pin_memory: bool = False
+ prefetch_factor: Optional[int] = None
+ persistent_workers: bool = False
+ timeout: int = 0
+
+
+class EvaluatorType(StrEnum):
+ downstream = "downstream"
+ lm = "lm"
+
+
+@dataclass
+class EvaluatorConfig(BaseConfig):
+ label: str
+ type: EvaluatorType = EvaluatorType.lm
+ data: DataConfig = field(default_factory=DataConfig)
+ device_eval_batch_size: Optional[int] = None
+ subset_num_batches: Optional[int] = None
+
+
+class TruncationDirection(StrEnum):
+ right = "right"
+ left = "left"
+
+
+@dataclass
+class TokenizerConfig(BaseConfig):
+ identifier: str = "gpt2"
+ truncate_direction: TruncationDirection = TruncationDirection.right
+
+
+@dataclass
+class WandbConfig(BaseConfig):
+ project: Optional[str] = None
+ entity: Optional[str] = "ai2-llm"
+ group: Optional[str] = None
+ name: Optional[str] = None
+ tags: Optional[List[str]] = field(default_factory=lambda: ["watching"])
+ log_artifacts: bool = False
+ rank_zero_only: bool = True
+ log_interval: int = 1
+
+
+@dataclass
+class SpeedMonitorConfig(BaseConfig):
+ window_size: int = 100
+ gpu_flops_available: Optional[Union[float, int]] = None
+
+
+@dataclass
+class CompilerConfig(BaseConfig):
+ mode: Optional[str] = None
+ """
+ The mode to compile the model in. At the moment this can be "default",
+ "reduce-overhead" (useful for smaller models/batches), or "max-autotune"
+ (the fastest for larger models, but takes a long time to compile).
+ """
+
+ fullgraph: bool = False
+ """
+ Whether it is OK to break model into several subgraphs when compiling.
+ Note that this is not compatible with FSDP.
+ """
+
+ backend: str = "inductor"
+ """
+ The backend to use.
+ """
+
+
+class FSDPWrapStrategy(StrEnum):
+ by_block = "by_block"
+ """
+ Wrap each OLMo block with its own FSDP instance.
+ """
+
+ by_block_and_size = "by_block_and_size"
+ """
+ Like 'by_block' but `wte` and `ff_out` will be wrapped separately as well.
+ """
+
+ by_block_group = "by_block_group"
+ """
+ Wrap each block group together into its own FSDP instance.
+ This requires :attr:`~ModelConfig.block_group_size` to be bigger than 1.
+ """
+
+ by_block_group_and_size = "by_block_group_and_size"
+ """
+ Like 'by_block_group' but `wte` and `ff_out` will be wrapped separately as well.
+ """
+
+ size_based = "size_based"
+ """
+ Used PyTorch's default size-based auto wrap policy.
+ """
+
+ one_in_two = "one_in_two"
+ one_in_three = "one_in_three"
+ one_in_four = "one_in_four"
+ one_in_five = "one_in_five"
+
+
+class FSDPPrecision(StrEnum):
+ pure = "pure"
+ """
+ Equivalent to :class:`torch.distributed.fsdp.MixedPrecision` with ``param_dtype``, ``reduce_dtype``,
+ and ``buffer_dtype`` all set to the autocast precision data type.
+ """
+
+ mixed = "mixed"
+ """
+ Equivalent to :class:`torch.distributed.fsdp.MixedPrecision` with ``param_dtype``, and ``buffer_dtype``
+ set to the autocast precision data type, while ``reduce_dtype`` is set to fp32.
+ """
+
+
+@dataclass
+class FSDPConfig(BaseConfig):
+ use_orig_params: bool = True
+ """
+ This must be ``True`` if using ``compile`` or you want to track the parameter norm during training.
+ """
+
+ sharding_strategy: ShardingStrategy = ShardingStrategy.FULL_SHARD
+
+ wrapping_strategy: Optional[FSDPWrapStrategy] = None
+ """
+ The wrapping strategy to use. If ``None``, the default, the model is wrapped with a single top-level
+ FSDP instance.
+ """
+
+ precision: FSDPPrecision = FSDPPrecision.pure
+
+
+class CheckpointType(StrEnum):
+ sharded = "sharded"
+ unsharded = "unsharded"
+
+
+class ShardedCheckpointerType(StrEnum):
+ torch_new = "torch_new"
+ torch_legacy = "torch_legacy"
+ local = "local"
+
+
+class ActivationCheckpointingStrategy(StrEnum):
+ whole_layer = "whole_layer"
+ one_in_two = "one_in_two"
+ one_in_three = "one_in_three"
+ one_in_four = "one_in_four"
+ fine_grained = "fine_grained"
+
+
+@dataclass
+class TrainConfig(BaseConfig):
+ """
+ OLMo training configuration.
+ """
+
+ run_name: Optional[str] = None
+ """
+ The name of the run.
+ """
+
+ seed: int = 6198
+ """
+ Used to seed all initial RNG states.
+ """
+
+ epoch: int = 0
+ """
+ Increment this when starting a new epoch.
+ """
+
+ dry_run: bool = False
+ """
+ If ``True``, don't actually train.
+ """
+
+ model: ModelConfig = field(default_factory=ModelConfig)
+ """
+ OLMo Model configuration.
+ """
+
+ optimizer: OptimizerConfig = field(default_factory=OptimizerConfig)
+ """
+ Optimizer configuration.
+ """
+
+ scheduler: SchedulerConfig = field(default_factory=SchedulerConfig)
+ """
+ Learning rate scheduler configuration.
+ """
+
+ data: DataConfig = field(default_factory=DataConfig)
+ """
+ Training data configuration.
+ """
+
+ restore_dataloader: bool = True
+ """
+ When restarting, restore the data loader to where it left off.
+ If you restarting in order to train on a different dataset, set this to ``False``.
+ """
+
+ fast_forward_batches: Optional[int] = None
+ """
+ When restarting, use this to fast-forward the dataloader beyond the last checkpoint.
+ This can be useful when restarting due to a loss spike in order to skip the data that
+ corresponded to the spike.
+ """
+
+ evaluators: List[EvaluatorConfig] = field(default_factory=list)
+ """
+ Evaluation configurations.
+ """
+
+ eval_interval: int = 1000
+ """
+ How often (in terms of batches) to run evaluations.
+ """
+
+ tokenizer: TokenizerConfig = field(default_factory=TokenizerConfig)
+ """
+ Tokenizer configuration.
+ """
+
+ save_folder: str = "./"
+ """
+ The directory to save checkpoints to.
+ """
+
+ remote_save_folder: Optional[str] = None
+ """
+ A folder in a cloud bucket to upload saved checkpoints to.
+ """
+
+ canceled_check_interval: int = 50
+ """
+ How often (in batches) to check if the run has been canceled or reached its time limit.
+ """
+
+ save_interval: int = 1000
+ """
+ How often (in terms of batches) to save training state checkpoints that can be used for restarts.
+ """
+
+ save_interval_unsharded: Optional[int] = None
+ """
+ How often (if at all) to save the unsharded state to a single file.
+ For large models it can be costly to save these, so it usually makes sense to save
+ these less often than regular (sharded) training checkpoints.
+ """
+
+ save_num_checkpoints_to_keep: int = -1
+ """
+ How many checkpoints to keep.
+ """
+
+ save_num_unsharded_checkpoints_to_keep: int = -1
+ """
+ How many unsharded checkpoints to keep.
+ """
+
+ save_overwrite: bool = False
+ """
+ If ``True``, overwrite any conflicting checkpoint files.
+ """
+
+ force_save_unsharded: bool = False
+ """
+ Save an unsharded checkpoint before training (even during a dry run).
+ Use this option with `--load-path={PATH}` and `--dry_run` to convert a sharded
+ checkpoint into an unsharded checkpoint.
+ """
+
+ no_pre_train_checkpoint: bool = False
+ """
+ Skip saving pre-train checkpoint.
+ """
+
+ load_path: Optional[str] = None
+ """
+ The path to a training checkpoint to restore/resume from.
+
+ Note that you can make use of the "path.last_checkpoint" Omegaconfig YAML resolver here, which takes
+ a local or remote directory and resolves to the latest checkpoint (sharded or unsharded) in that directory.
+ For example,
+
+ ```bash
+ --load_path='${path.last_checkpoint:s3://ai2-llm/checkpoints/7b/v1_5-mix-run-001}'
+ ```
+ """
+
+ load_path_sharded_checkpointer: Optional[ShardedCheckpointerType] = None
+ """
+ The sharded checkpointer type to use to load the initial checkpoint from ``load_path``.
+ """
+
+ reset_optimizer_state: bool = False
+ """
+ When this is set, we restore the model from a checkpoint (if given), but we leave the optimizer uninitialized.
+ We also set a new learning rate schedule that does a new warmup, such that it intercepts the original learning
+ curve (according to the current learning rate schedule settings), and continues from there.
+ """
+
+ sharded_checkpointer: ShardedCheckpointerType = ShardedCheckpointerType.torch_legacy
+ """
+ The name of the sharded checkpointer to use to save (sharded) checkpoints throughout training.
+ """
+
+ new_style_checkpoints: Optional[bool] = None
+ """
+ Deprecated. Use ``sharded_checkpointer`` instead.
+ """
+
+ max_duration: Union[int, str] = 10000
+ """
+ How long to train for.
+
+ If specified without a unit (the default), the units are assumed to be steps.
+ You can also specify this in terms of tokens, for example: `max_duration="2e12T"` means train until
+ 2 trillion tokens.
+ """
+
+ global_train_batch_size: int = 512
+ """
+ The effective global batch size.
+ """
+
+ device_train_batch_size: Optional[int] = None # calculated automatically
+ """
+ Don't set this manually. This will be set to ``global_train_batch_size // world_size``.
+ """
+
+ device_train_microbatch_size: int = 16
+ """
+ The number of instances passed to the model in a single forward-backward pass. You should set
+ this as large as you can based on available GPU memory.
+ """
+
+ device_eval_batch_size: int = 16
+ """
+ The number of evaluation instances passed to the model in a single forward pass on each device.
+ """
+
+ eval_subset_num_batches: int = -1
+ """
+ The number of batches to use for downstream evaluation from each dataset.
+ """
+
+ eval_on_load: bool = False
+ """
+ When resuming from a checkpoint, run the evaluation loop right away.
+ """
+
+ device_train_grad_accum: Optional[int] = None # calculated automatically
+ """
+ Don't set this manually. This will be set to ``device_train_batch_size // device_train_microbatch_size``.
+ """
+
+ max_grad_norm: Optional[float] = None
+ """
+ Clip gradient norms to this value if set.
+ """
+
+ max_grad_norm_ratio: Optional[float] = None
+ """
+ If set, gradient norms will be clipped to `max_grad_norm_ratio * exp_avg(norm(grad))`.
+ This takes priority over `max_grad_norm` when set.
+ """
+
+ precision: Optional[str] = None
+ """
+ Precision to train with (e.g. "amp_bf16", "amp_fp16", or "fp32").
+ """
+
+ wandb: Optional[WandbConfig] = None
+ """
+ Weights & Biases configuration.
+ """
+
+ speed_monitor: SpeedMonitorConfig = field(default_factory=SpeedMonitorConfig)
+ """
+ Speed monitor configuration.
+ """
+
+ console_log_interval: int = 1
+ """
+ How often to log to the console.
+ """
+
+ compile: Optional[CompilerConfig] = None
+ """
+ Settings for compiling the model with ``torch.compile()``.
+ """
+
+ fsdp: FSDPConfig = field(default_factory=FSDPConfig)
+ """
+ Fully sharded data parallel settings.
+ """
+
+ softmax_auxiliary_loss: bool = False
+ """
+ If ``True``, we add the auxiliary loss function from PaLM that encourages the softmax
+ normalizing term to be close to 0.
+ """
+
+ time_limit: Optional[float] = 60 * 60 * 47.5
+ """
+ The maximum amount of time to train for before saving a checkpoint and ending early.
+ On LUMI we have 48 hours max per job, so we default to just under 48 hours to give us time
+ to write out a final checkpoint.
+ """
+
+ early_stopping_factor: Optional[float] = None
+
+ save_data_indices: bool = True
+ """
+ Save training data indices from each batch for each worker.
+ """
+
+ python_profiling: bool = False
+ """
+ Whether to run the Python profiler on batches 6, 7, and 8.
+ """
+
+ torch_profiling: bool = False
+ """
+ Whether to run the PyTorch profiler on batches 6, 7, and 8.
+ """
+
+ stop_at: Optional[int] = None
+ """
+ Stop at a specific step.
+ """
+
+ activation_checkpointing: Optional[ActivationCheckpointingStrategy] = None
+ """
+ The activation checkpointing strategy to use.
+ """
+
+ @property
+ def autocast_precision(self) -> torch.dtype:
+ if self.precision == "amp_bf16":
+ return torch.bfloat16
+ elif self.precision == "amp_fp16":
+ return torch.float16
+ elif self.precision == "fp32":
+ return torch.float32
+ else:
+ raise ValueError(f"Unexpected precision type '{self.precision}'")
+
+ @property
+ def fsdp_precision(self) -> MixedPrecision:
+ if self.fsdp.precision == FSDPPrecision.pure:
+ return MixedPrecision(
+ param_dtype=self.autocast_precision,
+ reduce_dtype=self.autocast_precision,
+ buffer_dtype=self.autocast_precision,
+ )
+ elif self.fsdp.precision == FSDPPrecision.mixed:
+ return MixedPrecision(
+ param_dtype=self.autocast_precision,
+ reduce_dtype=torch.float32,
+ buffer_dtype=self.autocast_precision,
+ )
+ else:
+ raise NotImplementedError(f"{self.fsdp.precision}")
diff --git a/venv/lib/python3.10/site-packages/olmo/data/__init__.py b/venv/lib/python3.10/site-packages/olmo/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65b6599bd2bdb7b788059b5ed08a62ebae8aa2ad
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/data/__init__.py
@@ -0,0 +1,109 @@
+from pathlib import Path
+from typing import Any, Dict, List
+
+from torch.utils.data import DataLoader, DistributedSampler
+
+from ..config import DataConfig, TrainConfig
+from ..exceptions import OlmoConfigurationError
+from ..torch_util import barrier, get_global_rank, get_world_size
+from .collator import DataCollator
+from .iterable_dataset import IterableDataset
+from .memmap_dataset import MemMapDataset
+
+__all__ = ["MemMapDataset", "DataCollator", "IterableDataset", "build_eval_dataloader", "build_train_dataloader"]
+
+
+def build_memmap_dataset(
+ train_config: TrainConfig, data_config: DataConfig, include_instance_metadata: bool = True
+) -> MemMapDataset:
+ paths: List[str]
+ metadata: List[Dict[str, Any]] = []
+ if data_config.paths:
+ if data_config.datasets:
+ raise OlmoConfigurationError("DataConfig.paths is mutually exclusive with DataConfig.datasets")
+ paths = data_config.paths
+ for path in paths:
+ metadata.append({"path": str(path)})
+ elif data_config.datasets:
+ paths = []
+ for label in sorted(data_config.datasets.keys()):
+ label_paths = data_config.datasets[label]
+ paths.extend(label_paths)
+ metadata.extend([{"label": label}] * len(label_paths))
+ else:
+ raise OlmoConfigurationError("One of DataConfig.paths or DataConfig.datasets is required")
+ return MemMapDataset(
+ *paths,
+ chunk_size=train_config.model.max_sequence_length,
+ metadata=metadata,
+ include_instance_metadata=include_instance_metadata,
+ )
+
+
+def build_eval_dataloader(
+ train_config: TrainConfig,
+ data_config: DataConfig,
+ batch_size: int,
+ shuffle: bool = True,
+) -> DataLoader:
+ dataset = build_memmap_dataset(train_config, data_config, include_instance_metadata=True)
+ collator = DataCollator(pad_direction=data_config.pad_direction, pad_token_id=train_config.model.pad_token_id)
+ if data_config.drop_last:
+ # Make sure batch size is small enough.
+ samples_per_device = len(dataset) // get_world_size()
+ batch_size = min(batch_size, samples_per_device)
+ assert batch_size > 0, f"dataset for {data_config.paths} is too small"
+ sampler = DistributedSampler(
+ dataset,
+ drop_last=data_config.drop_last,
+ shuffle=shuffle,
+ num_replicas=get_world_size(),
+ rank=get_global_rank(),
+ seed=train_config.seed,
+ )
+ return DataLoader(
+ dataset,
+ batch_size=batch_size,
+ collate_fn=collator,
+ num_workers=data_config.num_workers,
+ sampler=sampler,
+ pin_memory=data_config.pin_memory,
+ prefetch_factor=None if data_config.num_workers == 0 else data_config.prefetch_factor,
+ persistent_workers=False if data_config.num_workers == 0 else data_config.persistent_workers,
+ timeout=data_config.timeout,
+ )
+
+
+def build_train_dataloader(train_config: TrainConfig) -> DataLoader:
+ assert train_config.device_train_batch_size is not None
+ collator = DataCollator(
+ pad_direction=train_config.data.pad_direction, pad_token_id=train_config.model.pad_token_id
+ )
+ dataset = build_memmap_dataset(train_config, train_config.data, include_instance_metadata=False)
+ work_dir = Path(train_config.save_folder) / "train_data"
+ if get_global_rank() == 0:
+ if work_dir.is_dir() and not train_config.save_overwrite:
+ raise OlmoConfigurationError(
+ "train data working directory already exists, use --save_overwrite to overwrite"
+ )
+ else:
+ work_dir.mkdir(exist_ok=True, parents=True)
+ barrier()
+ return DataLoader(
+ IterableDataset(
+ dataset, # type: ignore
+ train_config.global_train_batch_size,
+ seed=train_config.seed + train_config.epoch,
+ shuffle=True,
+ drop_last=train_config.data.drop_last,
+ work_dir=work_dir,
+ ),
+ batch_size=train_config.device_train_batch_size,
+ drop_last=train_config.data.drop_last,
+ collate_fn=collator,
+ num_workers=train_config.data.num_workers,
+ pin_memory=train_config.data.pin_memory,
+ prefetch_factor=None if train_config.data.num_workers == 0 else train_config.data.prefetch_factor,
+ persistent_workers=False if train_config.data.num_workers == 0 else train_config.data.persistent_workers,
+ timeout=train_config.data.timeout,
+ )
diff --git a/venv/lib/python3.10/site-packages/olmo/data/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e9283bae3bbfdd6546ddbb56915b9e3be2335a4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/data/__pycache__/collator.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/collator.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fdc970dc9df2b10edd7e0fd878969dda6207eb0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/collator.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/data/__pycache__/iterable_dataset.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/iterable_dataset.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13ea282595db361a76b4b2aec828003c4bef0525
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/iterable_dataset.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/data/__pycache__/memmap_dataset.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/memmap_dataset.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..162cab5b95e97804ac110a12b1f4ad7e3e3bc2ff
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/data/__pycache__/memmap_dataset.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/data/collator.py b/venv/lib/python3.10/site-packages/olmo/data/collator.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d81d271e16c67812e8e051fbba03c6fb598ff3f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/data/collator.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Dict, List, Union
+
+import torch
+import torch.nn.functional as F
+
+from ..config import PaddingDirection, TrainConfig
+
+__all__ = ["DataCollator"]
+
+
+@dataclass
+class DataCollator:
+ pad_direction: PaddingDirection
+ pad_token_id: int
+
+ @classmethod
+ def from_train_config(cls, config: TrainConfig) -> DataCollator:
+ return cls(pad_direction=config.data.pad_direction, pad_token_id=config.model.pad_token_id)
+
+ def __call__(self, items: Union[List[Dict[str, Any]], List[torch.Tensor]]) -> Dict[str, Any]:
+ assert items
+ max_len = max((len(x["input_ids"] if isinstance(x, dict) else x) for x in items))
+ all_input_ids = []
+ all_attention_mask = []
+ all_attention_bias = []
+ all_indices = []
+ all_metadata = []
+ for x in items:
+ input_ids = x["input_ids"] if isinstance(x, dict) else x
+ if not isinstance(input_ids, torch.Tensor):
+ input_ids = torch.tensor(input_ids)
+
+ pad_shape = (
+ (max_len - len(input_ids), 0)
+ if self.pad_direction == PaddingDirection.left
+ else (0, max_len - len(input_ids))
+ )
+
+ # Pad input IDs.
+ all_input_ids.append(
+ F.pad(
+ input_ids.to(dtype=torch.long),
+ pad_shape,
+ value=self.pad_token_id,
+ )
+ )
+
+ # Pad attention mask.
+ attention_mask = x.get("attention_mask") if isinstance(x, dict) else None
+ if attention_mask is not None:
+ if not isinstance(attention_mask, torch.Tensor):
+ attention_mask = torch.tensor(attention_mask)
+ all_attention_mask.append(
+ F.pad(
+ attention_mask.to(dtype=torch.float),
+ pad_shape,
+ value=0.0,
+ )
+ )
+
+ # Pad attention bias.
+ attention_bias = x.get("attention_bias") if isinstance(x, dict) else None
+ if attention_bias is not None:
+ if not isinstance(attention_bias, torch.Tensor):
+ attention_bias = torch.tensor(attention_bias)
+ # Reshape to `(1, seq_len, seq_len)`
+ while len(attention_bias.shape) < 3:
+ attention_bias = attention_bias.unsqueeze(0)
+ pad_value = False if attention_bias.dtype == torch.bool else float("-inf")
+ all_attention_bias.append(
+ F.pad(
+ attention_bias,
+ pad_shape + pad_shape,
+ value=pad_value,
+ )
+ )
+
+ # Indices.
+ index = x.get("index") if isinstance(x, dict) else None
+ if index is not None:
+ all_indices.append(torch.tensor(index))
+
+ # Metadata.
+ metadata = x.get("metadata") if isinstance(x, dict) else None
+ if metadata is not None:
+ all_metadata.append(metadata)
+
+ out: Dict[str, Any] = {"input_ids": torch.stack(all_input_ids)}
+ if all_attention_mask:
+ out["attention_mask"] = torch.stack(all_attention_mask)
+ if all_attention_bias:
+ out["attention_bias"] = torch.stack(all_attention_bias)
+ if all_indices:
+ out["index"] = torch.stack(all_indices)
+ if all_metadata:
+ out["metadata"] = all_metadata
+ return out
diff --git a/venv/lib/python3.10/site-packages/olmo/data/iterable_dataset.py b/venv/lib/python3.10/site-packages/olmo/data/iterable_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..a937a8a6aea22682f3563479330fa3788b003f03
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/data/iterable_dataset.py
@@ -0,0 +1,177 @@
+import logging
+import math
+from pathlib import Path
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
+
+import numpy as np
+import torch
+import torch.utils.data
+
+from ..aliases import PathOrStr
+from ..torch_util import barrier, get_fs_local_rank, get_global_rank, get_world_size
+from ..util import roundrobin, threaded_generator
+
+__all__ = ["IterableDataset"]
+
+
+log = logging.getLogger(__name__)
+
+
+class IterableDataset(torch.utils.data.IterableDataset[Dict[str, Any]]):
+ """
+ Adapted from PyTorch's DistributedSampler, this wraps a Dataset or arbitrary sequence
+ as an IterableDataset that can be deterministically restarted at any point by setting `start_index`,
+ which should be a multiple of your global batch size.
+ Similarly `max_examples`, if set, should be a multiple of global batch size.
+ """
+
+ def __init__(
+ self,
+ dataset: Union[Sequence[List[int]], Sequence[torch.Tensor], Sequence[Dict[str, Any]]],
+ global_batch_size: int,
+ *,
+ seed: int = 0,
+ start_index: int = 0,
+ max_examples: Optional[int] = None,
+ shuffle: bool = True,
+ drop_last: bool = False,
+ world_size: Optional[int] = None,
+ rank: Optional[int] = None,
+ fs_local_rank: Optional[int] = None,
+ work_dir: Optional[PathOrStr] = None,
+ num_threads: Optional[int] = None,
+ ):
+ self.dataset = dataset
+ self.seed = seed
+ self.start_index = start_index
+ self.max_examples = max_examples
+ self.shuffle = shuffle
+ self.drop_last = drop_last
+ self.rank = rank if rank is not None else get_global_rank()
+ self.fs_local_rank = fs_local_rank if fs_local_rank is not None else get_fs_local_rank()
+ self.world_size = world_size if world_size is not None else get_world_size()
+ # If the dataset length is evenly divisible by # of replicas, then there
+ # is no need to drop any data, since the dataset will be split equally.
+ if self.drop_last and len(self.dataset) % self.world_size != 0: # type: ignore[arg-type]
+ # Split to nearest available length that is evenly divisible by world size.
+ # This is to ensure each rank receives the same amount of data.
+ num_samples = math.ceil(
+ (len(self.dataset) - self.world_size) / self.world_size # type: ignore[arg-type]
+ )
+ else:
+ num_samples = math.ceil(len(self.dataset) / self.world_size) # type: ignore[arg-type]
+ self.total_size = num_samples * self.world_size
+ self.num_threads = num_threads
+ assert global_batch_size % self.world_size == 0
+ self.device_batch_size = global_batch_size // self.world_size
+ self.global_indices_file: Optional[Path] = None
+
+ if work_dir is not None:
+ self.global_indices_file = Path(work_dir) / "global_indices.npy"
+ if self.fs_local_rank == 0:
+ log.info("Saving global data order indices...")
+ self.global_indices_file.parent.mkdir(parents=True, exist_ok=True)
+ global_indices = self._build_global_indices()
+ global_indices_mmap = np.memmap(
+ self.global_indices_file, dtype=np.uint32, mode="w+", shape=(len(global_indices),)
+ )
+ global_indices_mmap[:] = global_indices
+ global_indices_mmap.flush()
+ del global_indices_mmap
+ log.info("Global data order indices saved to '%s'", self.global_indices_file)
+ barrier()
+
+ def _build_global_indices(self) -> np.ndarray:
+ assert len(self.dataset) < np.iinfo(np.uint32).max
+ indices = np.arange(len(self.dataset), dtype=np.uint32)
+ if self.shuffle:
+ # Deterministically shuffle based on epoch and seed
+ # Torch built-in randomness is not very random, so we use numpy.
+ rng = np.random.Generator(np.random.PCG64(seed=self.seed))
+ rng.shuffle(indices)
+
+ if not self.drop_last:
+ # Add extra samples to make it evenly divisible
+ padding_size = self.total_size - len(indices)
+ arrays_to_concatenate = [indices]
+ while padding_size > 0:
+ array_to_concatenate = indices[: min(padding_size, len(indices))]
+ arrays_to_concatenate.append(array_to_concatenate)
+ padding_size -= len(array_to_concatenate)
+ del array_to_concatenate
+ indices = np.concatenate(arrays_to_concatenate)
+ else:
+ # Remove tail of data to make it evenly divisible.
+ indices = indices[: self.total_size]
+ assert len(indices) == self.total_size
+ return indices
+
+ def get_global_indices(self) -> np.ndarray:
+ if self.global_indices_file is not None:
+ return np.memmap(self.global_indices_file, mode="r", dtype=np.uint32) # type: ignore
+ else:
+ return self._build_global_indices()
+
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
+ indices = self.get_global_indices()
+
+ # Truncate to max_examples.
+ if self.max_examples is not None:
+ assert self.max_examples % self.world_size == 0
+ indices = indices[: self.max_examples]
+
+ # Start at the specified index.
+ if self.start_index > 0:
+ assert self.start_index % self.world_size == 0
+ indices = indices[self.start_index :]
+
+ # Slice indices by rank to avoid duplicates.
+ indices = indices[self.rank : self.total_size : self.world_size]
+
+ # Separate from data loading workers (which use multiprocessing), we also have the option
+ # to use multi-threading (within workers).
+ num_threads = self.num_threads
+
+ # Slice the indices by data loader worker rank to avoid duplicates.
+ worker_info = torch.utils.data.get_worker_info()
+ if worker_info is not None:
+ # Note that each data loading worker gathers a whole batch at a time, and the workers
+ # are called round-robin by rank. So to slice these up in a way that preserves order, regardless
+ # of the number of workers, we should give worker 0 the first chunk of `device_batch_size` indices,
+ # worker 1 the 2nd chunk of `device_train_batch_size` indices, etc...
+ truncated_size = self.device_batch_size * (len(indices) // self.device_batch_size)
+ left_overs = indices[truncated_size + worker_info.id :: worker_info.num_workers]
+ indices = (
+ indices[:truncated_size]
+ .reshape((-1, self.device_batch_size))[worker_info.id :: worker_info.num_workers] # type: ignore
+ .reshape((-1,))
+ )
+ indices = np.concatenate([indices, left_overs])
+ elif num_threads is None:
+ # If `num_threads` hasn't been specified and we're not using multiprocessing we'll try to guess
+ # a good number of threads.
+ num_threads = 4
+
+ # Finally, potentially slice by threads.
+ if num_threads:
+ # In order to stay ahead of training the total queue size (sum across all threads)
+ # should be bigger than the batch size.
+ queue_size = math.ceil(self.device_batch_size * 2 / num_threads)
+
+ thread_generators = []
+ for i in range(num_threads):
+ generator = (self._get_dataset_item(int(idx)) for idx in indices[i::num_threads])
+ thread_generators.append(
+ threaded_generator(generator, maxsize=queue_size, thread_name=f"data thread {i}")
+ )
+
+ return (x for x in roundrobin(*thread_generators))
+ else:
+ return (self._get_dataset_item(int(idx)) for idx in indices)
+
+ def _get_dataset_item(self, idx: int) -> Dict[str, Any]:
+ item = self.dataset[idx]
+ if isinstance(item, dict):
+ return dict(**item, index=idx)
+ else:
+ return {"input_ids": item, "index": idx}
diff --git a/venv/lib/python3.10/site-packages/olmo/data/memmap_dataset.py b/venv/lib/python3.10/site-packages/olmo/data/memmap_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d7d5fd99da821a0f16dd969329edc25986f9c16
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/data/memmap_dataset.py
@@ -0,0 +1,157 @@
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from torch.utils.data import Dataset
+
+from olmo.exceptions import OlmoEnvironmentError
+
+from ..aliases import PathOrStr
+from ..util import _get_s3_client, file_size, get_bytes_range
+
+__all__ = ["MemMapDataset"]
+
+
+class MemMapDataset(Dataset[Dict[str, Any]]):
+ """
+ A PyTorch :class:`~torch.utils.data.Dataset` backed by one or more numpy memory-mapped arrays
+ of token IDs. Token IDs are chunked together into contiguous blocks of ``chunk_size``
+ to create instances.
+
+ If the length of a memory-mapped array is not a multiple of ``chunk_size`` the
+ remainder of the tokens will be ignored.
+
+ No special tokens are added to the input IDs so it's assumed that if you want
+ EOS tokens between documents, for example, those will already be in the memory-mapped array.
+
+ :param paths: Paths to memory-mapped token arrays.
+ :param chunk_size: The number of tokens to chunk together into a single instance.
+ Generally this should correspond to your model's maximum input length.
+ :param memmap_dtype: The numpy datatype of the memory-mapped array.
+ :param metadata: Metadata to add to each item. This should be a dictionary or a list of dictionaries
+ with the same number of items as there are paths.
+ :param include_instance_metadata: If ``True`` (the default), each instance returned from `__getitem__` will
+ include the metadata from its source.
+ """
+
+ def __init__(
+ self,
+ *paths: PathOrStr,
+ chunk_size: int = 1024,
+ memmap_dtype=np.uint16,
+ metadata: Optional[Union[List[Dict[str, Any]], Dict[str, Any]]] = None,
+ include_instance_metadata: bool = True,
+ ):
+ if not paths:
+ raise ValueError("At least one path is required")
+ if isinstance(metadata, list):
+ if len(metadata) != len(paths):
+ raise ValueError("'metadata' should have the same length as the number of file paths")
+ else:
+ metadata = [metadata or {}] * len(paths)
+ self._memmap_paths = paths
+ self._metadata = metadata
+ self._chunk_size = chunk_size
+ self._mmap_offsets: Optional[List[Tuple[int, int]]] = None
+ self._num_instances: Optional[int] = None
+ self.dtype = memmap_dtype
+ self._item_size = self.dtype(0).itemsize
+ self._include_instance_metadata = include_instance_metadata
+
+ @property
+ def chunk_size(self) -> int:
+ return self._chunk_size
+
+ @property
+ def max_seq_len(self) -> int:
+ # For compatibility with composer's SpeedMonitor callback.
+ return self.chunk_size
+
+ @property
+ def offsets(self) -> List[Tuple[int, int]]:
+ # Create the global S3 client up front to work around a threading issue in boto.
+ _get_s3_client("s3")
+ try:
+ _get_s3_client("r2")
+ except OlmoEnvironmentError:
+ # R2 might not be needed, so ignore this error. We will get an error
+ # later if R2 is needed.
+ pass
+
+ if self._mmap_offsets is None:
+ import concurrent.futures
+
+ self._mmap_offsets = []
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ futures = []
+ for path in self._memmap_paths:
+ future = executor.submit(self._get_file_length, path)
+ futures.append(future)
+
+ path_to_length: Dict[PathOrStr, int] = {}
+ for future in concurrent.futures.as_completed(futures):
+ path, length = future.result()
+ path_to_length[path] = length
+
+ start_offset = 0
+ for path in self._memmap_paths:
+ length = path_to_length[path]
+ end_offset = start_offset + length
+ self._mmap_offsets.append((start_offset, end_offset))
+ start_offset += length
+ return self._mmap_offsets
+
+ def _read_chunk_from_memmap(self, path: PathOrStr, index: int) -> torch.Tensor:
+ bytes_start = index * self._item_size * self._chunk_size
+ num_bytes = self._item_size * self._chunk_size
+ buffer = get_bytes_range(path, bytes_start, num_bytes)
+ array = np.frombuffer(buffer, dtype=self.dtype)
+ return torch.tensor(array.astype(np.int_), dtype=torch.long)
+
+ def _get_file_length(self, path) -> Tuple[PathOrStr, int]:
+ return path, file_size(path) // (self._item_size * self._chunk_size)
+
+ def __len__(self) -> int:
+ if self._num_instances is None:
+ self._num_instances = self.offsets[-1][1]
+ return self._num_instances
+
+ def __getitem__(self, index: int) -> Dict[str, Any]:
+ index = int(index) # in case this is a numpy int type.
+ pos_index = index if index >= 0 else len(self) + index
+
+ # The index of the memmap array within 'self.memmaps'
+ memmap_index: Optional[int] = None
+ # The 'index' relative to the corresponding memmap array.
+ memmap_local_index: Optional[int] = None
+ for i, (offset_start, offset_end) in enumerate(self.offsets):
+ if offset_start <= pos_index < offset_end:
+ memmap_index = i
+ memmap_local_index = pos_index - offset_start
+
+ if memmap_index is None or memmap_local_index is None:
+ raise IndexError(f"{index} is out of bounds for dataset of size {len(self)}")
+
+ # Read the data from file.
+ input_ids = self._read_chunk_from_memmap(self._memmap_paths[memmap_index], memmap_local_index)
+ out: Dict[str, Any] = {"input_ids": input_ids}
+ if self._include_instance_metadata:
+ metadata = self._metadata[memmap_index]
+ out["metadata"] = deepcopy(metadata)
+ return out
+
+ def __add__(self, other: MemMapDataset) -> MemMapDataset:
+ """
+ Concatenate one :class:`MemMapDataset` with another.
+ """
+ if not isinstance(other, MemMapDataset):
+ raise NotImplementedError(f"Expected another MemMapDataset but got {type(other)}")
+ return MemMapDataset(
+ *(self._memmap_paths + other._memmap_paths),
+ chunk_size=self._chunk_size,
+ memmap_dtype=self.dtype,
+ metadata=self._metadata + other._metadata,
+ )
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/__init__.py b/venv/lib/python3.10/site-packages/olmo/eval/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c53f4b25f4bfe612593e53621ef404c524833e3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/eval/__init__.py
@@ -0,0 +1,111 @@
+from typing import Dict, List, Union
+
+import torch
+from torch.utils.data import DataLoader, DistributedSampler
+from torchmetrics import MeanMetric, Metric
+
+from ..config import EvaluatorConfig, EvaluatorType, TrainConfig
+from ..exceptions import OlmoConfigurationError
+from ..tokenizer import Tokenizer
+from ..torch_util import get_global_rank, get_world_size
+from .downstream import ICLMetric, label_to_task_map
+from .evaluator import Evaluator
+
+__all__ = [
+ "Evaluator",
+ "ICLMetric",
+ "label_to_task_map",
+ "build_downstream_evaluator",
+ "build_evaluator",
+ "build_evaluators",
+]
+
+
+def build_downstream_evaluator(
+ train_config: TrainConfig,
+ eval_cfg: EvaluatorConfig,
+ tokenizer: Tokenizer,
+ device: torch.device,
+ is_unit_test=False,
+) -> Evaluator:
+ task_class = label_to_task_map[eval_cfg.label]
+ ds_eval_dataset = task_class(tokenizer=tokenizer) # type: ignore
+ data_config = eval_cfg.data
+ if is_unit_test:
+ ds_eval_sampler = None
+ else:
+ ds_eval_sampler = DistributedSampler(
+ ds_eval_dataset,
+ drop_last=data_config.drop_last,
+ shuffle=False,
+ num_replicas=get_world_size(),
+ rank=get_global_rank(),
+ seed=train_config.seed,
+ )
+ ds_eval_dataloader = DataLoader(
+ ds_eval_dataset,
+ batch_size=eval_cfg.device_eval_batch_size or train_config.device_eval_batch_size,
+ collate_fn=ds_eval_dataset.collate_fn,
+ num_workers=data_config.num_workers,
+ sampler=ds_eval_sampler,
+ pin_memory=data_config.pin_memory,
+ prefetch_factor=data_config.prefetch_factor,
+ persistent_workers=data_config.persistent_workers,
+ timeout=data_config.timeout,
+ )
+ metric = ICLMetric(metric_type=ds_eval_dataset.metric_type)
+
+ evaluator = Evaluator(
+ label=eval_cfg.label,
+ type=eval_cfg.type,
+ eval_loader=ds_eval_dataloader,
+ eval_metric=metric.to(device),
+ subset_num_batches=eval_cfg.subset_num_batches,
+ )
+ return evaluator
+
+
+def build_evaluator(
+ train_config: TrainConfig, eval_config: EvaluatorConfig, tokenizer: Tokenizer, device: torch.device
+) -> Evaluator:
+ from ..data import build_eval_dataloader
+
+ if eval_config.type == EvaluatorType.downstream:
+ # Downstream evaluation.
+ return build_downstream_evaluator(train_config, eval_config, tokenizer, device)
+ elif eval_config.type == EvaluatorType.lm:
+ # Language modeling evaluation.
+ eval_loader = build_eval_dataloader(
+ train_config,
+ eval_config.data,
+ eval_config.device_eval_batch_size or train_config.device_eval_batch_size,
+ )
+
+ def make_metric():
+ return MeanMetric(nan_strategy="error").to(device)
+
+ eval_metric: Union[Metric, Dict[str, Metric]]
+ if eval_config.data.paths:
+ eval_metric = make_metric()
+ elif eval_config.data.datasets:
+ eval_metric = {label: make_metric() for label in eval_config.data.datasets.keys()}
+ else:
+ raise OlmoConfigurationError("One of DataConfig.paths or DataConfig.datasets is required")
+
+ return Evaluator(
+ label=eval_config.label,
+ type=eval_config.type,
+ eval_loader=eval_loader,
+ eval_metric=eval_metric,
+ subset_num_batches=eval_config.subset_num_batches,
+ )
+ else:
+ raise ValueError(f"Unexpected evaluator type '{eval_config.type}'")
+
+
+def build_evaluators(cfg: TrainConfig, device: torch.device) -> List[Evaluator]:
+ evaluators = []
+ tokenizer = Tokenizer.from_train_config(cfg)
+ for eval_cfg in cfg.evaluators:
+ evaluators.append(build_evaluator(cfg, eval_cfg, tokenizer, device))
+ return evaluators
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f018c2bd446ff304a712abeb2845f4bd81ea3e6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/downstream.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/downstream.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e22231e335f03eac6368bb1659c320a5a68474c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/downstream.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/evaluator.cpython-310.pyc b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/evaluator.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b394c99ae8ca3c62ee7986eccf13a47695b018fe
Binary files /dev/null and b/venv/lib/python3.10/site-packages/olmo/eval/__pycache__/evaluator.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/downstream.py b/venv/lib/python3.10/site-packages/olmo/eval/downstream.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fe5e4a7192392e42eb152d87f1a5b76d8399678
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/eval/downstream.py
@@ -0,0 +1,979 @@
+import abc
+import re
+from typing import Any, ClassVar, Dict, List, Optional
+
+import datasets
+import torch
+import torch.nn.functional as F
+from sklearn.metrics import f1_score
+from torchmetrics import Metric
+
+from ..tokenizer import Tokenizer
+
+
+class ICLMetric(Metric):
+ # update method does not require access to global metric state
+ full_state_update: bool = False
+
+ def __init__(self, metric_type="acc") -> None:
+ """metric_type: f1, acc, len_norm, pmi_dc"""
+ super().__init__(sync_on_compute=True)
+
+ self.metric_type = metric_type
+
+ self.add_state("loglikelihoods", default=[], dist_reduce_fx=None)
+ self.add_state("labels", default=[], dist_reduce_fx=None)
+
+ def reset(
+ self,
+ ):
+ self.loglikelihoods = []
+ self.labels = []
+
+ def update(self, batch: Dict[str, Any], lm_logits: torch.Tensor, dc_lm_logits=None):
+ lm_logits = F.log_softmax(lm_logits, dim=-1)
+
+ if self.metric_type == "pmi_dc":
+ assert dc_lm_logits is not None, "PMI_DC acc type selected but no domain conditional logits provided"
+
+ for idx, (doc_id, cont_id) in enumerate(zip(batch["doc_id"], batch["cont_id"])):
+ # [cont_len]: continuation is padded for batching
+ cont_tokens = batch["continuation"][idx][: batch["cont_len"][idx]]
+ # get logits from LM for the continuation: [cont_len, vocab]
+ # batch['input_ids'][idx] -> ctx + cont + padding
+ # -1 in both indices: lm_logits will be left shited 1 pos as 0th pos in input generates next token in the 0th pos of lm_logits
+ lm_cont_logits = lm_logits[idx][
+ batch["ctx_len"][idx] - 1 : batch["ctx_len"][idx] + batch["cont_len"][idx] - 1
+ ]
+
+ log_likelihood: torch.Tensor
+ if self.metric_type == "pmi_dc":
+ assert dc_lm_logits is not None
+ # get domain conditional continuation logits: [cont_len, vocab]
+ dc_lm_cont_logits = dc_lm_logits[idx][
+ batch["dc_len"][idx] - 1 : batch["dc_len"][idx] + batch["cont_len"][idx] - 1
+ ]
+
+ # gather log-probs at continuation token indices but divide by domain conditional prob
+ log_likelihood = (
+ torch.gather(lm_cont_logits, 1, cont_tokens.unsqueeze(-1)).sum()
+ / torch.gather(dc_lm_cont_logits, 1, cont_tokens.unsqueeze(-1)).sum()
+ )
+ elif self.metric_type == "acc" or self.metric_type == "f1":
+ # gather log-probs at continuation token indices
+ log_likelihood = torch.gather(lm_cont_logits, 1, cont_tokens.unsqueeze(-1)).sum()
+ elif self.metric_type == "len_norm":
+ log_likelihood = (
+ torch.gather(lm_cont_logits, 1, cont_tokens.unsqueeze(-1)).sum() / batch["cont_str_len"][idx]
+ )
+ else:
+ raise ValueError(self.metric_type)
+
+ # because metric states cannot be dict/list of tuples, store this tuple as tensor: (doc_id, cont_id, metric_state)
+ self.loglikelihoods.append(
+ torch.Tensor((doc_id, cont_id, log_likelihood)).to(batch["continuation"][idx].device)
+ )
+ self.labels.append(
+ torch.LongTensor((doc_id, cont_id, batch["label_id"][idx])).to(batch["label_id"][idx].device)
+ )
+
+ def compute(self) -> torch.Tensor:
+ # states should have been synced from all accelerators at this point
+ # account for duplicates here because of DistributedSampler compensating for drop_last=False
+ loglikelihood_dict: Dict[int, Dict[int, float]] = {}
+ label_dict = {}
+
+ # collect labels
+ for doc_id, cont_id, label_id in self.labels:
+ if doc_id.item() not in label_dict:
+ label_dict[doc_id.item()] = label_id.item()
+
+ # collect loglikelihoods
+ for doc_id, cont_id, loglikelihood in self.loglikelihoods:
+ if int(doc_id.item()) not in loglikelihood_dict:
+ loglikelihood_dict[int(doc_id.item())] = {}
+
+ if int(cont_id.item()) not in loglikelihood_dict[int(doc_id.item())]:
+ loglikelihood_dict[int(doc_id.item())][int(cont_id.item())] = loglikelihood
+
+ # compute acc
+ correct = []
+ preds: Optional[List[float]] = None
+ labels: Optional[List[int]] = None
+ if self.metric_type == "f1":
+ preds = []
+ labels = []
+
+ for doc_id in loglikelihood_dict:
+ # each doc_id might have a different number of continuation
+ num_continuations = len(loglikelihood_dict[doc_id].keys())
+ loglikelihoods = torch.tensor([-float("inf")] * num_continuations)
+
+ skip_document = False
+ for cont_id in loglikelihood_dict[doc_id]:
+ try:
+ loglikelihoods[cont_id] = loglikelihood_dict[doc_id][cont_id]
+ except IndexError:
+ # We didn't process all of the continuations, so skip this document.
+ skip_document = True
+ break
+
+ if skip_document:
+ continue
+
+ correct.append(1.0 if torch.argmax(loglikelihoods).item() == label_dict[doc_id] else 0.0)
+
+ if self.metric_type == "f1":
+ assert preds is not None
+ assert labels is not None
+ preds.append(torch.argmax(loglikelihoods).item())
+ labels.append(label_dict[doc_id])
+
+ if self.metric_type == "f1":
+ assert preds is not None
+ assert labels is not None
+ # for NLI tasks, continuations are yes, no, neither, so idx=0 assigned to pos label
+ score = f1_score(labels, preds, pos_label=0)
+ else:
+ score = sum(correct) / len(correct)
+
+ return torch.tensor(score)
+
+
+class ICLMultiChoiceTaskDataset(metaclass=abc.ABCMeta):
+ """Only supports zero-shot for now."""
+
+ metric_type: ClassVar[str]
+
+ def __init__(
+ self,
+ tokenizer: Tokenizer,
+ dataset_path: str,
+ dataset_name: Optional[str] = None,
+ model_ctx_len: int = 2048,
+ ):
+ super().__init__()
+
+ self.tokenizer = tokenizer
+ self.dataset_path = dataset_path
+ self.dataset_name = dataset_name
+ self.model_ctx_len = model_ctx_len
+
+ self.samples: List[Dict[str, Any]] = []
+ self.dataset = datasets.load_dataset(
+ path=self.dataset_path,
+ name=self.dataset_name,
+ split="validation",
+ )
+
+ # prep examples
+ self.prep_examples()
+
+ def __getitem__(self, index):
+ return self.samples[index]
+
+ def __len__(self):
+ return len(self.samples)
+
+ def prep_examples(self):
+ """Append doc_ids to each example so that they are processed together in the metric"""
+ doc_id = 0
+ for doc in self.dataset:
+ # from EAI harness
+ # how this all works:
+ # CTX CONT
+ # inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
+ # gpt2 \ \
+ # logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
+ # cont_toks 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
+
+ continuations = self.doc_to_continuations(doc)
+ label_id = self.doc_to_label(doc)
+ ctx = self.token_encode(self.doc_to_text(doc))
+ dc = self.token_encode(self.doc_to_domain_conditional(doc))
+
+ for cont_id, continuation_str in enumerate(continuations):
+ cont_str_len = len(continuation_str) - 1 # continuation contain leading blank
+ continuation = self.token_encode(continuation_str)
+
+ # query, remove last token from continuation, truncate from left is longer than model ctx length
+ query = ctx + continuation[:-1]
+ query = query[-self.model_ctx_len :]
+
+ # get domain conditional query
+ # we don't expect this to be longer than self.model_ctx_len and it won't make sense to truncate from left
+ dc_query = dc + continuation[:-1]
+
+ # form a sample
+ self.samples.append(
+ {
+ "doc_id": doc_id,
+ "cont_id": cont_id,
+ "ctx": ctx,
+ "continuation": continuation,
+ "ctx_len": len(ctx),
+ "dc_len": len(dc),
+ "cont_len": len(
+ continuation
+ ), # even if query has last token removed, LM will output same cont len
+ "cont_str_len": cont_str_len,
+ "query": query, # remove last token from continuation
+ "dc_query": dc_query,
+ "label_id": label_id,
+ }
+ )
+
+ doc_id += 1
+
+ def pad_tokens_until_max(self, tokens, max_len=2048):
+ """truncate from left if len(tokens) > model_ctx_len, max_len is not considered then
+ queries are already truncated at max length of model_ctx_len
+ this acts as additional check for all types of sequences in the batch
+ """
+ if len(tokens) > self.model_ctx_len:
+ return tokens[-self.model_ctx_len :]
+ else:
+ # pad to max_len, but check again if this padding exceeded self.model_ctx_len
+ # this time truncate from right side of the sequence because additional padding caused len(tokens) > self.model_ctx_len
+ tokens = tokens + [self.tokenizer.pad_token_id] * (max_len - len(tokens))
+
+ if len(tokens) > self.model_ctx_len:
+ tokens = tokens[: self.model_ctx_len]
+
+ return tokens
+
+ def collate_fn(self, data):
+ # pad to max length
+ # 'ctx', 'continuation', 'query' can all have variable length
+ max_ctx_len = 0
+ max_cont_len = 0
+ max_query_len = 0
+ max_dc_query_len = 0
+
+ for sample in data:
+ if len(sample["ctx"]) > max_ctx_len:
+ max_ctx_len = len(sample["ctx"])
+
+ if len(sample["continuation"]) > max_cont_len:
+ max_cont_len = len(sample["continuation"])
+
+ if len(sample["query"]) > max_query_len:
+ max_query_len = len(sample["query"])
+
+ if len(sample["dc_query"]) > max_dc_query_len:
+ max_dc_query_len = len(sample["dc_query"])
+
+ doc_ids = []
+ cont_ids = []
+ ctxs = []
+ continuations = []
+ ctx_lens = []
+ dc_lens = []
+ cont_lens = []
+ cont_str_lens = []
+ queries = []
+ dc_queries = []
+ label_ids = []
+
+ # pad according to max_lengths
+ for sample in data:
+ doc_ids.append(sample["doc_id"])
+ cont_ids.append(sample["cont_id"])
+
+ ctxs.append(torch.LongTensor(self.pad_tokens_until_max(sample["ctx"], max_len=max_ctx_len)))
+ continuations.append(
+ torch.LongTensor(self.pad_tokens_until_max(sample["continuation"], max_len=max_cont_len))
+ )
+
+ ctx_lens.append(sample["ctx_len"])
+ dc_lens.append(sample["dc_len"])
+ cont_lens.append(sample["cont_len"])
+ cont_str_lens.append(sample["cont_str_len"])
+
+ queries.append(torch.LongTensor(self.pad_tokens_until_max(sample["query"], max_len=max_query_len)))
+ dc_queries.append(
+ torch.LongTensor(self.pad_tokens_until_max(sample["dc_query"], max_len=max_dc_query_len))
+ )
+
+ label_ids.append(sample["label_id"])
+
+ batch = {
+ "doc_id": torch.LongTensor(doc_ids),
+ "cont_id": torch.LongTensor(cont_ids),
+ "ctx": torch.stack(ctxs),
+ "continuation": torch.stack(continuations),
+ "ctx_len": torch.LongTensor(ctx_lens),
+ "dc_len": torch.LongTensor(dc_lens),
+ "cont_len": torch.LongTensor(cont_lens), # since query has last token removed from continuation
+ "cont_str_len": torch.LongTensor(cont_str_lens),
+ "input_ids": torch.stack(queries),
+ "dc_input_ids": torch.stack(dc_queries),
+ "label_id": torch.LongTensor(label_ids),
+ }
+
+ return batch
+
+ def token_encode(self, string: str) -> List[int]:
+ return self.tokenizer.encode(string, add_special_tokens=False)
+
+ def token_decode(self, tokens: List[int]) -> str:
+ return self.tokenizer.decode(tokens)
+
+ @abc.abstractmethod
+ def doc_to_text(self, doc) -> str:
+ """Match EAI eval harness
+ returns a single context string
+ """
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def doc_to_continuations(self, doc) -> List[str]:
+ """Match EAI eval harness
+ returns a list of continuations
+ """
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def doc_to_label(self, doc) -> int:
+ """Match EAI eval harness
+ returns continuation id which corresponds to true label
+ """
+ raise NotImplementedError
+
+ def doc_to_domain_conditional(self, doc) -> str:
+ """Provide string for domain conditional normalization
+ by default its blank string, continuation normalized by prob conditioned on a blank
+ """
+ del doc
+ return " "
+
+
+class PIQA(ICLMultiChoiceTaskDataset):
+ """PIQA sends context in the following fashion: "Question: GOAL\nAnswer:"
+ space added as prefix to each continuation
+
+ implement PMI_DC
+
+ {
+ 'goal': "How do I ready a guinea pig cage for it's new occupants?",
+ 'sol1': 'Provide the guinea pig with a cage full of a few inches of bedding made of ripped paper strips, you will also need to supply it with a water bottle and a food dish.',
+ 'sol2': 'Provide the guinea pig with a cage full of a few inches of bedding made of ripped jeans material, you will also need to supply it with a water bottle and a food dish.',
+ 'label': 0
+ }
+ """
+
+ metric_type = "len_norm"
+
+ def __init__(self, tokenizer, dataset_path="piqa", dataset_name=None):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return "Question: " + doc["goal"] + "\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ return [" " + doc["sol1"], " " + doc["sol2"]]
+
+ def doc_to_label(self, doc):
+ return doc["label"]
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class HellaSwag(ICLMultiChoiceTaskDataset):
+ """HellaSwag concats "ACTIVITY_LABEL: CTX_A CTX_B.capitalize()" to form context and then sends endings as continuations
+ space added as prefix to each continuation
+
+ {
+ 'activity_label': 'Roof shingle removal',
+ 'ctx_a': 'A man is sitting on a roof.',
+ 'ctx_b': 'he',
+ 'ctx': 'A man is sitting on a roof. he',
+ 'endings': ['is using wrap to wrap a pair of skis.', 'is ripping level tiles off.', "is holding a rubik's cube.", 'starts pulling up roofing on a roof.'],
+ 'label': '3'
+ }
+ """
+
+ metric_type = "len_norm"
+
+ def __init__(self, tokenizer, dataset_path="hellaswag", dataset_name=None):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ @classmethod
+ def preprocess(cls, text):
+ text = text.strip()
+ # NOTE: Brackets are artifacts of the WikiHow dataset portion of HellaSwag.
+ text = text.replace(" [title]", ". ")
+ text = re.sub("\\[.*?\\]", "", text)
+ text = text.replace(" ", " ")
+
+ return text
+
+ def doc_to_text(self, doc):
+ return self.preprocess(doc["activity_label"] + ": " + doc["ctx_a"] + " " + doc["ctx_b"].capitalize())
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ return [" " + self.preprocess(ending) for ending in doc["endings"]]
+
+ def doc_to_label(self, doc):
+ return int(doc["label"])
+
+ def doc_to_domain_conditional(self, doc):
+ domain_conditional = self.preprocess(doc["ctx_b"].capitalize())
+
+ # ensure non 0 len domain conditional
+ if len(domain_conditional) == 0:
+ return self.preprocess(doc["ctx_a"]).split(" ")[-1]
+
+ return domain_conditional
+
+
+class WinoGrande(ICLMultiChoiceTaskDataset):
+ """Prompt: split sentence at _ "SENTENCE[:idx] + OPTION1/OPTION2", where idx = SENTENCE.index("_")
+ implement PMI_DC
+ acc, random at 50%
+ continuation is everything in setnence after '_' (" SENTENCE[idx:].strip()")
+
+ Req_loglikelihood('People think Samantha', ' is embarassed, because Samantha made snide comments about the shirt Rebecca was wearing.')
+ Req_loglikelihood('People think Rebecca', ' is embarassed, because Samantha made snide comments about the shirt Rebecca was wearing.')
+
+ {
+ 'sentence': 'People think _ is embarassed, because Samantha made snide comments about the shirt Rebecca was wearing.',
+ 'option1': 'Samantha',
+ 'option2': 'Rebecca',
+ 'answer': '2'
+ }
+
+ TODO: might need to write custom metric for Winogrande
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="winogrande", dataset_name="winogrande_xl"):
+ # all winogrande datasets have same val set
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def prep_examples(self):
+ """Overwrite for WinoGrande as multiple ctx, single continuation"""
+ doc_id = 0
+ for doc in self.dataset:
+ # here ctx is a list
+ ctxs = self.doc_to_text(doc)
+ dcs = self.doc_to_domain_conditional(doc)
+
+ continuation = self.doc_to_continuations(doc)
+ label_id = self.doc_to_label(doc)
+ cont_str_len = len(continuation) - 1 # continuations contain leading blank space
+
+ # tokenize
+ continuation = self.token_encode(continuation)
+
+ for cont_id, (ctx, dc) in enumerate(zip(ctxs, dcs)):
+ ctx = self.token_encode(ctx)
+ dc = self.token_encode(dc)
+
+ # query, remove last token from continuation, truncate from left is longer than model ctx length
+ query = ctx + continuation[:-1]
+ query = query[-self.model_ctx_len :]
+
+ # get domain conditional query
+ # we don't expect this to be longer than self.model_ctx_len and it won't make sense to truncate from left
+ dc_query = dc + continuation[:-1]
+
+ # form a sample
+ self.samples.append(
+ {
+ "doc_id": doc_id,
+ "cont_id": cont_id,
+ "ctx": ctx,
+ "continuation": continuation,
+ "ctx_len": len(ctx),
+ "dc_len": len(dc),
+ "cont_len": len(
+ continuation
+ ), # even if query has last token removed, LM will output same cont len
+ "cont_str_len": cont_str_len,
+ "query": query, # remove last token from continuation
+ "dc_query": dc_query,
+ "label_id": label_id,
+ }
+ )
+
+ doc_id += 1
+
+ def doc_to_text(self, doc):
+ # special case where there are multiple ctx and single continuation
+ pronoun_loc = doc["sentence"].index("_")
+
+ ctx = []
+ for option in [doc["option1"], doc["option2"]]:
+ ctx.append(doc["sentence"][:pronoun_loc] + option)
+
+ return ctx
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ pronoun_loc = doc["sentence"].index("_") + 1
+ return " " + doc["sentence"][pronoun_loc:].strip()
+
+ def doc_to_label(self, doc):
+ return int(doc["answer"]) - 1
+
+ def doc_to_domain_conditional(self, doc):
+ """same number of domain conditionals as context"""
+ return [doc["option1"], doc["option2"]]
+
+
+class OpenBookQA(ICLMultiChoiceTaskDataset):
+ """OBQA: question_stem is sent as context (no special prompt format) and choices are sent as continuation
+ space added as prefix to each continuation
+
+ implement PMI_DC
+
+ {
+ 'question_stem': 'Frilled sharks and angler fish live far beneath the surface of the ocean, which is why they are known as',
+ 'choices': {'text': ['Deep sea animals', 'fish', 'Long Sea Fish', 'Far Sea Animals'],
+ 'label': ['A', 'B', 'C', 'D']},
+ 'answerKey': 'A'
+ }
+ """
+
+ metric_type = "len_norm"
+
+ def __init__(self, tokenizer, dataset_path="openbookqa", dataset_name=None):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return doc["question_stem"]
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ return [" " + choice for choice in doc["choices"]["text"]]
+
+ def doc_to_label(self, doc):
+ return ["A", "B", "C", "D"].index(doc["answerKey"].strip())
+
+ def doc_to_domain_conditional(self, doc):
+ return doc["question_stem"].strip().split(" ")[-1]
+
+
+class BoolQ(ICLMultiChoiceTaskDataset):
+ """Prompt: "PASSAGE\nQuestion: QUESTION?\nAnswer:"
+ acc, random at 50% (SuperGLUE)
+ continuation: yes, no
+
+ {
+ 'question': 'is ncis new orleans over for the season',
+ 'passage': 'NCIS: New Orleans (season 4) -- The fourth season of NCIS: New Orleans premiered on September 26, 2017 on CBS. The series continues to air following Bull, Tuesday at 10:00 p.m. (ET) and contained 24 episodes. The season concluded on May 15, 2018.',
+ 'label': 1
+ }
+ """
+
+ metric_type = "pmi_dc"
+
+ def __init__(self, tokenizer, dataset_path="boolq", dataset_name=None):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return doc["passage"] + "\nQuestion: " + doc["question"] + "?\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ del doc
+ # add spaces in front of continuation
+ return [" yes", " no"]
+
+ def doc_to_label(self, doc):
+ # if doc['answer'] is True, return index of " yes" which is 0
+ if doc["answer"]:
+ return 0
+ else:
+ return 1
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class SciQ(ICLMultiChoiceTaskDataset):
+ """SciQ sends context as "SUPPORT\nQuestion: QUESTION\nAnswer:" and then distractors + correct_answer as continuations
+ space added as prefix to each continuation
+
+ implement PMI_DC
+
+ {
+ 'question': 'Who proposed the theory of evolution by natural selection?',
+ 'distractor3': 'Scopes',
+ 'distractor1': 'Linnaeus',
+ 'distractor2': 'shaw',
+ 'correct_answer': 'darwin',
+ 'support': ''
+ }
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="sciq", dataset_name=None):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return doc["support"] + "\nQuestion: " + doc["question"] + "\nAnswer:".strip()
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ return [
+ " " + doc["distractor1"],
+ " " + doc["distractor2"],
+ " " + doc["distractor3"],
+ " " + doc["correct_answer"],
+ ]
+
+ def doc_to_label(self, doc):
+ del doc
+ return 3
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class ArcEasy(ICLMultiChoiceTaskDataset):
+ """ArcEasy creates context with "Question: QUESTION\nAnswer:" and sends the choices as continuations
+ space added as prefix to each continuation
+
+ {
+ 'question': 'Which technology was developed most recently?',
+ 'choices': {'text': ['cellular telephone', 'television', 'refrigerator', 'airplane'],
+ 'label': ['A', 'B', 'C', 'D']},
+ 'answerKey': 'A'
+ }
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="ai2_arc", dataset_name="ARC-Easy"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return "Question: " + doc["question"] + "\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ return [" " + choice for choice in doc["choices"]["text"]]
+
+ def doc_to_label(self, doc):
+ # some doc["answerKey"] are stored as numbers
+ num_to_letter = {"1": "A", "2": "B", "3": "C", "4": "D", "5": "E"}
+
+ if doc["answerKey"] in num_to_letter:
+ doc["answerKey"] = num_to_letter[doc["answerKey"]]
+
+ return ["A", "B", "C", "D", "E"].index(doc["answerKey"])
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class ArcChallenge(ArcEasy):
+ """ArcChallenge follows the same prompt format as ArcEasy.
+ implement PMI_DC
+ """
+
+ metric_type = "pmi_dc"
+
+ def __init__(self, tokenizer, dataset_path="ai2_arc", dataset_name="ARC-Challenge"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+
+class COPA(ICLMultiChoiceTaskDataset):
+ """Prompt: "PREMISE.strip()[:-1] because/therefore"
+ Req_loglikelihood('The pair of students came under scrutiny by the teacher because', ' the students both received excellent grades.'
+ continuations: CHOICE1/CHOICE2
+
+ "cause": "because",
+ "effect": "therefore",
+
+ implement PMI_DC
+ acc, random at 50%
+
+ {
+ 'premise': 'The pair of students came under scrutiny by the teacher.',
+ 'choice1': 'The students both received excellent grades.',
+ 'choice2': 'Their responses on the assignment were identical.',
+ 'question': 'cause',
+ 'label': 1
+ }
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="super_glue", dataset_name="copa"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ connector = "because" if doc["question"] == "cause" else "therefore"
+
+ # remove the period
+ return doc["premise"].strip()[:-1] + " " + connector
+
+ def doc_to_continuations(self, doc):
+ # add spaces in front of continuation
+ def convert_choice(choice):
+ return choice[0].lower() + choice[1:]
+
+ return [" " + convert_choice(doc["choice1"]), " " + convert_choice(doc["choice2"])]
+
+ def doc_to_label(self, doc):
+ return doc["label"]
+
+ def doc_to_domain_conditional(self, doc):
+ return "because" if doc["question"] == "cause" else "therefore"
+
+
+class RTE(ICLMultiChoiceTaskDataset):
+ """Prompt: "SENTENCE1\nQuestion: SENTENCE2 True or False?\nAnswer:"
+ implement PMI_DC
+ acc, random at 50% (GLUE)
+ continuations: True, False
+
+ {
+ 'sentence1': 'The number of Danes opposed to swapping the krone for the euro has increased slightly to 35.3 percent, up from 34.6 percent in April, according to a poll published on Thursday by Danske Bank.',
+ 'sentence2': 'The introduction of the euro has been opposed.',
+ 'label': 0,
+ }
+ """
+
+ metric_type = "len_norm"
+
+ def __init__(self, tokenizer, dataset_path="glue", dataset_name="rte"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return doc["sentence1"] + "\nQuestion: " + doc["sentence2"] + " True or False?\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ del doc
+ # add spaces in front of continuation
+ return [" True", " False"]
+
+ def doc_to_label(self, doc):
+ return doc["label"]
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class CommitmentBank(ICLMultiChoiceTaskDataset):
+ """Prompt: "PREMISE\nQuestion: HYPOTHESIS. True, False or Neither?\nAnswer:"
+ continuations: True, False, Neither
+
+ implement PMI_DC
+ acc/F1, random at 33% acc. (SuperGLUE)
+
+ {
+ 'premise': 'Then they would awake, terrified and sweating, to find themselves in white starched linen, in a comfortable bed, in peaceful England. And all would be well. It may be said that although he survived it the siege nevertheless had a bad effect on the Collector.',
+ 'hypothesis': 'the siege nevertheless had a bad effect on the Collector',
+ 'label': 0
+ }
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="super_glue", dataset_name="cb"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ def doc_to_text(self, doc):
+ return doc["premise"] + "\nQuestion: " + doc["hypothesis"] + ". True, False or Neither?\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ del doc
+ # add spaces in front of continuation
+ return [" True", " False", " Neither"]
+
+ def doc_to_label(self, doc):
+ return doc["label"]
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class MRPC(ICLMultiChoiceTaskDataset):
+ """Prompt for MRPC is formed using "Sentence 1: SENTENCE1\nSentence 2: SENTENCE2\nQuestion: Do both sentences mean the same thing?\nAnswer:"
+ acc/F1, random at 50% acc. (GLUE)
+ continuations: yes and no
+
+ {
+ 'sentence1': 'In fiction : Edward P. Jones ( " The Known World " ) and Scott Spencer ( " A Ship Made of Paper " ) .',
+ 'sentence2': 'The fifth nominee for fiction is Scott Spencer , for A Ship Made of Paper .',
+ 'label': 0
+ }
+ """
+
+ metric_type = "f1"
+
+ def __init__(self, tokenizer, dataset_path="glue", dataset_name="mrpc"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ @classmethod
+ def preprocess(cls, string: str) -> str:
+ string = string.replace(" n't", "n't")
+ string = string.replace(" )", ")")
+ string = string.replace("( ", "(")
+ string = string.replace('" ', '"')
+ string = string.replace(' "', '"')
+
+ string = re.sub(r" (['.,])", r"\1", string)
+
+ return string
+
+ def doc_to_text(self, doc):
+ return (
+ "Sentence 1: "
+ + self.preprocess(doc["sentence1"])
+ + "\nSentence 2: "
+ + self.preprocess(doc["sentence2"])
+ + "\nQuestion: Do both sentences mean the same thing?\nAnswer:"
+ )
+
+ def doc_to_continuations(self, doc):
+ del doc
+ # add spaces in front of continuation
+ return [" yes", " no"]
+
+ def doc_to_label(self, doc):
+ # if doc['label'] is True, return index of " yes" which is 0
+ if doc["label"]:
+ return 0
+ else:
+ return 1
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+class SST2(ICLMultiChoiceTaskDataset):
+ """SST2 task formats prompts as "SENTENCE\nQuestion: Is this sentence positive or negative?\nAnswer:"
+ some preprocessing done on sentence
+
+ constructs 2 requests, 1 for positive and another for negative
+ positive and negative have just 1 token in tokenizer
+ positive: 1313
+ negative: 2430
+
+ implement PMI_DC
+ acc, random at 50% (GLUE)
+
+ {
+ 'sentence': "harrison 's flowers puts its heart in the right place , but its brains are in no particular place at all . ",
+ 'label': 1,
+ }
+ """
+
+ metric_type = "acc"
+
+ def __init__(self, tokenizer, dataset_path="glue", dataset_name="sst2"):
+ super().__init__(
+ tokenizer=tokenizer,
+ dataset_path=dataset_path,
+ dataset_name=dataset_name,
+ )
+
+ @classmethod
+ def preprocess(cls, string: str) -> str:
+ string = string.replace(" n't", "n't")
+ string = string.replace(" )", ")")
+ string = string.replace("( ", "(")
+ string = string.replace('" ', '"')
+ string = string.replace(' "', '"')
+
+ string = re.sub(r" (['.,])", r"\1", string)
+
+ return string
+
+ def doc_to_text(self, doc):
+ return self.preprocess(doc["sentence"]) + "\nQuestion: Is this sentence positive or negative?\nAnswer:"
+
+ def doc_to_continuations(self, doc):
+ del doc
+ # add spaces in front of continuation
+ # # {1: "positive", 0: "negative"}
+ return [" negative", " positive"]
+
+ def doc_to_label(self, doc):
+ # {1: "positive", 0: "negative"}
+ return doc["label"]
+
+ def doc_to_domain_conditional(self, doc):
+ del doc
+ return "Answer:"
+
+
+label_to_task_map = {
+ "piqa": PIQA,
+ "hellaswag": HellaSwag,
+ "winogrande": WinoGrande,
+ "openbook_qa": OpenBookQA,
+ "boolq": BoolQ,
+ "sciq": SciQ,
+ "arc_easy": ArcEasy,
+ "arc_challenge": ArcChallenge,
+ "copa": COPA,
+ "rte": RTE,
+ "commitment_bank": CommitmentBank,
+ "mrpc": MRPC,
+ "sst2": SST2,
+}
diff --git a/venv/lib/python3.10/site-packages/olmo/eval/evaluator.py b/venv/lib/python3.10/site-packages/olmo/eval/evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddc85a6035ff646f5efcaffa185295058a2da7ed
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/eval/evaluator.py
@@ -0,0 +1,83 @@
+from dataclasses import dataclass
+from typing import Any, Dict, Optional, Union
+
+import torch
+from torch.utils.data import DataLoader
+from torchmetrics import MeanMetric, Metric
+
+from ..config import EvaluatorType
+from .downstream import ICLMetric
+
+__all__ = ["Evaluator"]
+
+
+@dataclass
+class Evaluator:
+ label: str
+ type: EvaluatorType
+ eval_loader: DataLoader
+ eval_metric: Union[Metric, Dict[str, Metric]]
+ subset_num_batches: Optional[int] = None
+
+ def reset_metrics(self) -> None:
+ if isinstance(self.eval_metric, Metric):
+ self.eval_metric.reset()
+ else:
+ for metric in self.eval_metric.values():
+ metric.reset()
+
+ def compute_metrics(self) -> Dict[str, float]:
+ if self.type == EvaluatorType.downstream:
+ assert isinstance(self.eval_metric, ICLMetric)
+ return {
+ f"eval/downstream/{self.label}_{self.eval_metric.metric_type}": self.eval_metric.compute().item(),
+ }
+ elif self.type == EvaluatorType.lm:
+ # Metric(s) = cross entropy loss
+ metrics: Dict[str, Metric]
+ if isinstance(self.eval_metric, Metric):
+ metrics = {self.label: self.eval_metric}
+ else:
+ metrics = self.eval_metric
+ out = {}
+ for label in sorted(metrics.keys()):
+ metric = metrics[label]
+ assert isinstance(metric, MeanMetric)
+ if metric.weight.item() == 0.0: # type: ignore
+ # In this case we probably haven't called '.update()' on this metric yet,
+ # so we do so here with dummy values. Since we pass 0.0 in for weight this won't
+ # affect the final value.
+ # This can happen when the evaluator contains multiple tasks/datasets and we didn't
+ # get to this one within the current evaluation loop.
+ metric.update(0.0, 0.0)
+ loss = metric.compute()
+ if loss.isnan().item():
+ # This can happen when the evaluator contains multiple tasks/datasets and we didn't
+ # get to this one within the current evaluation loop.
+ continue
+ else:
+ out[f"eval/{label}/CrossEntropyLoss"] = loss.item()
+ out[f"eval/{label}/Perplexity"] = torch.exp(loss).item()
+ return out
+ else:
+ raise ValueError(f"Unexpected evaluator type '{self.type}'")
+
+ def update_metrics(
+ self,
+ batch: Dict[str, Any],
+ ce_loss: torch.Tensor,
+ logits: torch.Tensor,
+ ) -> None:
+ if self.type == EvaluatorType.downstream:
+ assert isinstance(self.eval_metric, ICLMetric)
+ self.eval_metric.update(batch, logits) # type: ignore
+ elif self.type == EvaluatorType.lm:
+ # Metric(s) = cross entropy loss
+ for metadata, instance_loss in zip(batch["metadata"], ce_loss):
+ if isinstance(self.eval_metric, dict):
+ metric = self.eval_metric[metadata["label"]]
+ else:
+ metric = self.eval_metric
+ metric.update(instance_loss)
+ else:
+ raise ValueError(f"Unexpected evaluator type '{self.type}'")
diff --git a/venv/lib/python3.10/site-packages/olmo/exceptions.py b/venv/lib/python3.10/site-packages/olmo/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..754580c959a86c1542242cdcea9a47b34fa38ea7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/exceptions.py
@@ -0,0 +1,37 @@
+__all__ = ["OlmoError", "OlmoConfigurationError", "OlmoCliError", "OlmoEnvironmentError", "OlmoNetworkError"]
+
+
+class OlmoError(Exception):
+ """
+ Base class for all custom OLMo exceptions.
+ """
+
+
+class OlmoConfigurationError(OlmoError):
+ """
+ An error with a configuration file.
+ """
+
+
+class OlmoCliError(OlmoError):
+ """
+ An error from incorrect CLI usage.
+ """
+
+
+class OlmoEnvironmentError(OlmoError):
+ """
+ An error from incorrect environment variables.
+ """
+
+
+class OlmoNetworkError(OlmoError):
+ """
+ An error with a network request.
+ """
+
+
+class OlmoThreadError(Exception):
+ """
+ Raised when a thread fails.
+ """
diff --git a/venv/lib/python3.10/site-packages/olmo/initialization.py b/venv/lib/python3.10/site-packages/olmo/initialization.py
new file mode 100644
index 0000000000000000000000000000000000000000..260e9475733db909ce6df0a55cc14d123ec1a6ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/initialization.py
@@ -0,0 +1,95 @@
+import math
+from typing import Optional, Union
+
+import torch
+import torch.nn as nn
+
+from .config import InitFnType, ModelConfig
+from .util import StrEnum
+
+__all__ = ["init_weights", "ModuleType"]
+
+
+class ModuleType(StrEnum):
+ in_module = "in"
+ out_module = "out"
+ emb = "emb"
+ final_out = "final_out"
+
+
+def init_weights(
+ config: ModelConfig,
+ module: Union[nn.Linear, nn.Embedding],
+ d: Optional[int] = None,
+ layer_id: Optional[int] = None,
+ std_factor: float = 1.0,
+ type_of_module: Optional[ModuleType] = None,
+) -> None:
+ """
+ Initialize weights of a linear or embedding module.
+
+ :param config: The model config.
+ :param module: The linear or embedding submodule to initialize.
+ :param d: The effective input dimensionality of the weights. This could be smaller than the actual dimensions
+ for fused layers.
+ :param layer_id: When set, the standard deviation for the "mitchell" method will be adjusted by
+ ``1 / sqrt(2 * (layer_id + 1))``.
+ """
+ d = d if d is not None else config.d_model
+ if config.init_fn == InitFnType.normal:
+ std = config.init_std * std_factor
+ if config.init_cutoff_factor is not None:
+ cutoff_value = config.init_cutoff_factor * std
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-cutoff_value, b=cutoff_value)
+ else:
+ nn.init.normal_(module.weight, mean=0.0, std=std)
+ elif config.init_fn == InitFnType.mitchell:
+ std = std_factor / math.sqrt(d)
+ if layer_id is not None:
+ std = std / math.sqrt(2 * (layer_id + 1))
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-3 * std, b=3 * std)
+ elif config.init_fn == InitFnType.kaiming_normal:
+ nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
+ elif config.init_fn == InitFnType.fan_in:
+ std = std_factor / math.sqrt(d)
+ nn.init.normal_(module.weight, mean=0.0, std=std)
+ elif config.init_fn == InitFnType.full_megatron:
+ if type_of_module is None:
+ raise RuntimeError(f"When using the {InitFnType.full_megatron} init, every module must have a type.")
+
+ cutoff_factor = config.init_cutoff_factor
+ if cutoff_factor is None:
+ cutoff_factor = 3
+
+ if type_of_module == ModuleType.in_module:
+ # for att_proj (same as QKV), ff_proj
+ std = config.init_std
+ elif type_of_module == ModuleType.out_module:
+ # for attn_out, ff_out
+ std = config.init_std / math.sqrt(2.0 * config.n_layers)
+ elif type_of_module == ModuleType.emb:
+ # positional embeddings (wpe)
+ # token embeddings (wte)
+ std = config.init_std
+ elif type_of_module == ModuleType.final_out:
+ # final output (ff_out)
+ std = config.d_model**-0.5
+ else:
+ raise RuntimeError(f"Unknown module type '{type_of_module}'")
+ nn.init.trunc_normal_(
+ module.weight,
+ mean=0.0,
+ std=std,
+ a=-cutoff_factor * std,
+ b=cutoff_factor * std,
+ )
+ else:
+ raise NotImplementedError(config.init_fn)
+
+ if isinstance(module, nn.Linear):
+ if module.bias is not None:
+ nn.init.zeros_(module.bias)
+
+ if config.init_fn == InitFnType.normal and getattr(module, "_is_residual", False):
+ with torch.no_grad():
+ module.weight.div_(math.sqrt(2 * config.n_layers))
diff --git a/venv/lib/python3.10/site-packages/olmo/model.py b/venv/lib/python3.10/site-packages/olmo/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..b635518cb6f61e1630005e796598174e4db0dca4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/model.py
@@ -0,0 +1,1654 @@
+"""
+Adapted from
+[MosaiclML](https://github.com/mosaicml/examples.git) and
+[minGPT](https://github.com/karpathy/minGPT.git)
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+from abc import abstractmethod
+from collections import defaultdict
+from collections.abc import MutableMapping
+from functools import partial
+from typing import (
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ NamedTuple,
+ Optional,
+ Sequence,
+ Set,
+ Tuple,
+ cast,
+)
+
+import torch
+import torch.backends.cuda
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import einsum
+
+from .aliases import PathOrStr
+from .beam_search import BeamSearch, Constraint, FinalSequenceScorer, Sampler
+from .config import (
+ ActivationCheckpointingStrategy,
+ ActivationType,
+ BlockType,
+ CheckpointType,
+ FSDPWrapStrategy,
+ LayerNormType,
+ ModelConfig,
+)
+from .exceptions import OlmoConfigurationError
+from .initialization import ModuleType, init_weights
+from .torch_util import ensure_finite_
+from .util import pass_through_fn
+
+__all__ = [
+ "LayerNormBase",
+ "LayerNorm",
+ "RMSLayerNorm",
+ "AMDLayerNorm",
+ "RotaryEmbedding",
+ "Activation",
+ "GELU",
+ "ReLU",
+ "SwiGLU",
+ "OlmoBlock",
+ "OlmoSequentialBlock",
+ "OlmoParallelBlock",
+ "Olmo",
+ "OlmoOutput",
+ "OlmoGenerateOutput",
+]
+
+
+log = logging.getLogger(__name__)
+
+
+def activation_checkpoint_function(cfg: ModelConfig):
+ preserve_rng_state = (
+ (cfg.attention_dropout == 0.0) and (cfg.embedding_dropout == 0.0) and (cfg.residual_dropout == 0.0)
+ )
+ from torch.utils.checkpoint import checkpoint
+
+ return partial(
+ checkpoint,
+ preserve_rng_state=preserve_rng_state,
+ use_reentrant=False,
+ )
+
+
+class BufferCache(dict, MutableMapping[str, torch.Tensor]):
+ """
+ Cache for attention biases and other things that would normally be stored as buffers.
+ We avoid using buffers because we've run into various issues doing so with FSDP.
+ In general it appears the way FSDP handles buffers is not well-defined.
+ It doesn't shard them but apparently it does synchronize them across processes, which we want to avoid
+ since (A) it isn't necessary, and (B) we sometimes have `-inf` in these biases which might get turned into
+ NaNs when they're synchronized due to casting or some other issue.
+ """
+
+
+def _non_meta_init_device(config: ModelConfig) -> torch.device:
+ if config.init_device is not None and config.init_device != "meta":
+ return torch.device(config.init_device)
+ else:
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+
+class Dropout(nn.Dropout):
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if self.p == 0.0:
+ return input
+ else:
+ return F.dropout(input, self.p, self.training, self.inplace)
+
+
+class LayerNormBase(nn.Module):
+ def __init__(
+ self,
+ config: ModelConfig,
+ *,
+ size: Optional[int] = None,
+ elementwise_affine: Optional[bool] = True,
+ eps: float = 1e-05,
+ ):
+ super().__init__()
+ self.config = config
+ self.eps = eps
+ self.normalized_shape = (size or config.d_model,)
+ if elementwise_affine or (elementwise_affine is None and self.config.layer_norm_with_affine):
+ self.weight = nn.Parameter(torch.ones(self.normalized_shape, device=config.init_device))
+ use_bias = self.config.bias_for_layer_norm
+ if use_bias is None:
+ use_bias = self.config.include_bias
+ if use_bias:
+ self.bias = nn.Parameter(torch.zeros(self.normalized_shape, device=config.init_device))
+ else:
+ self.register_parameter("bias", None)
+ else:
+ self.register_parameter("bias", None)
+ self.register_parameter("weight", None)
+
+ @abstractmethod
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ raise NotImplementedError
+
+ @classmethod
+ def build(cls, config: ModelConfig, size: Optional[int] = None, **kwargs) -> LayerNormBase:
+ if config.layer_norm_type == LayerNormType.default:
+ return LayerNorm(config, size=size, low_precision=False, **kwargs)
+ elif config.layer_norm_type == LayerNormType.low_precision:
+ return LayerNorm(config, size=size, low_precision=True, **kwargs)
+ elif config.layer_norm_type == LayerNormType.rms:
+ return RMSLayerNorm(config, size=size, **kwargs)
+ elif config.layer_norm_type == LayerNormType.amd_compatible:
+ return AMDLayerNorm(config, size=size, **kwargs)
+ else:
+ raise NotImplementedError(f"Unknown LayerNorm type: '{config.layer_norm_type}'")
+
+ def _cast_if_autocast_enabled(self, tensor: torch.Tensor, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
+ # `is_autocast_cpu_enabled()` for CPU autocast.
+ # See https://github.com/pytorch/pytorch/issues/110966.
+ if tensor.device.type == "cuda" and torch.is_autocast_enabled():
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_gpu_dtype())
+ elif tensor.device.type == "cpu" and torch.is_autocast_cpu_enabled():
+ return tensor.to(dtype=dtype if dtype is not None else torch.get_autocast_cpu_dtype())
+ else:
+ return tensor
+
+ def reset_parameters(self):
+ if self.weight is not None:
+ torch.nn.init.ones_(self.weight) # type: ignore
+ if self.bias is not None:
+ torch.nn.init.zeros_(self.bias) # type: ignore
+
+
+class LayerNorm(LayerNormBase):
+ """
+ The default :class:`LayerNorm` implementation which can optionally run in low precision.
+ """
+
+ def __init__(
+ self,
+ config: ModelConfig,
+ size: Optional[int] = None,
+ low_precision: bool = False,
+ elementwise_affine: Optional[bool] = None,
+ eps: float = 1e-05,
+ ):
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
+ self.low_precision = low_precision
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.low_precision:
+ module_device = x.device
+ downcast_x = self._cast_if_autocast_enabled(x)
+ downcast_weight = (
+ self._cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
+ )
+ downcast_bias = self._cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
+ with torch.autocast(enabled=False, device_type=module_device.type):
+ return F.layer_norm(
+ downcast_x, self.normalized_shape, weight=downcast_weight, bias=downcast_bias, eps=self.eps
+ )
+ else:
+ return F.layer_norm(x, self.normalized_shape, weight=self.weight, bias=self.bias, eps=self.eps)
+
+
+class AMDLayerNorm(LayerNormBase):
+ """
+ LayerNorm implemented using PyTorch primitives.
+
+ We do this to work around a bug in the PyTorch/ROCm implementation of layer norm that fails with a
+ segfault when the bias is not present.
+ """
+
+ def __init__(
+ self,
+ config: ModelConfig,
+ size: Optional[int] = None,
+ elementwise_affine: Optional[bool] = None,
+ eps: float = 1e-05,
+ ):
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ og_dtype = x.dtype
+ x = self._cast_if_autocast_enabled(x, dtype=torch.float32)
+ with torch.autocast(enabled=False, device_type=x.device.type):
+ var, mean = torch.var_mean(x, dim=-1, correction=0, keepdim=True)
+ var.add_(self.eps)
+ var.rsqrt_() # rsqrt should be more stable than 1/sqrt
+ x = var * (x - mean)
+ if self.weight is not None:
+ x.mul_(self.weight)
+ if self.bias is not None:
+ x.add_(self.bias)
+ return x.to(og_dtype)
+
+
+class RMSLayerNorm(LayerNormBase):
+ """
+ RMS layer norm, a simplified :class:`LayerNorm` implementation
+ """
+
+ def __init__(
+ self,
+ config: ModelConfig,
+ size: Optional[int] = None,
+ elementwise_affine: Optional[bool] = None,
+ eps: float = 1e-5,
+ ):
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ with torch.autocast(enabled=False, device_type=x.device.type):
+ og_dtype = x.dtype
+ x = x.to(torch.float32)
+ variance = x.pow(2).mean(-1, keepdim=True)
+ x = x * torch.rsqrt(variance + self.eps)
+ x = x.to(og_dtype)
+
+ if self.weight is not None:
+ if self.bias is not None:
+ return self.weight * x + self.bias
+ else:
+ return self.weight * x
+ else:
+ return x
+
+
+class RotaryEmbedding(nn.Module):
+ """
+ [Rotary positional embeddings (RoPE)](https://arxiv.org/abs/2104.09864).
+ """
+
+ def __init__(self, config: ModelConfig, cache: BufferCache):
+ super().__init__()
+ self.config = config
+ self.__cache = cache
+ # Warm up cache.
+ self.get_rotary_embedding(config.max_sequence_length, _non_meta_init_device(config))
+
+ def get_rotary_embedding(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
+ if (
+ (pos_sin := self.__cache.get("rope_pos_sin")) is not None
+ and (pos_cos := self.__cache.get("rope_pos_cos")) is not None
+ and pos_sin.shape[-2] >= seq_len
+ and pos_cos.shape[-2] >= seq_len
+ ):
+ if pos_sin.device != device:
+ pos_sin = pos_sin.to(device)
+ self.__cache["rope_pos_sin"] = pos_sin
+ if pos_cos.device != device:
+ pos_cos = pos_cos.to(device)
+ self.__cache["rope_pos_cos"] = pos_cos
+ return pos_sin[:, :, :seq_len, :], pos_cos[:, :, :seq_len, :]
+
+ with torch.autocast(device.type, enabled=False):
+ dim = self.config.d_model // self.config.n_heads
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, device=device, dtype=torch.float) / dim))
+ seq = torch.arange(seq_len, device=device, dtype=torch.float)
+ freqs = einsum("i , j -> i j", seq, inv_freq)
+ positions = torch.cat((freqs, freqs), dim=-1)
+ pos_sin, pos_cos = positions.sin()[None, None, :, :], positions.cos()[None, None, :, :]
+ self.__cache["rope_pos_sin"] = pos_sin
+ self.__cache["rope_pos_cos"] = pos_cos
+ return pos_sin, pos_cos
+
+ def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
+ B, nh, T, hs = x.size()
+ x = x.view(B, nh, T, 2, hs // 2)
+ x1, x2 = x.unbind(dim=-2)
+ return torch.cat((-x2, x1), dim=-1)
+
+ def apply_rotary_pos_emb(self, pos_sin: torch.Tensor, pos_cos: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
+ return ((t * pos_cos) + (self.rotate_half(t) * pos_sin)).to(t.dtype)
+
+ def forward(self, q: torch.Tensor, k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ if self.config.rope_full_precision:
+ q_, k_ = q.float(), k.float()
+ else:
+ q_, k_ = q, k
+
+ with torch.autocast(q.device.type, enabled=False):
+ query_len, key_len = q_.shape[-2], k_.shape[-2] # could be different if layer_past not None
+ pos_sin, pos_cos = self.get_rotary_embedding(key_len, q_.device)
+ pos_sin = pos_sin.type_as(q_)
+ pos_cos = pos_cos.type_as(q_)
+ q_ = self.apply_rotary_pos_emb(
+ pos_sin[:, :, key_len - query_len : key_len, :],
+ pos_cos[:, :, key_len - query_len : key_len, :],
+ q_,
+ )
+ k_ = self.apply_rotary_pos_emb(pos_sin, pos_cos, k_)
+ return q_.type_as(q), k_.type_as(k)
+
+
+class Activation(nn.Module):
+ def __init__(self, config: ModelConfig):
+ super().__init__()
+ self.config = config
+
+ @abstractmethod
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ raise NotImplementedError
+
+ @property
+ @abstractmethod
+ def output_multiplier(self) -> float:
+ raise NotImplementedError
+
+ @classmethod
+ def build(cls, config: ModelConfig) -> Activation:
+ if config.activation_type == ActivationType.gelu:
+ return cast(Activation, GELU(approximate="none"))
+ elif config.activation_type == ActivationType.relu:
+ return cast(Activation, ReLU(inplace=False))
+ elif config.activation_type == ActivationType.swiglu:
+ return SwiGLU(config)
+ else:
+ raise NotImplementedError(f"Unknown activation: '{config.activation_type}'")
+
+
+class GELU(nn.GELU):
+ @property
+ def output_multiplier(self) -> float:
+ return 1.0
+
+
+class ReLU(nn.ReLU):
+ @property
+ def output_multiplier(self) -> float:
+ return 1.0
+
+
+class SwiGLU(Activation):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x, gate = x.chunk(2, dim=-1)
+ return F.silu(gate) * x
+
+ @property
+ def output_multiplier(self) -> float:
+ return 0.5
+
+
+def causal_attention_bias(seq_len: int, device: torch.device) -> torch.FloatTensor:
+ att_bias = torch.triu(
+ torch.ones(seq_len, seq_len, device=device, dtype=torch.float),
+ diagonal=1,
+ )
+ att_bias.masked_fill_(att_bias == 1, torch.finfo(att_bias.dtype).min)
+ return att_bias.view(1, 1, seq_len, seq_len) # type: ignore
+
+
+def get_causal_attention_bias(cache: BufferCache, seq_len: int, device: torch.device) -> torch.Tensor:
+ if (causal_bias := cache.get("causal_attention_bias")) is not None and causal_bias.shape[-1] >= seq_len:
+ if causal_bias.device != device:
+ causal_bias = causal_bias.to(device)
+ cache["causal_attention_bias"] = causal_bias
+ return causal_bias
+ with torch.autocast(device.type, enabled=False):
+ causal_bias = causal_attention_bias(seq_len, device)
+ cache["causal_attention_bias"] = causal_bias
+ return causal_bias
+
+
+def alibi_attention_bias(seq_len: int, config: ModelConfig, device: torch.device) -> torch.FloatTensor:
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, 1, seq_len)
+
+ # shape: (1, 1, seq_len, seq_len)
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.float, device=device).view(1, 1, seq_len, 1)
+ alibi_bias.abs_().mul_(-1)
+
+ # shape: (n_heads,)
+ m = torch.arange(1, config.n_heads + 1, dtype=torch.float, device=device)
+ m.mul_(config.alibi_bias_max / config.n_heads)
+
+ # shape: (1, n_heads, seq_len, seq_len)
+ return alibi_bias * (1.0 / (2 ** m.view(1, config.n_heads, 1, 1))) # type: ignore
+
+
+class OlmoBlock(nn.Module):
+ """
+ A base class for transformer block implementations.
+ """
+
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
+ super().__init__()
+ self.layer_id = layer_id
+ self.config = config
+ self.hidden_size = (
+ config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
+ )
+ self.__cache = cache
+ assert config.d_model % config.n_heads == 0
+
+ self._activation_checkpoint_fn = pass_through_fn
+
+ # Dropout.
+ self.dropout = Dropout(config.residual_dropout)
+
+ # Layer norms.
+ self.k_norm: Optional[LayerNormBase] = None
+ self.q_norm: Optional[LayerNormBase] = None
+ if config.attention_layer_norm:
+ self.k_norm = LayerNormBase.build(
+ config,
+ size=config.d_model // config.n_heads if config.multi_query_attention else None,
+ elementwise_affine=config.attention_layer_norm_with_affine,
+ )
+ self.q_norm = LayerNormBase.build(config, elementwise_affine=config.attention_layer_norm_with_affine)
+
+ # Activation function.
+ self.act = Activation.build(config)
+ assert (self.act.output_multiplier * self.hidden_size) % 1 == 0
+
+ # Attention output projection.
+ self.attn_out = nn.Linear(
+ config.d_model, config.d_model, bias=config.include_bias, device=config.init_device
+ )
+
+ # Feed-forward output projection.
+ self.ff_out = nn.Linear(
+ int(self.act.output_multiplier * self.hidden_size),
+ config.d_model,
+ bias=config.include_bias,
+ device=config.init_device,
+ )
+ self.ff_out._is_residual = True # type: ignore
+
+ # Rotary embeddings.
+ if self.config.rope:
+ self.rotary_emb = RotaryEmbedding(config, self.__cache)
+
+ def reset_parameters(self):
+ if self.k_norm is not None:
+ self.k_norm.reset_parameters()
+ if self.q_norm is not None:
+ self.q_norm.reset_parameters()
+ init_weights(
+ self.config,
+ self.attn_out,
+ d=self.config.d_model,
+ layer_id=self.layer_id,
+ type_of_module=ModuleType.out_module,
+ )
+ init_weights(
+ self.config,
+ self.ff_out,
+ d=self.ff_out.in_features,
+ layer_id=self.layer_id,
+ type_of_module=ModuleType.out_module,
+ )
+
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
+ if strategy == ActivationCheckpointingStrategy.fine_grained:
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
+ else:
+ self._activation_checkpoint_fn = pass_through_fn
+
+ @classmethod
+ def _cast_attn_bias(cls, bias: torch.Tensor, input_dtype: torch.dtype) -> torch.Tensor:
+ target_dtype = input_dtype
+ # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
+ # `is_autocast_cpu_enabled()` for CPU autocast.
+ # See https://github.com/pytorch/pytorch/issues/110966.
+ if bias.device.type == "cuda" and torch.is_autocast_enabled():
+ target_dtype = torch.get_autocast_gpu_dtype()
+ elif bias.device.type == "cpu" and torch.is_autocast_cpu_enabled():
+ target_dtype = torch.get_autocast_cpu_dtype()
+ if bias.dtype != target_dtype:
+ bias = bias.to(target_dtype)
+ ensure_finite_(bias, check_neg_inf=True, check_pos_inf=False)
+ return bias
+
+ def _scaled_dot_product_attention(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ v: torch.Tensor,
+ attn_mask: Optional[torch.Tensor] = None,
+ dropout_p: float = 0.0,
+ is_causal: bool = False,
+ ) -> torch.Tensor:
+ """
+ Computes scaled dot product attention on query, key and value tensors, using an optional
+ attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.
+
+ This method is based on PyTorch's `scaled_dot_product_attention`.
+ """
+ return F.scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ attn_mask=attn_mask,
+ dropout_p=dropout_p,
+ is_causal=is_causal,
+ )
+
+ def attention(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ v: torch.Tensor,
+ attention_bias: Optional[torch.Tensor] = None,
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
+ B, T, C = q.size() # batch size, sequence length, d_model
+ dtype = k.dtype
+
+ # Optionally apply layer norm to keys and queries.
+ if self.q_norm is not None and self.k_norm is not None:
+ q = self.q_norm(q).to(dtype=dtype)
+ k = self.k_norm(k).to(dtype=dtype)
+
+ # Move head forward to be next to the batch dim.
+ # shape: (B, nh, T, hs)
+ q = q.view(B, T, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
+ if self.config.multi_query_attention:
+ # shape: (B, 1, T, hs)
+ k = k.view(B, T, 1, C // self.config.n_heads).transpose(1, 2)
+ # shape: (B, 1, T, hs)
+ v = v.view(B, T, 1, C // self.config.n_heads).transpose(1, 2)
+ else:
+ # shape: (B, nh, T, hs)
+ k = k.view(B, T, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
+ # shape: (B, nh, T, hs)
+ v = v.view(B, T, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
+
+ if layer_past is not None:
+ past_key, past_value = layer_past
+ k = torch.cat((past_key, k), dim=-2)
+ v = torch.cat((past_value, v), dim=-2)
+
+ present = (k, v) if use_cache else None
+ query_len, key_len = q.shape[-2], k.shape[-2] # could be different if layer_past not None
+
+ if self.config.rope:
+ # Apply rotary embeddings.
+ q, k = self.rotary_emb(q, k)
+
+ if attention_bias is not None:
+ # Resize and cast attention bias.
+ # The current dtype of the attention bias might not match the dtype that the SDP attn function will
+ # run in if AMP is enabled, and this can be a problem if some tokens are masked out due to padding
+ # as down-casting the attention bias to the autocast precision will result in -infs, which will
+ # cause the SDP attn function to produce NaNs.
+ attention_bias = self._cast_attn_bias(
+ attention_bias[:, :, key_len - query_len : key_len, :key_len], dtype
+ )
+
+ # Get the attention scores.
+ # shape: (B, nh, T, hs)
+ att = self._scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ attn_mask=attention_bias,
+ dropout_p=0.0 if not self.training else self.config.attention_dropout,
+ is_causal=attention_bias is None,
+ )
+
+ # Re-assemble all head outputs side-by-side.
+ att = att.transpose(1, 2).contiguous().view(B, T, C)
+
+ # Apply output projection.
+ return self.attn_out(att), present
+
+ @abstractmethod
+ def forward(
+ self,
+ x: torch.Tensor,
+ attention_bias: Optional[torch.FloatTensor] = None,
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
+ raise NotImplementedError
+
+ @classmethod
+ def build(cls, layer_id: int, config: ModelConfig, cache: BufferCache) -> OlmoBlock:
+ if config.block_type == BlockType.sequential:
+ return OlmoSequentialBlock(layer_id, config, cache)
+ elif config.block_type == BlockType.parallel:
+ return OlmoParallelBlock(layer_id, config, cache)
+ elif config.block_type == BlockType.llama:
+ return OlmoLlamaBlock(layer_id, config, cache)
+ else:
+ raise NotImplementedError(f"Unknown block type: '{config.block_type}'")
+
+
+class OlmoSequentialBlock(OlmoBlock):
+ """
+ This is a typical transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
+ (plus another skip connection).
+ """
+
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
+ super().__init__(layer_id, config, cache)
+ # Layer norms.
+ self.attn_norm = LayerNorm.build(config)
+ self.ff_norm = LayerNorm.build(config)
+ # Attention input projection. Projects x -> (q, k, v)
+ if config.multi_query_attention:
+ self.fused_dims = (config.d_model, config.d_model // config.n_heads, config.d_model // config.n_heads)
+ else:
+ self.fused_dims = (config.d_model, config.d_model, config.d_model)
+ self.att_proj = nn.Linear(
+ config.d_model, sum(self.fused_dims), bias=config.include_bias, device=config.init_device
+ )
+ # Feed-forward input projection.
+ self.ff_proj = nn.Linear(
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
+ )
+
+ def reset_parameters(self):
+ super().reset_parameters()
+ self.attn_norm.reset_parameters()
+ self.ff_norm.reset_parameters()
+ # NOTE: the standard deviation for these weights does not depend on the layer.
+ init_weights(
+ self.config, self.att_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
+ )
+ init_weights(
+ self.config, self.ff_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ attention_bias: Optional[torch.Tensor] = None,
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
+ # Get query, key, value projections.
+ # shape:
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
+ # k, v: (batch_size, seq_len, d_model // n_heads)
+ q, k, v = self.att_proj(self._activation_checkpoint_fn(self.attn_norm, x)).split(self.fused_dims, dim=-1)
+
+ # Get attention scores.
+ att, cache = self._activation_checkpoint_fn(
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
+ )
+
+ # Add attention scores.
+ # shape: (B, T, C)
+ x = x + self.dropout(att)
+
+ # Add feed-forward projection.
+ # shape: (batch_size, seq_len, d_model)
+ og_x = x
+ x = self._activation_checkpoint_fn(self.ff_norm, x)
+ x = self.ff_proj(x)
+ x = self._activation_checkpoint_fn(self.act, x)
+ x = self.ff_out(x)
+ x = self.dropout(x)
+ x = og_x + x
+
+ return x, cache
+
+
+class OlmoParallelBlock(OlmoBlock):
+ """
+ This is a transformer block where the output is computed as ``MLP(LN(x)) + Attention(LN(x))``
+ as in the PaLM architecture, as opposed to the typical ``MLP(LN(x + Attention(LN(x))))``
+ as in :class:`OlmoSequentialBlock` (ignoring some skip connections).
+
+ The decoupling of the MLP and Attention functions allow us to fuse the separate input projections
+ into a single linear layer to increase throughput. In this configuration it's also straight-forward
+ to fuse the output projections, but we found that didn't help.
+ """
+
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
+ super().__init__(layer_id, config, cache)
+ self.norm = LayerNorm.build(config)
+ # Fused attention and feed-forward projection.
+ # NOTE: we could also fuse the attention and feed-forward output projections but we
+ # found that didn't help, possibly because of the overhead of joining the `att` and
+ # `ff` activations together. See https://github.com/allenai/LLM/pull/79 for details.
+ if config.multi_query_attention:
+ self.fused_dims = (
+ config.d_model,
+ config.d_model // config.n_heads,
+ config.d_model // config.n_heads,
+ self.hidden_size,
+ )
+ else:
+ self.fused_dims = (config.d_model, config.d_model, config.d_model, self.hidden_size)
+ self.fused_attn_ff_proj = nn.Linear(
+ config.d_model, sum(self.fused_dims), bias=config.include_bias, device=config.init_device
+ )
+
+ def reset_parameters(self):
+ super().reset_parameters()
+ self.norm.reset_parameters()
+ # NOTE: the standard deviation for these weights does not depend on the layer.
+ init_weights(
+ self.config,
+ self.fused_attn_ff_proj,
+ d=self.config.d_model,
+ layer_id=None,
+ type_of_module=ModuleType.in_module,
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ attention_bias: Optional[torch.Tensor] = None,
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
+ # Get query, key, value, and feed-forward projections.
+ # shape of q, k, v:
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
+ # k, v: (batch_size, seq_len, d_model // n_heads)
+ # shape of ff: (batch_size, seq_len, hidden_size)
+ q, k, v, ff = self.fused_attn_ff_proj(self._activation_checkpoint_fn(self.norm, x)).split(
+ self.fused_dims, dim=-1
+ )
+
+ # Get attention scores.
+ # shape: (B, T, C)
+ att, cache = self._activation_checkpoint_fn(
+ self.attention, q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache
+ )
+
+ # Apply output projections (and activation function) and sum the results.
+ # We keep these projections separate because we found that we got better throughput this
+ # way compared to fusing them.
+ return (
+ x + self.dropout(self.ff_out(self._activation_checkpoint_fn(self.act, ff))) + self.dropout(att),
+ cache,
+ )
+
+
+class OlmoLlamaBlock(OlmoBlock):
+ """
+ This is a transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
+ (plus another skip connection). This block is similar to `OlmoSequentialBlock`
+ but some operations have slightly different implementations to imitate the
+ behavior of Llama.
+ """
+
+ def __init__(self, layer_id: int, config: ModelConfig, cache: BufferCache):
+ super().__init__(layer_id, config, cache)
+ # Layer norms.
+ self.attn_norm = LayerNorm.build(config)
+ self.ff_norm = LayerNorm.build(config)
+ self.__cache = cache
+
+ # Attention input projection. Projects x -> (q, k, v)
+ if config.multi_query_attention:
+ q_proj_out_dim = config.d_model
+ k_proj_out_dim = config.d_model // config.n_heads
+ v_proj_out_dim = config.d_model // config.n_heads
+ else:
+ q_proj_out_dim = config.d_model
+ k_proj_out_dim = config.d_model
+ v_proj_out_dim = config.d_model
+ self.q_proj = nn.Linear(
+ config.d_model, q_proj_out_dim, bias=config.include_bias, device=config.init_device
+ )
+ self.k_proj = nn.Linear(
+ config.d_model, k_proj_out_dim, bias=config.include_bias, device=config.init_device
+ )
+ self.v_proj = nn.Linear(
+ config.d_model, v_proj_out_dim, bias=config.include_bias, device=config.init_device
+ )
+
+ # Feed-forward input projection.
+ self.ff_proj = nn.Linear(
+ config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
+ )
+
+ def reset_parameters(self):
+ super().reset_parameters()
+ self.attn_norm.reset_parameters()
+ self.ff_norm.reset_parameters()
+ # NOTE: the standard deviation for these weights does not depend on the layer.
+ init_weights(self.config, self.q_proj, d=self.config.d_model, layer_id=None)
+ init_weights(self.config, self.k_proj, d=self.config.d_model, layer_id=None)
+ init_weights(self.config, self.v_proj, d=self.config.d_model, layer_id=None)
+ init_weights(self.config, self.ff_proj, d=self.config.d_model, layer_id=None)
+
+ def _scaled_dot_product_attention(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ v: torch.Tensor,
+ attn_mask: Optional[torch.Tensor] = None,
+ dropout_p: float = 0.0,
+ is_causal: bool = False,
+ ) -> torch.Tensor:
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(q.size(-1))
+
+ if is_causal:
+ assert attn_mask is None
+
+ query_len, key_len = q.shape[-2], k.shape[-2] # could be different if layer_past not None
+ attn_bias = get_causal_attention_bias(self.__cache, key_len, q.device)[:, :, :query_len, :key_len]
+ elif attn_mask is not None:
+ attn_bias = attn_mask.to(q.dtype)
+ else:
+ attn_bias = torch.zeros_like(attn_weights)
+
+ attn_weights += attn_bias
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1).to(q.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout_p)
+ return torch.matmul(attn_weights, v)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ attention_bias: Optional[torch.Tensor] = None,
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
+ # Get query, key, value projections.
+ # shape:
+ # - for regular attn q, k, v: (batch_size, seq_len, d_model)
+ # - for multi-query attn q: (batch_size, seq_len, d_model)
+ # k, v: (batch_size, seq_len, d_model // n_heads)
+ x_normed = self.attn_norm(x)
+ q = self.q_proj(x_normed)
+ k = self.k_proj(x_normed)
+ v = self.v_proj(x_normed)
+
+ # Get attention scores.
+ att, cache = self.attention(q, k, v, attention_bias, layer_past=layer_past, use_cache=use_cache)
+
+ # Add attention scores.
+ # shape: (B, T, C)
+ x = x + self.dropout(att)
+
+ # Add feed-forward projection.
+ # shape: (batch_size, seq_len, d_model)
+ og_x = x
+ x = self._activation_checkpoint_fn(self.ff_norm, x)
+ x = self.ff_proj(x)
+ x = self._activation_checkpoint_fn(self.act, x)
+ x = self.ff_out(x)
+ x = self.dropout(x)
+ x = og_x + x
+
+ return x, cache
+
+
+class OlmoOutput(NamedTuple):
+ logits: torch.FloatTensor
+ """
+ A tensor of shape `(batch_size, seq_len, vocab_size)` representing the log probabilities
+ for the next token *before* normalization via (log) softmax.
+ """
+
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]
+ """
+ Attention keys and values from each block.
+ """
+
+
+class OlmoGenerateOutput(NamedTuple):
+ token_ids: torch.LongTensor
+ """
+ The generated token IDs, a tensor of shape `(batch_size, beam_size, max_steps)`.
+ These do *not* include the original input IDs.
+ """
+
+ scores: torch.FloatTensor
+ """
+ The scores of the generated sequences, a tensor of shape `(batch_size, beam_size)`.
+ """
+
+
+class OlmoBlockGroup(nn.ModuleList):
+ def __init__(self, config: ModelConfig, layer_offset: int, modules: Optional[Iterable[nn.Module]] = None):
+ super().__init__(modules)
+ self.config = config
+ self.layer_offset = layer_offset
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
+ self._activation_checkpoint_fn = activation_checkpoint_function(self.config)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ attention_bias: Optional[torch.FloatTensor] = None,
+ layers_past: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
+ use_cache: bool = False,
+ ) -> Tuple[torch.Tensor, Optional[List[Tuple[torch.Tensor, torch.Tensor]]]]:
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
+ for block_idx, block in enumerate(self):
+ layer_past = None if layers_past is None else layers_past[block_idx]
+ block_idx += self.layer_offset
+ if (
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
+ and block_idx % 2 == 0
+ )
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
+ and block_idx % 3 == 0
+ )
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
+ and block_idx % 4 == 0
+ )
+ ):
+ # shape: (batch_size, seq_len, d_model)
+ x, cache = self._activation_checkpoint_fn(
+ block, x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache
+ )
+ else:
+ # shape: (batch_size, seq_len, d_model)
+ x, cache = block(x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache)
+ if attn_key_values is not None:
+ assert cache is not None
+ attn_key_values.append(cache)
+ return x, attn_key_values
+
+ def reset_parameters(self):
+ for block in self:
+ block.reset_parameters()
+
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
+ self.activation_checkpointing_strategy = strategy
+ for block in self:
+ block.set_activation_checkpointing(strategy)
+
+
+class Olmo(nn.Module):
+ def __init__(self, config: ModelConfig, init_params: bool = True):
+ super().__init__()
+ self.config = config
+ self.__cache = BufferCache()
+
+ # Validate config.
+ if self.config.alibi and self.config.flash_attention:
+ raise OlmoConfigurationError("ALiBi is currently not supported with FlashAttention")
+
+ if self.config.alibi and self.config.rope:
+ raise OlmoConfigurationError("ALiBi and RoPE are mutually exclusive")
+
+ if self.config.embedding_size is not None and self.config.embedding_size != self.config.vocab_size:
+ if self.config.embedding_size < self.config.vocab_size:
+ raise OlmoConfigurationError("embedding size should be at least as big as vocab size")
+ elif self.config.embedding_size % 128 != 0:
+ import warnings
+
+ warnings.warn(
+ "Embedding size is not a multiple of 128! This could hurt throughput performance.", UserWarning
+ )
+
+ self.activation_checkpointing_strategy: Optional[ActivationCheckpointingStrategy] = None
+ self._activation_checkpoint_fn: Callable = activation_checkpoint_function(self.config)
+
+ if not (
+ 0 < self.config.block_group_size <= self.config.n_layers
+ and self.config.n_layers % self.config.block_group_size == 0
+ ):
+ raise OlmoConfigurationError("n layers must be divisible by block group size")
+
+ torch.backends.cuda.enable_flash_sdp(self.config.flash_attention)
+ torch.backends.cuda.enable_mem_efficient_sdp(False) # this is super slow so make sure torch won't use it
+
+ self.transformer = nn.ModuleDict(
+ dict(
+ wte=nn.Embedding(
+ config.embedding_size or config.vocab_size, config.d_model, device=config.init_device
+ ),
+ emb_drop=Dropout(config.embedding_dropout),
+ ln_f=LayerNorm.build(config),
+ )
+ )
+
+ blocks = [OlmoBlock.build(i, config, self.__cache) for i in range(config.n_layers)]
+ if self.config.block_group_size > 1:
+ block_groups = [
+ OlmoBlockGroup(config, i, blocks[i : i + config.block_group_size])
+ for i in range(0, config.n_layers, config.block_group_size)
+ ]
+ self.transformer.update({"block_groups": nn.ModuleList(block_groups)})
+ else:
+ self.transformer.update({"blocks": nn.ModuleList(blocks)})
+
+ if not (self.config.alibi or self.config.rope):
+ self.transformer.update(
+ {"wpe": nn.Embedding(config.max_sequence_length, config.d_model, device=config.init_device)}
+ )
+ if not config.weight_tying:
+ self.transformer.update(
+ {
+ "ff_out": nn.Linear(
+ config.d_model,
+ config.embedding_size or config.vocab_size,
+ bias=config.include_bias,
+ device=config.init_device,
+ )
+ }
+ )
+ # When `init_device="meta"` FSDP will call `reset_parameters()` to initialize weights.
+ if init_params and self.config.init_device != "meta":
+ self.reset_parameters()
+ self.__num_fwd_flops: Optional[int] = None
+
+ # Warm up cache.
+ if self.config.alibi:
+ get_causal_attention_bias(self.__cache, config.max_sequence_length, _non_meta_init_device(config))
+ self.get_alibi_attention_bias(config.max_sequence_length, _non_meta_init_device(config))
+
+ def enable_activation_checkpointing(self, enable: bool = True):
+ self.set_activation_checkpointing(ActivationCheckpointingStrategy.whole_layer if enable else None)
+
+ def set_activation_checkpointing(self, strategy: Optional[ActivationCheckpointingStrategy]):
+ self.activation_checkpointing_strategy = strategy
+ if self.config.block_group_size != 1:
+ for block_group in self.transformer.block_groups:
+ block_group.set_activation_checkpointing(strategy)
+ else:
+ for block in self.transformer.blocks:
+ block.set_activation_checkpointing(strategy)
+
+ @property
+ def device(self) -> torch.device:
+ device: torch.device = self.transformer.wte.weight.device # type: ignore
+ if device.type == "meta":
+ return _non_meta_init_device(self.config)
+ else:
+ return device
+
+ def reset_parameters(self):
+ log.info("Initializing model parameters...")
+ # Top-level embeddings / linear layers.
+ init_weights(
+ self.config,
+ self.transformer.wte, # type: ignore
+ std_factor=(0.5 * math.sqrt(self.config.d_model)) if self.config.scale_logits else 1.0,
+ type_of_module=ModuleType.emb,
+ )
+ if hasattr(self.transformer, "wpe"):
+ init_weights(self.config, self.transformer.wpe, type_of_module=ModuleType.emb) # type: ignore
+
+ # Top-level layer norm.
+ self.transformer.ln_f.reset_parameters() # type: ignore
+
+ # Output weights.
+ if hasattr(self.transformer, "ff_out"):
+ init_weights(self.config, self.transformer.ff_out, type_of_module=ModuleType.final_out) # type: ignore
+
+ # Let the blocks handle themselves.
+ if self.config.block_group_size == 1:
+ for block in self.transformer.blocks:
+ block.reset_parameters()
+ else:
+ for block_group in self.transformer.block_groups:
+ block_group.reset_parameters()
+
+ def get_alibi_attention_bias(self, seq_len: int, device: torch.device) -> torch.Tensor:
+ if (alibi_bias := self.__cache.get("alibi_attention_bias")) is not None and alibi_bias.shape[
+ -1
+ ] >= seq_len:
+ if alibi_bias.device != device:
+ alibi_bias = alibi_bias.to(device)
+ self.__cache["alibi_attention_bias"] = alibi_bias
+ return alibi_bias
+ with torch.autocast(device.type, enabled=False):
+ alibi_bias = alibi_attention_bias(seq_len, self.config, device)
+ self.__cache["alibi_attention_bias"] = alibi_bias
+ return alibi_bias
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ attention_bias: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
+ use_cache: bool = False,
+ last_logits_only: bool = False,
+ ) -> OlmoOutput:
+ """
+ :param input_ids: A tensor of shape `(batch_size, seq_len)`.
+ :param attention_mask: A tensor of shape `(batch_size, seq_len)` that indicates
+ which input IDs are masked. A `1` value in the mask means that
+ the corresponding input ID should *not* be ignored. A `0` means
+ that the corresponding input ID is masked.
+
+ This has the same meaning as the `attention_mask` in HuggingFace's `transformers`
+ library.
+ :param attention_bias: A tensor of shape `(batch_size, 1, seq_len, seq_len)`,
+ `(1, 1, seq_len, seq_len)`, or `(seq_len, seq_len)`. This is used
+ to introduce causal or other biases.
+
+ If the tensor is a bool or byte tensor, a `True` or `1` at `attention_bias[:, :, i, j]`
+ indicates that the i-th element in the sequence is allowed to attend to the j-th
+ element in the sequence.
+
+ If the tensor is a float tensor, it will just be added to the attention
+ scores before the softmax.
+
+ The default is causal, which corresponds to a lower-diagonal byte matrix of ones.
+ :param past_key_values: Pre-computed keys and values for each attention block.
+ Can be used to speed up sequential decoding. The `input_ids` which have
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
+ :param use_cache: If `True`, return key and value tensors for each block.
+ :param last_logits_only: If `True`, only compute the logits for the last token of each sequence.
+ This can speed up decoding when you only care about the next token.
+ """
+ if past_key_values:
+ assert len(past_key_values) == self.config.n_layers
+
+ batch_size, seq_len = input_ids.size()
+ if past_key_values is None:
+ past_length = 0
+ else:
+ past_length = past_key_values[0][0].size(-2)
+
+ # Get embeddings of input.
+ # shape: (batch_size, seq_len, d_model)
+ x = self.transformer.wte(input_ids) # type: ignore
+
+ if not (self.config.alibi or self.config.rope):
+ # Get positional embeddings.
+ # shape: (1, seq_len)
+ pos = torch.arange(
+ past_length, past_length + seq_len, dtype=torch.long, device=input_ids.device
+ ).unsqueeze(0)
+ # shape: (1, seq_len, d_model)
+ pos_emb = self.transformer.wpe(pos) # type: ignore
+ x = pos_emb + x
+
+ # Add input + positional embeddings and apply dropout.
+ # shape: (batch_size, seq_len, d_model)
+ x = self.transformer.emb_drop(x) # type: ignore
+
+ # Transform the attention mask into what the blocks expect.
+ if attention_mask is not None:
+ # shape: (batch_size, 1, 1, seq_len)
+ attention_mask = attention_mask.to(dtype=torch.float).view(batch_size, -1)[:, None, None, :]
+ attention_mask = (1.0 - attention_mask) * torch.finfo(attention_mask.dtype).min
+
+ # Merge attention mask with attention bias.
+ if (
+ attention_bias is not None
+ or attention_mask is not None
+ or self.config.alibi
+ # NOTE (epwalsh): we need to initialize the attn bias in order for attn to work properly
+ # with key+value cache. Otherwise `F.scaled_dot_product_attention()` doesn't seem to compute
+ # scores correctly.
+ or past_key_values is not None
+ ):
+ if attention_bias is None and self.config.alibi:
+ attention_bias = get_causal_attention_bias(
+ self.__cache, past_length + seq_len, x.device
+ ) + self.get_alibi_attention_bias(past_length + seq_len, x.device)
+ elif attention_bias is None:
+ attention_bias = get_causal_attention_bias(self.__cache, past_length + seq_len, x.device)
+ elif attention_bias.dtype in (torch.int8, torch.bool):
+ attention_bias = attention_bias.to(dtype=torch.float)
+ attention_bias.masked_fill_(attention_bias == 0.0, torch.finfo(attention_bias.dtype).min)
+
+ # Transform to the right shape and data type.
+ mask_len = seq_len
+ if attention_mask is not None:
+ mask_len = attention_mask.shape[-1]
+ elif past_key_values is not None:
+ mask_len = past_key_values[0][0].shape[-2] + input_ids.shape[-1]
+ attention_bias = attention_bias[:, :, :mask_len, :mask_len].to(dtype=torch.float)
+
+ # Add in the masking bias.
+ if attention_mask is not None:
+ attention_bias = attention_bias + attention_mask
+ # Might get -infs after adding attention mask, since dtype.min + dtype.min = -inf.
+ # `F.scaled_dot_product_attention()` doesn't handle -inf like you'd expect, instead
+ # it can produce NaNs.
+ ensure_finite_(attention_bias, check_neg_inf=True, check_pos_inf=False)
+
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
+
+ # Apply blocks one-by-one.
+ if self.config.block_group_size == 1:
+ for block_idx, block in enumerate(self.transformer.blocks):
+ layer_past = None if past_key_values is None else past_key_values[block_idx]
+ if (
+ (self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.whole_layer)
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_two
+ and block_idx % 2 == 0
+ )
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_three
+ and block_idx % 3 == 0
+ )
+ or (
+ self.activation_checkpointing_strategy == ActivationCheckpointingStrategy.one_in_four
+ and block_idx % 4 == 0
+ )
+ ):
+ # shape: (batch_size, seq_len, d_model)
+ x, cache = self._activation_checkpoint_fn(
+ block, x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache
+ )
+ else:
+ # shape: (batch_size, seq_len, d_model)
+ x, cache = block(x, attention_bias=attention_bias, layer_past=layer_past, use_cache=use_cache)
+ if attn_key_values is not None:
+ assert cache is not None
+ attn_key_values.append(cache)
+ else:
+ for group_idx, block_group in enumerate(self.transformer.block_groups):
+ layers_past = (
+ None
+ if past_key_values is None
+ else past_key_values[
+ group_idx * self.config.block_group_size : (group_idx + 1) * self.config.block_group_size
+ ]
+ )
+ x, cache = block_group(
+ x, attention_bias=attention_bias, layers_past=layers_past, use_cache=use_cache
+ )
+ if attn_key_values is not None:
+ assert cache is not None
+ attn_key_values.extend(cache)
+
+ if last_logits_only:
+ # shape: (batch_size, 1, d_model)
+ x = x[:, -1, :].unsqueeze(1)
+
+ # Apply final layer norm.
+ # shape: (batch_size, seq_len or 1, d_model)
+ x = self.transformer.ln_f(x) # type: ignore
+
+ # Get logits.
+ # shape: (batch_size, seq_len or 1, vocab_size)
+ if self.config.weight_tying:
+ logits = F.linear(x, self.transformer.wte.weight, None) # type: ignore
+ else:
+ logits = self.transformer.ff_out(x) # type: ignore
+ if self.config.scale_logits:
+ logits.mul_(1 / math.sqrt(self.config.d_model))
+
+ return OlmoOutput(logits=logits, attn_key_values=attn_key_values) # type: ignore[arg-type]
+
+ def get_fsdp_wrap_policy(self, wrap_strategy: Optional[FSDPWrapStrategy] = None):
+ if wrap_strategy is None:
+ return None
+ if wrap_strategy == FSDPWrapStrategy.by_block:
+
+ def fsdp_wrap_fn(module, recurse: bool = True, nonwrapped_numel: int = 0):
+ del nonwrapped_numel
+ if recurse:
+ return True # always recurse for simplicity
+ return isinstance(module, OlmoBlock)
+
+ return fsdp_wrap_fn
+ elif wrap_strategy == FSDPWrapStrategy.by_block_and_size:
+
+ def fsdp_wrap_fn(module, recurse: bool = True, nonwrapped_numel: int = 0):
+ del nonwrapped_numel
+ if recurse:
+ # Determine if we should recurse.
+ return not isinstance(module, OlmoBlock)
+ else:
+ # Determine if we should wrap.
+ return isinstance(module, (OlmoBlock, nn.Linear, nn.Embedding))
+
+ return fsdp_wrap_fn
+ elif wrap_strategy == FSDPWrapStrategy.by_block_group:
+ if self.config.block_group_size <= 1:
+ raise OlmoConfigurationError(
+ "'by_block_group' FSDP wrapping strategy requires block group size greater than 1"
+ )
+
+ def fsdp_wrap_fn(module, recurse: bool = True, nonwrapped_numel: int = 0):
+ del nonwrapped_numel
+ if recurse:
+ return True # always recurse for simplicity
+ return isinstance(module, OlmoBlockGroup)
+
+ return fsdp_wrap_fn
+ elif wrap_strategy == FSDPWrapStrategy.by_block_group_and_size:
+ if self.config.block_group_size <= 1:
+ raise OlmoConfigurationError(
+ "'by_block_group_and_size' FSDP wrapping strategy requires block group size greater than 1"
+ )
+
+ def fsdp_wrap_fn(module, recurse: bool = True, nonwrapped_numel: int = 0):
+ del nonwrapped_numel
+ if recurse:
+ # Determine if we should recurse.
+ return not isinstance(module, OlmoBlockGroup)
+ else:
+ # Determine if we should wrap.
+ return isinstance(module, (OlmoBlockGroup, nn.Linear, nn.Embedding))
+
+ return fsdp_wrap_fn
+ elif wrap_strategy == FSDPWrapStrategy.size_based:
+ from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy
+
+ return size_based_auto_wrap_policy
+ elif wrap_strategy in {
+ FSDPWrapStrategy.one_in_two,
+ FSDPWrapStrategy.one_in_three,
+ FSDPWrapStrategy.one_in_four,
+ FSDPWrapStrategy.one_in_five,
+ }:
+ c = {
+ FSDPWrapStrategy.one_in_two: 2,
+ FSDPWrapStrategy.one_in_three: 3,
+ FSDPWrapStrategy.one_in_four: 4,
+ FSDPWrapStrategy.one_in_five: 5,
+ }[wrap_strategy]
+
+ def fsdp_wrap_fn(module, recurse: bool = True, nonwrapped_numel: int = 0):
+ del nonwrapped_numel
+ if recurse:
+ return True # always recurse for simplicity
+ return isinstance(module, OlmoBlock) and module.layer_id % c == 0
+
+ return fsdp_wrap_fn
+ else:
+ raise NotImplementedError(wrap_strategy)
+
+ def num_params(self, include_embedding: bool = True) -> int:
+ """
+ Get the total number of parameters.
+ """
+ params = (np for np in self.named_parameters())
+ if not include_embedding:
+ params = filter( # type: ignore
+ lambda np: ".wte." not in np[0] and ".wpe." not in np[0],
+ params,
+ )
+ return sum(p.numel() for _, p in params)
+
+ @property
+ def num_fwd_flops(self):
+ if self.__num_fwd_flops:
+ return self.__num_fwd_flops
+ n_params = self.num_params()
+ # the number of parameters is approximately the number of multiply-accumulates (MAC) in the network
+ # each MAC has 2 FLOPs - we multiply by 2 ie 2 * n_param
+ # this gets us FLOPs / token
+ params_flops_per_token = 2 * n_params
+ params_flops_per_seq = params_flops_per_token * self.config.max_sequence_length
+ # there are 2 FLOPS per mac; there is A=Q*K^T and out=A*V ops (ie mult by 2)
+ attn_flops_per_seq = (
+ self.config.n_layers * 2 * 2 * (self.config.d_model * (self.config.max_sequence_length**2))
+ )
+ self.__num_fwd_flops = params_flops_per_seq + attn_flops_per_seq
+ return self.__num_fwd_flops
+
+ def generate(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ attention_bias: Optional[torch.Tensor] = None,
+ max_steps: int = 10,
+ beam_size: int = 1,
+ per_node_beam_size: Optional[int] = None,
+ sampler: Optional[Sampler] = None,
+ min_steps: Optional[int] = None,
+ final_sequence_scorer: Optional[FinalSequenceScorer] = None,
+ constraints: Optional[List[Constraint]] = None,
+ ) -> OlmoGenerateOutput:
+ """
+ Generate token IDs using beam search.
+
+ Note that by default ``beam_size`` is set to 1, which is greedy decoding.
+
+ :param input_ids: A tensor of shape `(batch_size, seq_len)`.
+ :param attention_mask: A optional tensor of shape `(batch_size, seq_len)`, the same
+ as for the forward method.
+ :param attention_bias: A tensor of shape
+ `(batch_size, 1, seq_len + tokens_to_generate, seq_len + tokens_to_generate)`,
+ the same as for the forward method except only one shape is excepted here.
+
+ For an explanation of the other arguments, see :class:`BeamSearch`.
+ """
+ beam_search = BeamSearch(
+ self.config.eos_token_id,
+ max_steps=max_steps,
+ beam_size=beam_size,
+ per_node_beam_size=per_node_beam_size,
+ sampler=sampler,
+ min_steps=min_steps,
+ final_sequence_scorer=final_sequence_scorer,
+ constraints=constraints,
+ )
+
+ # Validate inputs.
+ batch_size, seq_len = input_ids.shape
+ if attention_mask is not None:
+ assert attention_mask.shape == (batch_size, seq_len)
+ if attention_bias is not None:
+ assert len(attention_bias.shape) == 4
+ assert attention_bias.shape[:2] == (batch_size, 1)
+ assert (
+ seq_len + beam_search.max_steps
+ <= attention_bias.shape[2]
+ == attention_bias.shape[3]
+ <= self.config.max_sequence_length
+ )
+
+ tokens_generated = 0
+
+ def flatten_past_key_values(
+ past_key_values: List[Tuple[torch.Tensor, torch.Tensor]]
+ ) -> Dict[str, torch.Tensor]:
+ out = {}
+ for i, (key, value) in enumerate(past_key_values):
+ out[f"past_key_{i}"] = key
+ out[f"past_value_{i}"] = value
+ return out
+
+ def unflatten_past_key_values(
+ past_key_values: Dict[str, torch.Tensor]
+ ) -> List[Tuple[torch.Tensor, torch.Tensor]]:
+ out = []
+ for i in range(self.config.n_layers):
+ past_key = past_key_values[f"past_key_{i}"]
+ past_value = past_key_values[f"past_value_{i}"]
+ out.append((past_key, past_value))
+ return out
+
+ def step(
+ last_predictions: torch.Tensor, state: dict[str, torch.Tensor]
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
+ nonlocal tokens_generated
+
+ attention_mask = state.get("attention_mask")
+ attention_bias = state.get("attention_bias")
+
+ if tokens_generated > 0:
+ past_key_values = unflatten_past_key_values(state)
+ input_ids = last_predictions.unsqueeze(1)
+ if attention_mask is not None:
+ group_size = input_ids.shape[0]
+ attention_mask = torch.cat((attention_mask, attention_mask.new_ones((group_size, 1))), dim=-1)
+ else:
+ past_key_values = None
+ input_ids = state["input_ids"]
+
+ tokens_generated += 1
+
+ # Run forward pass of model to get logits, then normalize to get log probs.
+ output = self(
+ input_ids,
+ attention_mask=attention_mask,
+ attention_bias=attention_bias,
+ past_key_values=past_key_values,
+ use_cache=True,
+ last_logits_only=True,
+ )
+ log_probs = F.log_softmax(output.logits[:, -1, :], dim=-1)
+
+ # Create new state.
+ state = flatten_past_key_values(output.attn_key_values)
+ if attention_mask is not None:
+ state["attention_mask"] = attention_mask
+ if attention_bias is not None:
+ state["attention_bias"] = attention_bias
+
+ return log_probs, state
+
+ initial_preds = input_ids.new_zeros((batch_size,)) # This is arbitrary, we won't use this.
+ state: dict[str, torch.Tensor] = {"input_ids": input_ids}
+ if attention_mask is not None:
+ state["attention_mask"] = attention_mask
+ if attention_bias is not None:
+ state["attention_bias"] = attention_bias
+ with torch.no_grad():
+ token_ids, scores = beam_search.search(initial_preds, state, step)
+
+ return OlmoGenerateOutput(
+ token_ids=token_ids, # type: ignore[arg-type]
+ scores=scores, # type: ignore[arg-type]
+ )
+
+ @classmethod
+ def from_checkpoint(
+ cls, checkpoint_dir: PathOrStr, device: str = "cpu", checkpoint_type: Optional[CheckpointType] = None
+ ) -> Olmo:
+ """
+ Load an OLMo model from a checkpoint.
+ """
+ from .util import resource_path
+
+ # Guess checkpoint type.
+ if checkpoint_type is None:
+ try:
+ if resource_path(checkpoint_dir, "model.pt").is_file():
+ checkpoint_type = CheckpointType.unsharded
+ else:
+ checkpoint_type = CheckpointType.sharded
+ except FileNotFoundError:
+ checkpoint_type = CheckpointType.sharded
+
+ # Load config.
+ config_path = resource_path(checkpoint_dir, "config.yaml")
+ model_config = ModelConfig.load(config_path, key="model", validate_paths=False)
+
+ if checkpoint_type == CheckpointType.unsharded:
+ # Initialize model (always on CPU to start with so we don't run out of GPU memory).
+ model_config.init_device = "cpu"
+ model = Olmo(model_config)
+
+ # Load state dict directly to target device.
+ state_dict_path = resource_path(checkpoint_dir, "model.pt")
+ state_dict = torch.load(state_dict_path, map_location="cpu")
+ model.load_state_dict(model._make_state_dict_compatible(state_dict)[0])
+ model = model.to(torch.device(device))
+ else:
+ from .checkpoint import load_model_state
+
+ # Initialize model on target device. In this case the state dict is loaded in-place
+ # so it's not necessary to start on CPU if the target device is a GPU.
+ model_config.init_device = device
+ model = Olmo(model_config)
+
+ # Load state dict in place.
+ load_model_state(checkpoint_dir, model)
+
+ return model.eval()
+
+ def _make_state_dict_compatible(
+ self, state_dict: Dict[str, torch.Tensor]
+ ) -> Tuple[Dict[str, torch.Tensor], Dict[str, Set[str]]]:
+ """
+ Handles some cases where the state dict is valid yet may need to be transformed in order to
+ be loaded.
+
+ This modifies the state dict in-place and also returns it, along with a mapping of original key
+ names to new key names in cases where the keys were simply renamed. That mapping can be used
+ to make a corresponding optimizer state dict compatible as well.
+ """
+ import re
+ from fnmatch import fnmatch
+
+ new_keys_to_og_keys: Dict[str, str] = {}
+
+ # Remove "_fsdp_wrapped_module." prefix from all keys. We don't want this prefix when the model is
+ # not wrapped in FSDP. And when the model is wrapped in FSDP, loading this state dict will still work
+ # fine without the prefixes. This also simplifies the other steps below.
+ for key in list(state_dict.keys()):
+ state_dict[(new_key := key.replace("_fsdp_wrapped_module.", ""))] = state_dict.pop(key)
+ new_keys_to_og_keys[new_key] = key
+
+ # For backwards compatibility prior to fixing https://github.com/allenai/LLM/issues/222
+ if self.config.block_type == BlockType.sequential:
+ for key in list(state_dict.keys()):
+ if fnmatch(key, "transformer.*.norm.weight"):
+ tensor = state_dict.pop(key)
+ state_dict[(new_key := key.replace("norm.weight", "attn_norm.weight"))] = tensor
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys[key]
+ state_dict[(new_key := key.replace("norm.weight", "ff_norm.weight"))] = tensor.clone()
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys[key]
+ del new_keys_to_og_keys[key]
+ elif fnmatch(key, "transformer.*.norm.bias"):
+ tensor = state_dict.pop(key)
+ state_dict[(new_key := key.replace("norm.bias", "attn_norm.bias"))] = tensor
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys[key]
+ state_dict[(new_key := key.replace("norm.bias", "ff_norm.bias"))] = tensor.clone()
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys[key]
+ del new_keys_to_og_keys[key]
+
+ # For loading a state dict that was saved with a different `block_group_size`.
+ if "transformer.block_groups.0.0.attn_out.weight" in state_dict.keys():
+ state_dict_block_group_size = len(
+ [k for k in state_dict.keys() if fnmatch(k, "transformer.block_groups.0.*.attn_out.weight")]
+ )
+ else:
+ state_dict_block_group_size = 1
+ if self.config.block_group_size != state_dict_block_group_size:
+ log.info(
+ f"Regrouping state dict blocks from group size {state_dict_block_group_size} to "
+ f"group size {self.config.block_group_size}"
+ )
+ # For simplicity we're first going to flatten out the block groups in the state dict (if necessary)
+ # and then (re-)group them into the right block sizes.
+ if state_dict_block_group_size > 1:
+ for key in list(state_dict.keys()):
+ if (m := re.match(r"transformer.block_groups\.(\d+)\.(\d+)\..*", key)) is not None:
+ group_idx, group_block_idx = int(m.group(1)), int(m.group(2))
+ block_idx = (group_idx * state_dict_block_group_size) + group_block_idx
+ state_dict[
+ (
+ new_key := key.replace(
+ f"block_groups.{group_idx}.{group_block_idx}.", f"blocks.{block_idx}."
+ )
+ )
+ ] = state_dict.pop(key)
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys.pop(key)
+
+ if self.config.block_group_size > 1:
+ # Group the state dict blocks into the right block size.
+ for key in list(state_dict.keys()):
+ if (m := re.match(r"transformer.blocks\.(\d+)\..*", key)) is not None:
+ block_idx = int(m.group(1))
+ group_idx, group_block_idx = (
+ block_idx // self.config.block_group_size,
+ block_idx % self.config.block_group_size,
+ )
+ state_dict[
+ (
+ new_key := key.replace(
+ f"blocks.{block_idx}.", f"block_groups.{group_idx}.{group_block_idx}."
+ )
+ )
+ ] = state_dict.pop(key)
+ new_keys_to_og_keys[new_key] = new_keys_to_og_keys.pop(key)
+
+ og_keys_to_new: Dict[str, Set[str]] = defaultdict(set)
+ for new_key, og_key in new_keys_to_og_keys.items():
+ og_keys_to_new[og_key].add(new_key)
+
+ return state_dict, og_keys_to_new
diff --git a/venv/lib/python3.10/site-packages/olmo/optim.py b/venv/lib/python3.10/site-packages/olmo/optim.py
new file mode 100644
index 0000000000000000000000000000000000000000..711e6d889306af5222e1ea818017500c4b63b6c8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/optim.py
@@ -0,0 +1,756 @@
+import logging
+from abc import ABCMeta, abstractmethod
+from dataclasses import dataclass, replace
+from math import cos, pi, sqrt
+from typing import Any, Dict, List, Optional, Tuple
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+from torch.distributed.fsdp import FullyShardedDataParallel
+from torch.optim.optimizer import Optimizer as OptimizerBase
+
+from . import LayerNormBase
+from .config import OptimizerType, SchedulerConfig, SchedulerType, TrainConfig
+from .torch_util import get_default_device, is_distributed
+
+__all__ = [
+ "Optimizer",
+ "LionW",
+ "AdamW",
+ "Scheduler",
+ "CosWithWarmup",
+ "LinearWithWarmup",
+ "InvSqrtWithWarmup",
+ "MaxScheduler",
+ "ConstantScheduler",
+ "BoltOnWarmupScheduler",
+ "build_optimizer",
+ "build_scheduler",
+]
+
+
+log = logging.getLogger(__name__)
+
+
+class Optimizer(OptimizerBase):
+ def _clean_param_name(self, name: str) -> str:
+ return name.replace("_fsdp_wrapped_module.", "")
+
+ @torch.no_grad()
+ def clip_grads_and_collect_metrics(
+ self, global_step: int, collect_param_metrics: bool = True
+ ) -> Dict[str, torch.Tensor]:
+ """
+ Clips gradients for every group that has the field `max_grad_norm`.
+ At the same time collect metrics for each parameter and its gradient.
+ """
+ device = get_default_device()
+
+ # NOTE (epwalsh): during distributed training we're making an assumption that the order of
+ # the param groups and the params within each group are the same across all ranks.
+ # This is justified since we initialize the parameter groups in every rank by iterating over
+ # `module.parameters()` or `module.named_modules()` / `module.named_parameters()`, each of which
+ # provides a consistent order.
+ # For each parameter (with a gradient) we'll collect:
+ # - min, max, avg, norm of the param itself
+ # - min, max, avg, norm of the param's gradient
+ # - min, max, avg, norm of any additional per-parameter optimizer state metrics returned from
+ # `self.get_state_for_param()`.
+ # Afterwards we'll reduce these all over all ranks.
+ per_param_min_metrics: List[torch.Tensor] = []
+ per_param_max_metrics: List[torch.Tensor] = []
+ per_param_sum_metrics: List[torch.Tensor] = []
+ per_param_norm_metrics: List[torch.Tensor] = []
+ per_param_numel_metrics: List[torch.Tensor] = []
+
+ per_param_min_metric_names: List[str] = []
+ per_param_max_metric_names: List[str] = []
+ per_param_avg_metric_names: List[str] = []
+ per_param_norm_metric_names: List[str] = []
+
+ # Collect metrics locally.
+ for group in self.param_groups:
+ if is_distributed():
+ # TODO (epwalsh): handle non-sharded params. We don't have any right now but we would
+ # with ReLoRa, for example.
+ assert group.get("sharded", True) is True
+
+ for name, p in zip(group["param_names"], group["params"]):
+ name = self._clean_param_name(name)
+ # Always need to collect the norm of gradients for clipping, even if we're not collecting
+ # other metrics.
+ tensors: List[Optional[torch.Tensor]] = [p.grad]
+ prefixes: List[str] = [f"grad/{name}"]
+ if collect_param_metrics:
+ state = self.get_state_for_param(p)
+ sorted_state_keys = sorted([k for k in state.keys()])
+ tensors.extend([p] + [state[key] for key in sorted_state_keys])
+ prefixes.extend([f"param/{name}"] + [f"{key}/{name}" for key in sorted_state_keys])
+ assert len(tensors) == len(prefixes)
+
+ # Get min, max, avg, and norm for all `tensors` associated with the parameter.
+ for x, prefix in zip(tensors, prefixes):
+ # grad or state tensors could be none for params that have their shards completely on
+ # other ranks.
+ if x is not None and x.numel() > 0:
+ if collect_param_metrics:
+ x_abs = x.abs()
+ per_param_min_metrics.append(x_abs.min().unsqueeze(0).to(dtype=torch.float32))
+ per_param_max_metrics.append(x_abs.max().unsqueeze(0).to(dtype=torch.float32))
+ per_param_sum_metrics.append(x.sum().unsqueeze(0).to(dtype=torch.float32))
+ per_param_numel_metrics.append(
+ torch.tensor([x.numel()], device=device, dtype=torch.float32)
+ )
+ per_param_norm_metrics.append(
+ torch.linalg.vector_norm(x, 2.0, dtype=torch.float32).unsqueeze(0)
+ )
+ else:
+ if collect_param_metrics:
+ per_param_min_metrics.append(
+ torch.tensor([float("inf")], device=device, dtype=torch.float32)
+ )
+ per_param_max_metrics.append(torch.tensor([0.0], device=device, dtype=torch.float32))
+ per_param_sum_metrics.append(torch.tensor([0.0], device=device, dtype=torch.float32))
+ per_param_numel_metrics.append(torch.tensor([0.0], device=device, dtype=torch.float32))
+ per_param_norm_metrics.append(torch.tensor([0.0], device=device, dtype=torch.float32))
+ if collect_param_metrics:
+ per_param_min_metric_names.append(f"{prefix}.min")
+ per_param_max_metric_names.append(f"{prefix}.max")
+ per_param_avg_metric_names.append(f"{prefix}.avg")
+ per_param_norm_metric_names.append(f"{prefix}.norm")
+
+ assert (
+ len(per_param_min_metrics)
+ == len(per_param_min_metric_names)
+ == len(per_param_max_metrics)
+ == len(per_param_max_metric_names)
+ == len(per_param_sum_metrics)
+ == len(per_param_numel_metrics)
+ == len(per_param_avg_metric_names)
+ )
+ assert len(per_param_norm_metrics) == len(per_param_norm_metric_names)
+
+ def is_grad_norm_metric(metric_name: str) -> bool:
+ return metric_name.startswith("grad/") and metric_name.endswith(".norm")
+
+ # Now reduce metrics over all ranks.
+ total_grad_norm: torch.Tensor
+ per_param_avg_metrics: List[torch.Tensor] = []
+ if is_distributed(): # TODO (epwalsh): skip for non-sharded params
+ # Reduce metrics across all ranks. Note that we can use a `reduce` for most cases
+ # instead of an `all_reduce`, but we need `all_reduce` for norms so that all ranks
+ # get the right value for gradient norms so they can clip correctly.
+ # Reduce mins.
+ if per_param_min_metrics:
+ all_mins = torch.cat(per_param_min_metrics).to(device)
+ dist.reduce(all_mins, 0, op=dist.ReduceOp.MIN)
+ per_param_min_metrics = all_mins.split(1)
+ # Reduce maxs.
+ if per_param_max_metrics:
+ all_maxs = torch.cat(per_param_max_metrics).to(device)
+ dist.reduce(all_maxs, 0, op=dist.ReduceOp.MAX)
+ per_param_max_metrics = all_maxs.split(1)
+ # Reduce sums or just norms.
+ all_norms = torch.cat(per_param_norm_metrics).to(device) ** 2.0
+ if per_param_sum_metrics and per_param_numel_metrics:
+ all_sums = torch.cat(per_param_sum_metrics).to(device)
+ all_numels = torch.cat(per_param_numel_metrics).to(device)
+ all_sums_norms_numels = torch.cat(
+ [all_sums.unsqueeze(0), all_norms.unsqueeze(0), all_numels.unsqueeze(0)], dim=0
+ )
+ dist.all_reduce(all_sums_norms_numels, op=dist.ReduceOp.SUM)
+ all_sums, all_norms, all_numels = all_sums_norms_numels.split(1)
+ # Get averages.
+ # NOTE: could get infs for non-rank0 processes but that's okay.
+ per_param_avg_metrics = (all_sums / all_numels).squeeze(0).split(1)
+ else:
+ dist.all_reduce(all_norms, op=dist.ReduceOp.SUM)
+ grad_norm_metric_mask = torch.tensor(
+ [float(is_grad_norm_metric(n)) for n in per_param_norm_metric_names], device=all_norms.device
+ )
+ total_grad_norm = (all_norms * grad_norm_metric_mask).sum() ** 0.5
+ per_param_norm_metrics = (all_norms ** (0.5)).squeeze(0).split(1)
+ else:
+ total_grad_norm = (
+ torch.cat(
+ [
+ m
+ for m, n in zip(per_param_norm_metrics, per_param_norm_metric_names)
+ if is_grad_norm_metric(n)
+ ]
+ )
+ ** 2.0
+ ).sum() ** 0.5
+ per_param_avg_metrics = [x / n for x, n in zip(per_param_sum_metrics, per_param_numel_metrics)]
+
+ assert len(per_param_avg_metrics) == len(per_param_avg_metric_names)
+
+ # Collect all metrics into a single dict.
+ all_metrics: Dict[str, torch.Tensor] = {}
+ for metric_name, metric in zip(per_param_min_metric_names, per_param_min_metrics):
+ all_metrics[metric_name] = metric.squeeze(0)
+ for metric_name, metric in zip(per_param_max_metric_names, per_param_max_metrics):
+ all_metrics[metric_name] = metric.squeeze(0)
+ for metric_name, metric in zip(per_param_avg_metric_names, per_param_avg_metrics):
+ all_metrics[metric_name] = metric.squeeze(0)
+ for metric_name, metric in zip(per_param_norm_metric_names, per_param_norm_metrics):
+ all_metrics[metric_name] = metric.squeeze(0)
+ all_metrics["total_grad_norm"] = total_grad_norm
+
+ # Clip gradients.
+ num_grads_clipped = 0
+ num_eligible_grads = 0
+ for group in self.param_groups:
+ if (max_norm_ratio := group.get("max_grad_norm_ratio")) is not None:
+ num_clipped = self._do_adaptive_clipping(
+ group, max_norm_ratio, global_step, all_metrics, collect_param_metrics=collect_param_metrics
+ )
+ elif (max_norm := group.get("max_grad_norm")) is not None:
+ num_clipped = self._do_global_fixed_clipping(
+ group, max_norm, all_metrics, collect_param_metrics=collect_param_metrics
+ )
+ else:
+ # No clipping needed.
+ continue
+ num_eligible_grads += len(group["params"])
+ if num_clipped is not None:
+ num_grads_clipped += num_clipped
+
+ if collect_param_metrics:
+ clipping_rate = torch.tensor(num_grads_clipped / num_eligible_grads, device="cpu")
+ all_metrics["clipping_rate"] = clipping_rate
+ return all_metrics
+ else:
+ return {}
+
+ @torch.no_grad()
+ def _do_adaptive_clipping(
+ self,
+ group: Dict[str, Any],
+ max_norm_ratio: float,
+ global_step: int,
+ all_metrics: Dict[str, torch.Tensor],
+ collect_param_metrics: bool = True,
+ ) -> Optional[int]:
+ """
+ Do adaptive gradient clipping on a param group.
+
+ If ``collect_param_metrics`` is ``True`` this will return the total number of gradients clipped.
+ """
+ device = get_default_device()
+ num_grads_clipped = 0
+ # We'll use the bigger of beta1 and beta2 to update the exponential average of the norm of
+ # the gradient (a scalar), not to be confused with the exponential average of the gradient.
+ # TODO (epwalsh): handle optimizers that don't have betas.
+ beta1, beta2 = group["betas"]
+ beta = max(beta1, beta2)
+ for name, p in zip(group["param_names"], group["params"]):
+ name = self._clean_param_name(name)
+ grad_norm = all_metrics.get(f"grad/{name}.norm")
+ if grad_norm is None:
+ continue
+
+ # Get or initialize the exponential average of grad norm.
+ # TODO: The way we have it right now, every rank tracks the `grad_norm_exp_avg` of every parameter,
+ # even parameters for which the corresponding local shard is empty. This has the potential to
+ # cause some issues with the optimizer, as we ran into with https://github.com/allenai/LLM/pull/372.
+ # So we should consider changing how we do this at some point so that we don't add any state
+ # to parameters for which the local shard is empty. That would probably add extra distributed
+ # communication, at least on steps where we have to log (i.e. when `collect_param_metrics=True`).
+ state = self.state[p]
+ grad_norm_exp_avg = state.get("grad_norm_exp_avg")
+ if grad_norm_exp_avg is None:
+ grad_norm_exp_avg = grad_norm.clone().to(device)
+ # We don't want to add anything to `state` until `state` has been initialized, otherwise
+ # this will crash some optimizers which rely on checking `len(state)`. The downside here
+ # is that we won't start tracking `grad_norm_exp_avg` until the 2nd training step.
+ if global_step > 1:
+ state["grad_norm_exp_avg"] = grad_norm_exp_avg
+
+ max_allowed_norm = max_norm_ratio * grad_norm_exp_avg
+ clip_coef = max_allowed_norm / (grad_norm + 1e-6)
+
+ # Clip the gradients and update the exponential average.
+ # Note that multiplying by the clamped coefficient is meaningless when it is
+ # equal to 1, but it avoids the host-device sync that would result from `if clip_coef_clamped < 1`.
+ clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
+ if p.grad is not None:
+ # p.grad could be none for some ranks when using FSDP.
+ p.grad.detach().mul_(clip_coef_clamped.to(p.grad.device, p.grad.dtype))
+
+ # Update the exponential average of the norm of the gradient with the clipped norm of the gradient.
+ grad_norm_exp_avg.lerp_((grad_norm * clip_coef_clamped).to(grad_norm_exp_avg.device), 1 - beta)
+ # Alternative: update with the *unclipped* norm of the gradient.
+ # grad_norm_exp_avg.lerp_(grad_norm.to(grad_norm_exp_avg.device), 1 - beta)
+
+ if collect_param_metrics:
+ # Can't avoid host-device sync here.
+ if clip_coef_clamped < 1.0:
+ num_grads_clipped += 1
+ all_metrics[f"grad_norm_exp_avg/{name}"] = grad_norm_exp_avg
+ return num_grads_clipped if collect_param_metrics else None
+
+ @torch.no_grad()
+ def _do_global_fixed_clipping(
+ self,
+ group: Dict[str, Any],
+ max_norm: float,
+ all_metrics: Dict[str, torch.Tensor],
+ collect_param_metrics: bool = True,
+ ) -> Optional[int]:
+ """
+ Do global fixed gradient clipping on a param group.
+
+ If ``collect_param_metrics`` is ``True`` this will return the total number of gradients clipped.
+ """
+ device = get_default_device()
+ total_grad_norm = all_metrics["total_grad_norm"]
+ clip_coef = max_norm / (total_grad_norm.to(device) + 1e-6)
+ clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
+ num_grads_clipped: Optional[int] = None
+ if collect_param_metrics:
+ # Can't avoid host-device sync here.
+ if clip_coef_clamped < 1.0:
+ num_grads_clipped = len(group["params"])
+ for p in group["params"]:
+ # Clip the gradients.
+ # Note that multiplying by the clamped coefficient is meaningless when it is
+ # equal to 1, but it avoids the host-device sync that would result from `if clip_coef_clamped < 1`.
+ if p.grad is not None:
+ # p.grad could be none for some ranks when using FSDP.
+ p.grad.detach().mul_(clip_coef_clamped.to(p.grad.device, p.grad.dtype))
+ return num_grads_clipped
+
+ def get_post_step_metrics(self, module: nn.Module) -> Dict[str, torch.Tensor]:
+ del module
+ return {}
+
+ def get_state_for_param(self, param: nn.Parameter) -> Dict[str, Optional[torch.Tensor]]:
+ del param
+ return {}
+
+
+class LionW(Optimizer):
+ """
+ Adapted from https://github.com/google/automl/blob/master/lion/lion_pytorch.py
+ """
+
+ def __init__(
+ self,
+ params,
+ lr: float = 1e-4,
+ betas: Tuple[float, float] = (0.9, 0.99),
+ weight_decay: float = 0.0,
+ ):
+ assert lr > 0.0
+ assert all([0.0 <= beta <= 1.0 for beta in betas])
+ defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)
+ super().__init__(params, defaults)
+ for group in self.param_groups:
+ group["initial_lr"] = group["lr"]
+ self._update_total_dot_prod: Optional[torch.Tensor] = None
+ self._update_total_norm: Optional[torch.Tensor] = None
+ self._signed_update_total_norm: Optional[torch.Tensor] = None
+
+ def get_post_step_metrics(self, module: nn.Module) -> Dict[str, torch.Tensor]:
+ update_total_dot_prod = self._update_total_dot_prod
+ update_total_norm = self._update_total_norm
+ signed_update_total_norm = self._signed_update_total_norm
+ if update_total_dot_prod is None or update_total_norm is None or signed_update_total_norm is None:
+ return {}
+
+ if is_distributed() and isinstance(module, FullyShardedDataParallel):
+ # Reduce total dot prod and norms across all ranks.
+ update_total_norm = update_total_norm**2.0
+ signed_update_total_norm = signed_update_total_norm**2.0
+ # Reduce all together to avoid multiple communication calls.
+ all_together = torch.stack([update_total_dot_prod, update_total_norm, signed_update_total_norm])
+ # Only need the final result on rank0, since that's where we log from.
+ dist.reduce(all_together, 0)
+ update_total_dot_prod, update_total_norm, signed_update_total_norm = all_together
+ update_total_norm = update_total_norm**0.5
+ signed_update_total_norm = signed_update_total_norm**0.5
+
+ update_cos_sim = update_total_dot_prod / torch.max(
+ update_total_norm * signed_update_total_norm, torch.tensor(1e-8, device=get_default_device())
+ )
+ return {"update_cos_sim": update_cos_sim}
+
+ @torch.no_grad()
+ def step(self, closure=None) -> None:
+ if closure is not None:
+ with torch.enable_grad():
+ closure()
+
+ update_total_dot_prod = torch.tensor(0.0, dtype=torch.float32)
+ update_norms = []
+ signed_update_norms = []
+
+ for group in self.param_groups:
+ for p in group["params"]:
+ if p.grad is None:
+ continue
+
+ # Perform step weight decay
+ p.data.mul_(1 - group["lr"] * group["weight_decay"])
+
+ grad = p.grad
+ state = self.state[p]
+
+ # State initialization
+ if len(state) == 0:
+ # Exponential moving average of gradient values
+ state["exp_avg"] = torch.zeros_like(p)
+
+ exp_avg = state["exp_avg"]
+ beta1, beta2 = group["betas"]
+
+ # Weight update
+ update = exp_avg * beta1 + grad * (1 - beta1)
+ signed_update = torch.sign(update)
+ p.add_(signed_update, alpha=-group["lr"])
+
+ # Decay the momentum running average coefficient
+ exp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)
+
+ # Track dot product and norms of update vs signed update in order to calculate
+ # their cosine similarity.
+ update_total_dot_prod = update_total_dot_prod.to(update.device)
+ update_total_dot_prod += torch.tensordot(update, signed_update, dims=len(update.shape))
+ update_norms.append(torch.linalg.vector_norm(update, 2.0, dtype=torch.float32))
+ signed_update_norms.append(torch.linalg.vector_norm(signed_update, 2.0, dtype=torch.float32))
+
+ # Compute cosine similarity between update and signed update.
+ self._update_total_dot_prod = update_total_dot_prod.to(get_default_device())
+ self._update_total_norm = torch.linalg.vector_norm(
+ torch.stack(update_norms),
+ 2.0,
+ dtype=torch.float32,
+ ).to(get_default_device())
+ self._signed_update_total_norm = torch.linalg.vector_norm(
+ torch.stack(signed_update_norms),
+ 2.0,
+ dtype=torch.float32,
+ ).to(get_default_device())
+
+
+class AdamW(torch.optim.AdamW, Optimizer):
+ def get_state_for_param(self, param: nn.Parameter) -> Dict[str, Optional[torch.Tensor]]:
+ return {key: self.state[param].get(key) for key in ("exp_avg", "exp_avg_sq")} # type: ignore
+
+
+@dataclass
+class Scheduler(metaclass=ABCMeta):
+ # NOTE: these fields are not given default values because otherwise dataclasses complains
+ # about how the scheduler subclasses are defined.
+ grad_clip_warmup_steps: Optional[int]
+ grad_clip_warmup_factor: Optional[float]
+
+ @abstractmethod
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ raise NotImplementedError
+
+ def _get_max_grad_norm_coeff(
+ self, initial_value: Optional[float], step: int, max_steps: int
+ ) -> Optional[float]:
+ del max_steps # might need this in the future, but for now I just wanted to match the API of `get_lr()`.
+ if initial_value is None:
+ return None
+ elif (
+ self.grad_clip_warmup_steps is None
+ or self.grad_clip_warmup_factor is None
+ or step > self.grad_clip_warmup_steps
+ ):
+ return initial_value
+ else:
+ return self.grad_clip_warmup_factor * initial_value
+
+ def get_max_grad_norm(
+ self, initial_max_grad_norm: Optional[float], step: int, max_steps: int
+ ) -> Optional[float]:
+ return self._get_max_grad_norm_coeff(initial_max_grad_norm, step, max_steps)
+
+ def get_max_grad_norm_ratio(
+ self, initial_max_grad_norm_ratio: Optional[float], step: int, max_steps: int
+ ) -> Optional[float]:
+ return self._get_max_grad_norm_coeff(initial_max_grad_norm_ratio, step, max_steps)
+
+ def _linear_warmup(self, initial_lr: float, step: int, warmup_steps: int = 2000) -> float:
+ return initial_lr * (0.1 + 0.9 * min(step, warmup_steps) / warmup_steps)
+
+
+@dataclass
+class CosWithWarmup(Scheduler):
+ warmup_steps: int
+ alpha_f: float = 0.1
+ t_max: Optional[int] = None
+
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ max_steps = max_steps if self.t_max is None else self.t_max
+ eta_min = initial_lr * self.alpha_f
+ if step < self.warmup_steps:
+ return self._linear_warmup(initial_lr, step, self.warmup_steps)
+ elif step >= max_steps:
+ return eta_min
+ else:
+ step = step - self.warmup_steps
+ max_steps = max_steps - self.warmup_steps
+ return eta_min + (initial_lr - eta_min) * (1 + cos(pi * step / max_steps)) / 2
+
+
+@dataclass
+class LinearWithWarmup(Scheduler):
+ warmup_steps: int
+ alpha_f: float = 0.1
+ t_max: Optional[int] = None
+
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ max_steps = max_steps if self.t_max is None else self.t_max
+ eta_min = initial_lr * self.alpha_f
+ if step < self.warmup_steps:
+ return self._linear_warmup(initial_lr, step, self.warmup_steps)
+ elif step >= max_steps:
+ return eta_min
+ else:
+ step = step - self.warmup_steps
+ max_steps = max_steps - self.warmup_steps
+ return initial_lr - (initial_lr - eta_min) * (step / max_steps)
+
+
+@dataclass
+class InvSqrtWithWarmup(Scheduler):
+ warmup_steps: int
+
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ if step < self.warmup_steps:
+ return self._linear_warmup(initial_lr, step, self.warmup_steps)
+ del max_steps
+ return initial_lr * sqrt(self.warmup_steps / max(self.warmup_steps, step))
+
+
+@dataclass
+class MaxScheduler(Scheduler):
+ sched1: Scheduler
+ sched2: Scheduler
+
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ return max(
+ self.sched1.get_lr(initial_lr, step, max_steps), self.sched2.get_lr(initial_lr, step, max_steps)
+ )
+
+
+@dataclass
+class BoltOnWarmupScheduler(Scheduler):
+ inner: Scheduler
+ warmup_start: int
+ warmup_end: int
+
+ @classmethod
+ def wrap(cls, scheduler: Scheduler, warmup_start: int, warmup_end: int) -> "BoltOnWarmupScheduler":
+ return cls(
+ grad_clip_warmup_steps=None,
+ grad_clip_warmup_factor=None,
+ inner=scheduler,
+ warmup_start=warmup_start,
+ warmup_end=warmup_end,
+ )
+
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ if step < self.warmup_start:
+ return 0.0
+ if step < self.warmup_end:
+ lr_at_intercept = self.inner.get_lr(initial_lr, self.warmup_end, max_steps)
+ return lr_at_intercept * (step - self.warmup_start) / (self.warmup_end - self.warmup_start)
+ else:
+ return self.inner.get_lr(initial_lr, step, max_steps)
+
+ def _get_max_grad_norm_coeff(
+ self, initial_value: Optional[float], step: int, max_steps: int
+ ) -> Optional[float]:
+ return self.inner._get_max_grad_norm_coeff(initial_value, step, max_steps)
+
+
+@dataclass
+class ConstantScheduler(Scheduler):
+ def get_lr(self, initial_lr: float, step: int, max_steps: int) -> float:
+ del step, max_steps
+ return initial_lr
+
+
+PARAM_GROUP_FIELDS = ("sharded", "max_grad_norm", "max_grad_norm_ratio", "param_names")
+
+
+def get_param_groups(cfg: TrainConfig, model: nn.Module) -> List[Dict[str, Any]]:
+ """
+ Separate parameters into weight decay and non weight decay groups.
+ """
+ param_groups: List[Dict[str, Any]]
+ param_group_defaults = {
+ "sharded": isinstance(model, FullyShardedDataParallel),
+ "max_grad_norm": cfg.max_grad_norm,
+ "max_grad_norm_ratio": cfg.max_grad_norm_ratio,
+ }
+
+ # Separate out parameters that we don't want to apply weight decay to, like norms and biases.
+ decay = set()
+ no_decay = set()
+ all_params = {}
+ for mn, m in model.named_modules():
+ for pn, p in m.named_parameters():
+ # NOTE: because named_modules and named_parameters are recursive
+ # we will see the same tensors p many many times, but doing it this way
+ # allows us to know which parent module any tensor p belongs to...
+ if not p.requires_grad:
+ continue
+
+ fpn = f"{mn}.{pn}" if mn else pn
+ all_params[fpn] = p
+
+ if pn.endswith("bias"):
+ if cfg.optimizer.decay_norm_and_bias:
+ decay.add(fpn)
+ else:
+ no_decay.add(fpn)
+ elif pn.endswith("weight") and isinstance(m, nn.Linear):
+ decay.add(fpn)
+ elif pn.endswith("weight") and isinstance(m, (LayerNormBase, nn.LayerNorm)):
+ if cfg.optimizer.decay_norm_and_bias:
+ decay.add(fpn)
+ else:
+ no_decay.add(fpn)
+ elif pn.endswith("weight") and isinstance(m, nn.Embedding):
+ if cfg.optimizer.decay_embeddings:
+ decay.add(fpn)
+ else:
+ no_decay.add(fpn)
+
+ # Validate that we've considered every parameter
+ inter_params = decay & no_decay
+ union_params = decay | no_decay
+ assert len(inter_params) == 0, f"parameters {inter_params} made it into both decay/no_decay sets!"
+ assert (
+ len(all_params.keys() - union_params) == 0
+ ), f"parameters {all_params.keys() - union_params} were not separated into either decay/no_decay set!"
+
+ # Create the pytorch optimizer groups.
+ decay_sorted = sorted(list(decay))
+ no_decay_sorted = sorted(list(no_decay))
+ param_groups = []
+ if len(decay_sorted) > 0:
+ param_groups.append(
+ {
+ "params": [all_params[pn] for pn in decay_sorted],
+ "param_names": decay_sorted,
+ **param_group_defaults,
+ }
+ )
+ if len(no_decay_sorted) > 0:
+ param_groups.append(
+ {
+ "params": [all_params[pn] for pn in no_decay_sorted],
+ "param_names": no_decay_sorted,
+ "weight_decay": 0.0,
+ **param_group_defaults,
+ }
+ )
+
+ # Validate fields.
+ for group in param_groups:
+ for key in PARAM_GROUP_FIELDS:
+ assert key in group
+
+ return param_groups
+
+
+def fix_optim_state_dict(optimizer: Optimizer, state_dict: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Make sure old optim state dicts are compatible with new versions.
+ """
+ if len(state_dict["param_groups"]) == 1 and len(optimizer.param_groups) == 2:
+ assert optimizer.param_groups[1]["weight_decay"] == 0.0
+
+ # Decay
+ decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"}
+ decay_param_group["params"] = optimizer.state_dict()["param_groups"][0]["params"]
+
+ # No decay.
+ no_decay_param_group = {k: v for k, v in state_dict["param_groups"][0].items() if k != "params"}
+ no_decay_param_group["weight_decay"] = 0.0
+ no_decay_param_group["params"] = optimizer.state_dict()["param_groups"][1]["params"]
+
+ state_dict["param_groups"] = [decay_param_group, no_decay_param_group]
+
+ assert len(optimizer.param_groups) == len(state_dict["param_groups"])
+
+ # Make sure:
+ # - All required fields are included in the state dict,
+ # - And that the values of those fields doesn't change from what's currently set in the optimizer,
+ # since we might have changed those fields on purpose after a restart.
+ for group, sd_group in zip(optimizer.param_groups, state_dict["param_groups"]):
+ for key in PARAM_GROUP_FIELDS:
+ sd_group[key] = group[key]
+
+ return state_dict
+
+
+def build_optimizer(cfg: TrainConfig, model: nn.Module) -> Optimizer:
+ param_groups = get_param_groups(cfg, model)
+ log.info(f"Constructing optimizer with {len(param_groups)} param groups")
+ if cfg.optimizer.name == OptimizerType.lionw:
+ return LionW(
+ param_groups,
+ lr=cfg.optimizer.learning_rate,
+ betas=cfg.optimizer.betas,
+ weight_decay=cfg.optimizer.weight_decay,
+ )
+ elif cfg.optimizer.name == OptimizerType.adamw:
+ return AdamW(
+ param_groups,
+ lr=cfg.optimizer.learning_rate,
+ betas=cfg.optimizer.betas,
+ weight_decay=cfg.optimizer.weight_decay,
+ eps=1e-5,
+ )
+ else:
+ raise NotImplementedError
+
+
+def build_scheduler(cfg: TrainConfig, sched_cfg: Optional[SchedulerConfig] = None) -> Scheduler:
+ sched_cfg = sched_cfg if sched_cfg is not None else cfg.scheduler
+ if sched_cfg.name == SchedulerType.cosine_with_warmup:
+ return CosWithWarmup(
+ grad_clip_warmup_steps=sched_cfg.grad_clip_warmup_steps,
+ grad_clip_warmup_factor=sched_cfg.grad_clip_warmup_factor,
+ warmup_steps=sched_cfg.t_warmup,
+ alpha_f=sched_cfg.alpha_f,
+ t_max=sched_cfg.t_max,
+ )
+ elif sched_cfg.name == SchedulerType.linear_with_warmup:
+ return LinearWithWarmup(
+ grad_clip_warmup_steps=sched_cfg.grad_clip_warmup_steps,
+ grad_clip_warmup_factor=sched_cfg.grad_clip_warmup_factor,
+ warmup_steps=sched_cfg.t_warmup,
+ alpha_f=sched_cfg.alpha_f,
+ t_max=sched_cfg.t_max,
+ )
+ elif sched_cfg.name == SchedulerType.inverse_sqrt_with_warmup:
+ return InvSqrtWithWarmup(
+ grad_clip_warmup_steps=sched_cfg.grad_clip_warmup_steps,
+ grad_clip_warmup_factor=sched_cfg.grad_clip_warmup_factor,
+ warmup_steps=sched_cfg.t_warmup,
+ )
+ elif sched_cfg.name == SchedulerType.max_scheduler:
+ return MaxScheduler(
+ grad_clip_warmup_steps=sched_cfg.grad_clip_warmup_steps,
+ grad_clip_warmup_factor=sched_cfg.grad_clip_warmup_factor,
+ sched1=build_scheduler(cfg, replace(sched_cfg, name=SchedulerType.cosine_with_warmup)),
+ sched2=build_scheduler(cfg, replace(sched_cfg, name=SchedulerType.inverse_sqrt_with_warmup)),
+ )
+ elif sched_cfg.name == SchedulerType.constant:
+ return ConstantScheduler(
+ grad_clip_warmup_steps=sched_cfg.grad_clip_warmup_steps,
+ grad_clip_warmup_factor=sched_cfg.grad_clip_warmup_factor,
+ )
+ else:
+ raise NotImplementedError
diff --git a/venv/lib/python3.10/site-packages/olmo/py.typed b/venv/lib/python3.10/site-packages/olmo/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/olmo/tokenizer.py b/venv/lib/python3.10/site-packages/olmo/tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6b934839537b0e2fa07a4bcdb036a4b0bc88b12
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/tokenizer.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import List, Optional, Union
+
+from tokenizers import Tokenizer as BaseTokenizer
+
+from .aliases import PathOrStr
+from .config import ModelConfig, TokenizerConfig, TrainConfig, TruncationDirection
+from .exceptions import OlmoConfigurationError
+
+__all__ = ["Tokenizer"]
+
+
+class Tokenizer:
+ """
+ A :class:`Tokenizer` is a light-weight wrapper around a HuggingFace :class:`tokenizers.Tokenizer`.
+
+ :param base_tokenizer: The :class:`tokenizers.Tokenizer` to use.
+ :param eos_token_id: The token ID corresponding to the "end-of-sentence" token.
+ :param truncate_to: Truncate when tokenizing to this number of token IDs.
+ :param truncate_direction: The direction to truncate in. "right" means truncate the tokens
+ on the right. "left" means truncate the tokens on the left. If ``truncate_to`` is null,
+ this setting has no effect.
+ """
+
+ def __init__(
+ self,
+ base_tokenizer: BaseTokenizer,
+ eos_token_id: int,
+ pad_token_id: Optional[int] = None,
+ truncate_to: Optional[int] = None,
+ truncate_direction: Union[str, TruncationDirection] = TruncationDirection.right,
+ ):
+ self.base_tokenizer = base_tokenizer
+ self.base_tokenizer.no_truncation()
+ self.eos_token_id = eos_token_id
+ self.pad_token_id = pad_token_id if pad_token_id is not None else eos_token_id
+ self.truncate_to = truncate_to
+ self.truncate_direction = TruncationDirection(truncate_direction)
+
+ @property
+ def vocab_size(self) -> int:
+ return self.base_tokenizer.get_vocab_size()
+
+ @classmethod
+ def from_train_config(cls, config: TrainConfig) -> Tokenizer:
+ tokenizer_identifier = config.tokenizer.identifier
+ if Path(tokenizer_identifier).is_file():
+ tokenizer = cls.from_file(
+ tokenizer_identifier,
+ eos_token_id=config.model.eos_token_id,
+ pad_token_id=config.model.pad_token_id,
+ )
+ else:
+ tokenizer = cls.from_pretrained(
+ tokenizer_identifier,
+ eos_token_id=config.model.eos_token_id,
+ pad_token_id=config.model.pad_token_id,
+ )
+ if config.model.vocab_size != tokenizer.vocab_size:
+ raise OlmoConfigurationError("vocab size mismatch between config and tokenizer")
+ return tokenizer
+
+ @classmethod
+ def from_pretrained(cls, identifier: str, **kwargs) -> Tokenizer:
+ """
+ Initialize a tokenizer from a pretrained tokenizer on the HuggingFace Hub.
+
+ :param identifier: The identifier of a model on the Hub that contains a
+ ``tokenizer.json`` file.
+ :param kwargs: Other key word arguments passed to :class:`Tokenizer`.
+ """
+ base_tokenizer = BaseTokenizer.from_pretrained(identifier)
+ eos_token_id = kwargs.pop("eos_token_id", base_tokenizer.get_vocab_size() - 1)
+ return cls(base_tokenizer, eos_token_id, **kwargs)
+
+ @classmethod
+ def from_file(cls, filename: PathOrStr, **kwargs) -> Tokenizer:
+ """
+ Initialize a tokenizer from a file.
+
+ You can create those files with ``BaseTokenizer.save()``.
+
+ :param filename: The name of a file containing a tokenizer specification.
+ :param kwargs: Other key word arguments passed to :class:`Tokenizer`.
+ """
+ base_tokenizer = BaseTokenizer.from_file(filename)
+ eos_token_id = kwargs.pop("eos_token_id", base_tokenizer.get_vocab_size() - 1)
+ return cls(base_tokenizer, eos_token_id, **kwargs)
+
+ @classmethod
+ def from_checkpoint(cls, checkpoint_dir: PathOrStr) -> Tokenizer:
+ """
+ Load a tokenizer from a checkpoint.
+ """
+ from cached_path import cached_path
+
+ # Load configs.
+ config_path = cached_path(os.path.join(checkpoint_dir, "config.yaml"))
+ tokenizer_config = TokenizerConfig.load(config_path, key="tokenizer")
+ model_config = ModelConfig.load(config_path, key="model")
+
+ # Initialize tokenizer and validate vocab size.
+ tokenizer = cls.from_pretrained(
+ tokenizer_config.identifier,
+ eos_token_id=model_config.eos_token_id,
+ pad_token_id=model_config.pad_token_id,
+ )
+ if model_config.vocab_size != tokenizer.vocab_size:
+ raise OlmoConfigurationError("vocab size mismatch between config and tokenizer")
+ return tokenizer
+
+ def add_special_tokens(self, input_ids: List[int]) -> List[int]:
+ """
+ Add special tokens in-place (if not already present) to the given token IDs.
+ """
+ if not input_ids or input_ids[-1] != self.eos_token_id:
+ input_ids.append(self.eos_token_id)
+ return input_ids
+
+ def num_special_tokens_to_add(self, is_pair: bool = False) -> int:
+ return 2 if is_pair else 1
+
+ def _truncate(
+ self, input_ids: List[int], truncate_to: Optional[int], direction: TruncationDirection
+ ) -> list[int]:
+ if truncate_to is None or len(input_ids) <= truncate_to:
+ return input_ids
+ elif direction == TruncationDirection.left:
+ return input_ids[len(input_ids) - truncate_to :]
+ else:
+ return input_ids[: -(len(input_ids) - truncate_to)]
+
+ def encode(self, input: str, add_special_tokens: bool = True) -> List[int]:
+ """
+ Encode a string into token IDs.
+ """
+ return self.encode_batch([input], add_special_tokens=add_special_tokens)[0]
+
+ def encode_batch(self, inputs: List[str], add_special_tokens: bool = True) -> List[List[int]]:
+ """
+ Encode a batch of strings into token IDs.
+ """
+ truncate_to = self.truncate_to
+ if truncate_to is not None and add_special_tokens:
+ truncate_to -= self.num_special_tokens_to_add(False)
+
+ batch_encoding = self.base_tokenizer.encode_batch(inputs)
+
+ all_input_ids = []
+ for encoding in batch_encoding:
+ input_ids = self._truncate(encoding.ids, truncate_to, self.truncate_direction)
+ if add_special_tokens:
+ input_ids = self.add_special_tokens(input_ids)
+ all_input_ids.append(input_ids)
+
+ return all_input_ids
+
+ def decode(self, token_ids: List[int], skip_special_tokens: bool = True) -> str:
+ """
+ Decode a list of token IDs to a string.
+ """
+ return self.base_tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
diff --git a/venv/lib/python3.10/site-packages/olmo/torch_util.py b/venv/lib/python3.10/site-packages/olmo/torch_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..86749f91517f3696c238bc2e3c4573eb3a413df8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/torch_util.py
@@ -0,0 +1,125 @@
+import os
+from typing import Optional, TypeVar
+
+import torch
+import torch.distributed as dist
+
+T = TypeVar("T")
+
+
+def seed_all(seed: int):
+ """Seed all rng objects."""
+ import random
+
+ import numpy as np
+
+ if seed < 0 or seed > 2**32 - 1:
+ raise ValueError(f"Seed {seed} is invalid. It must be on [0; 2^32 - 1]")
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ # torch.manual_seed may call manual_seed_all but calling it again here
+ # to make sure it gets called at least once
+ torch.cuda.manual_seed_all(seed)
+
+
+def is_distributed() -> bool:
+ return dist.is_available() and dist.is_initialized()
+
+
+def get_node_rank() -> int:
+ return int(os.environ.get("NODE_RANK") or (get_global_rank() - get_local_rank()) // get_local_world_size())
+
+
+def get_world_size() -> int:
+ if is_distributed():
+ return dist.get_world_size()
+ else:
+ return 1
+
+
+def get_local_world_size() -> int:
+ return int(os.environ.get("LOCAL_WORLD_SIZE") or 1)
+
+
+def get_global_rank() -> int:
+ return int(os.environ.get("RANK") or dist.get_rank())
+
+
+def get_local_rank() -> int:
+ return int(os.environ.get("LOCAL_RANK") or 0)
+
+
+def get_fs_local_rank() -> int:
+ """Get the local rank per filesystem, meaning that, regardless of the number of nodes,
+ if all ranks share the same filesystem then `get_fs_local_rank()` will be equivalent to `get_global_rank()`,
+ but if nodes do not share the same filesystem then `get_fs_local_rank()` will be equivalent to `get_local_rank()`.
+ """
+ return int(os.environ.get("FS_LOCAL_RANK") or get_local_rank())
+
+
+def move_to_device(o: T, device: torch.device) -> T:
+ if isinstance(o, torch.Tensor):
+ return o.to(device) # type: ignore[return-value]
+ elif isinstance(o, dict):
+ return {k: move_to_device(v, device) for k, v in o.items()} # type: ignore[return-value]
+ elif isinstance(o, list):
+ return [move_to_device(x, device) for x in o] # type: ignore[return-value]
+ elif isinstance(o, tuple):
+ return tuple((move_to_device(x, device) for x in o)) # type: ignore[return-value]
+ else:
+ return o
+
+
+def ensure_finite_(x: torch.Tensor, check_neg_inf: bool = True, check_pos_inf: bool = False):
+ """
+ Modify ``x`` in place to replace ``float("-inf")`` with the minimum value of the dtype when ``check_neg_inf``
+ is ``True`` and to replace ``float("inf")`` with the maximum value of the dtype when ``check_pos_inf`` is ``True``.
+ """
+ if check_neg_inf:
+ x.masked_fill_(x == float("-inf"), torch.finfo(x.dtype).min)
+ if check_pos_inf:
+ x.masked_fill_(x == float("inf"), torch.finfo(x.dtype).max)
+
+
+def get_default_device() -> torch.device:
+ if torch.cuda.is_available() and torch.cuda.is_initialized():
+ return torch.device("cuda")
+ else:
+ return torch.device("cpu")
+
+
+def barrier() -> None:
+ if is_distributed():
+ dist.barrier()
+
+
+def peak_gpu_memory(reset: bool = False) -> Optional[float]:
+ """
+ Get the peak GPU memory usage in MB across all ranks.
+ Only rank 0 will get the final result.
+ """
+ if not torch.cuda.is_available():
+ return None
+
+ device = torch.device("cuda")
+ peak_mb = torch.cuda.max_memory_allocated(device) / 1000000
+ if is_distributed():
+ peak_mb_tensor = torch.tensor(peak_mb, device=device)
+ dist.reduce(peak_mb_tensor, 0, dist.ReduceOp.MAX)
+ peak_mb = peak_mb_tensor.item()
+
+ if reset:
+ # Reset peak stats.
+ torch.cuda.reset_max_memory_allocated(device)
+
+ return peak_mb
+
+
+def synchronize_flag(flag: bool, device: torch.device) -> bool:
+ if is_distributed():
+ flag_tensor = torch.tensor(flag, device=device)
+ dist.broadcast(flag_tensor, 0)
+ return flag_tensor.item() # type: ignore
+ else:
+ return flag
diff --git a/venv/lib/python3.10/site-packages/olmo/train.py b/venv/lib/python3.10/site-packages/olmo/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec8bb78ea99da3497bd84d8695ffe727be21ef3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/train.py
@@ -0,0 +1,930 @@
+from __future__ import annotations
+
+import cProfile
+import logging
+import math
+import os
+import random
+import shutil
+import time
+from collections import deque
+from dataclasses import dataclass, field
+from itertools import islice
+from pathlib import Path
+from pstats import SortKey
+from typing import Any, Deque, Dict, List, Optional, TextIO, Tuple
+
+import numpy as np
+import torch
+import torch.distributed as dist
+import torch.nn.functional as F
+import wandb
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+from torch.utils.data import DataLoader
+
+from .aliases import PathOrStr
+from .checkpoint import Checkpointer, FullCheckpointer, build_sharded_checkpointer
+from .config import (
+ CheckpointType,
+ ShardedCheckpointerType,
+ SpeedMonitorConfig,
+ TrainConfig,
+)
+from .data import IterableDataset
+from .eval import Evaluator
+from .exceptions import OlmoConfigurationError
+from .model import Olmo
+from .optim import Optimizer, Scheduler
+from .torch_util import (
+ barrier,
+ get_fs_local_rank,
+ get_global_rank,
+ get_world_size,
+ move_to_device,
+ peak_gpu_memory,
+ synchronize_flag,
+)
+from .util import upload
+
+__all__ = ["SpeedMonitor", "LRMonitor", "Trainer"]
+
+log = logging.getLogger(__name__)
+
+
+@dataclass
+class SpeedMonitor:
+ cfg: SpeedMonitorConfig
+ start_times: Deque[float] = field(default_factory=lambda: deque([]))
+ global_total_tokens: int = 0
+ device_interval_tokens: Deque[int] = field(default_factory=lambda: deque([]))
+
+ def batch_start(self, global_total_tokens: int, device_batch_num_tokens: int, record: bool = True) -> None:
+ self.global_total_tokens = global_total_tokens
+ if record:
+ if len(self.start_times) >= self.cfg.window_size:
+ self.start_times.popleft()
+ self.device_interval_tokens.popleft()
+ self.start_times.append(time.monotonic())
+ self.device_interval_tokens.append(device_batch_num_tokens)
+
+ def reset(self) -> None:
+ self.start_times.clear()
+ self.device_interval_tokens.clear()
+
+ def check(self) -> Dict[str, float]:
+ metrics: Dict[str, float] = {"throughput/total_tokens": self.global_total_tokens}
+ if self.start_times:
+ interval_seconds = time.monotonic() - self.start_times[0]
+ interval_batches = len(self.start_times)
+ interval_tokens = sum(self.device_interval_tokens)
+ metrics["throughput/device/tokens_per_second"] = interval_tokens / interval_seconds
+ metrics["throughput/device/batches_per_second"] = interval_batches / interval_seconds
+ return metrics
+
+
+@dataclass
+class LRMonitor:
+ optim: torch.optim.Optimizer
+
+ def check(self) -> Dict[str, float]:
+ lrs = [group["lr"] for group in self.optim.param_groups]
+ return {f"optim/learning_rate_group{idx}": lr for idx, lr in enumerate(lrs)}
+
+
+@dataclass
+class Trainer:
+ cfg: TrainConfig
+ model: Olmo
+ fsdp_model: FSDP
+ optim: Optimizer
+ scheduler: Scheduler
+ train_loader: DataLoader
+ device: torch.device
+ evaluators: List[Evaluator]
+ epoch: int = 0
+ global_step: int = 0
+ global_train_examples_seen_this_epoch: int = 0
+ """Tracks the global number of training examples seen in the current epoch for the purpose of restoring
+ the data loader position on restarts."""
+ global_train_tokens_seen: int = 0
+ """Tracks the global total number of tokens trained on."""
+ checkpoints: List[Path] = field(default_factory=list)
+ unsharded_checkpoints: List[Path] = field(default_factory=list)
+ min_train_loss: float = float("inf")
+ cur_train_loss: float = float("inf")
+ indices_file: Optional[TextIO] = None
+ _start_time: float = 0.0
+
+ @property
+ def max_steps(self) -> int:
+ if isinstance(self.cfg.max_duration, int):
+ return self.cfg.max_duration
+ elif isinstance(self.cfg.max_duration, str):
+ if self.cfg.max_duration.endswith("T"):
+ # convert to float *first* to handle scientific notation
+ max_tokens = int(float(self.cfg.max_duration[:-1].strip()))
+ tokens_remaining = max_tokens - self.global_train_tokens_seen
+ tokens_per_batch = self.cfg.global_train_batch_size * self.cfg.model.max_sequence_length
+ steps_remaining = tokens_remaining // tokens_per_batch
+ return self.global_step + steps_remaining
+ else:
+ # convert to float *first* to handle scientific notation
+ return int(float(self.cfg.max_duration))
+ else:
+ raise TypeError(f"expected int or str for 'max_duration', found {type(self.cfg.max_duration)}")
+
+ def trainer_state_dict(self) -> Dict[str, Any]:
+ return {
+ "epoch": self.epoch,
+ "global_step": self.global_step,
+ "global_train_examples_seen_this_epoch": self.global_train_examples_seen_this_epoch,
+ "global_train_tokens_seen": self.global_train_tokens_seen,
+ "world_size": get_world_size(),
+ "checkpoints": self.checkpoints,
+ "unsharded_checkpoints": self.unsharded_checkpoints,
+ "rng": {
+ "python": random.getstate(),
+ "numpy": np.random.get_state(),
+ "torch": torch.random.get_rng_state(),
+ "cuda": torch.cuda.get_rng_state(),
+ },
+ }
+
+ def load_trainer_state_dict(self, state_dict: Dict[str, Any]) -> None:
+ # Checkpoint paths.
+ self.checkpoints = [
+ path
+ for path in state_dict["checkpoints"]
+ if path.is_dir() and path.resolve().parent == Path(self.cfg.save_folder).resolve()
+ ]
+ self.unsharded_checkpoints = [
+ path
+ for path in state_dict["unsharded_checkpoints"]
+ if path.is_dir() and path.resolve().parent == Path(self.cfg.save_folder).resolve()
+ ]
+
+ # Dataset / dataloader position.
+ checkpoint_epoch = state_dict.get("epoch", 0)
+ self.global_step = state_dict["global_step"]
+ self.global_train_examples_seen_this_epoch = state_dict.get(
+ "global_train_examples_seen_this_epoch",
+ state_dict.get( # for backwards compatibility
+ "global_train_examples_seen",
+ state_dict.get("global_data_step", self.global_step) * self.cfg.global_train_batch_size,
+ ),
+ )
+ self.global_train_tokens_seen = state_dict.get(
+ "global_train_tokens_seen",
+ state_dict.get("global_data_step", self.global_step) # for backwards compatibility
+ * self.cfg.global_train_batch_size
+ * self.cfg.model.max_sequence_length,
+ )
+
+ if not self.cfg.restore_dataloader:
+ self.epoch = 0
+ self.global_train_tokens_seen = 0
+ self.global_train_examples_seen_this_epoch = 0
+ elif checkpoint_epoch != self.epoch:
+ log.info(f"Starting new epoch (epoch = {self.epoch})")
+ self.global_train_examples_seen_this_epoch = 0
+
+ if self.cfg.fast_forward_batches:
+ log.info(f"Fast-forwarding data loader by {self.cfg.fast_forward_batches:,d} steps")
+ # Technically we don't "see" these batches that we fast-forward through, but we use
+ # this variable to update the position of the dataset so we need to include them here.
+ self.global_train_examples_seen_this_epoch += (
+ self.cfg.fast_forward_batches * self.cfg.global_train_batch_size
+ )
+ # NOTE: on the other hand we don't add anything to 'self.global_train_tokens_seen' here because
+ # that variable is meant to track the actual number of tokens trained on.
+
+ if self.global_train_examples_seen_this_epoch > 0:
+ assert isinstance(self.train_loader.dataset, IterableDataset)
+ log.info(f"Data loader will start at instance index {self.global_train_examples_seen_this_epoch:,d}")
+ self.train_loader.dataset.start_index = self.global_train_examples_seen_this_epoch
+
+ # Reset learning rate and weight decay to the values from the config, not the checkpoint.
+ log.info("Resetting learning rate...")
+ new_learning_rate = self.scheduler.get_lr(
+ self.cfg.optimizer.learning_rate, self.global_step, self.max_steps
+ )
+ for group in self.optim.param_groups:
+ group["lr"] = new_learning_rate
+ group["initial_lr"] = self.cfg.optimizer.learning_rate
+ if "weight_decay" in group and group["weight_decay"] > 0.0:
+ group["weight_decay"] = self.cfg.optimizer.weight_decay
+
+ # RNG states.
+ if "rng" in state_dict and state_dict.get("world_size", get_world_size()) == get_world_size():
+ log.info("Restoring RNG states...")
+ rng_state = state_dict["rng"]
+ self.restore_rng_state(rng_state)
+ else:
+ log.warning(
+ "Trainer will not restore RNG states since the RNG states in the checkpoint are missing or invalid. "
+ "This typically happens when restoring from an unsharded checkpoint or a checkpoint that was saved "
+ "with a different world size. If that's the case you can safely ignore this warning."
+ )
+
+ def restore_rng_state(self, rng_state: Dict[str, Any]) -> None:
+ random.setstate(rng_state["python"])
+ np.random.set_state(rng_state["numpy"])
+ torch.set_rng_state(rng_state["torch"])
+ torch.cuda.set_rng_state(rng_state["cuda"])
+
+ def _save_checkpoint(
+ self, checkpointer: Checkpointer, checkpoint_type: CheckpointType
+ ) -> Tuple[PathOrStr, Optional[PathOrStr]]:
+ if checkpoint_type == CheckpointType.sharded:
+ suffix = ""
+ current_checkpoints = self.checkpoints
+ link_latest = get_fs_local_rank() == 0
+ num_checkpoints_to_keep = self.cfg.save_num_checkpoints_to_keep
+ elif checkpoint_type == CheckpointType.unsharded:
+ suffix = "-unsharded"
+ current_checkpoints = self.unsharded_checkpoints
+ link_latest = get_global_rank() == 0
+ num_checkpoints_to_keep = self.cfg.save_num_unsharded_checkpoints_to_keep
+ else:
+ raise NotImplementedError(checkpoint_type)
+
+ # Zero-gradients to avoid gathering them.
+ self.optim.zero_grad(set_to_none=True)
+
+ # Flush data indices file.
+ # TODO: upload the indices files?
+ if self.indices_file is not None:
+ self.indices_file.flush()
+
+ checkpoint_dir = Path(self.cfg.save_folder) / f"step{self.global_step}{suffix}"
+ remote_checkpoint_dir: Optional[str] = None
+ if self.cfg.remote_save_folder is not None:
+ remote_checkpoint_dir = f"{self.cfg.remote_save_folder.rstrip('/')}/{checkpoint_dir.name}"
+ current_checkpoints.append(checkpoint_dir)
+
+ # Save the checkpoint.
+ try:
+ checkpointer.save_checkpoint(
+ checkpoint_dir,
+ self.fsdp_model,
+ self.optim,
+ self.trainer_state_dict(),
+ upload_to=remote_checkpoint_dir,
+ )
+ except FileExistsError:
+ raise OlmoConfigurationError(
+ f"Checkpoint for step {self.global_step} already exists, use --save-overwrite to overwrite it"
+ )
+
+ if link_latest:
+ # Link to 'latest'.
+ latest_path = Path(self.cfg.save_folder) / f"latest{suffix}"
+ latest_path.unlink(missing_ok=True)
+ try:
+ latest_path.symlink_to(checkpoint_dir.name, target_is_directory=True)
+ except FileExistsError:
+ # Same as above, caught when another (file-system) local rank 0 has already made the 'latest' symlink.
+ # This can happen when nodes are saving to a common NFS drive but otherwise have distinct
+ # file-systems.
+ if latest_path.resolve().name != checkpoint_dir.name:
+ raise
+
+ # Remove old checkpoints.
+ if num_checkpoints_to_keep > 0:
+ while len(current_checkpoints) > num_checkpoints_to_keep:
+ self.remove_checkpoint(0, checkpoint_type)
+
+ barrier()
+
+ if remote_checkpoint_dir is not None:
+ return remote_checkpoint_dir, checkpoint_dir
+ else:
+ return checkpoint_dir, None
+
+ def save_sharded_checkpoint(self) -> Tuple[PathOrStr, Optional[PathOrStr]]:
+ checkpointer = build_sharded_checkpointer(self.cfg)
+ return self._save_checkpoint(checkpointer, CheckpointType.sharded)
+
+ def remove_sharded_checkpoint(self, idx: int = 0):
+ oldest_checkpoint = self.checkpoints.pop(idx)
+ barrier()
+ if get_fs_local_rank() == 0 and oldest_checkpoint.is_dir():
+ shutil.rmtree(oldest_checkpoint, ignore_errors=True)
+ latest_path = Path(self.cfg.save_folder) / "latest"
+ if latest_path.resolve() == oldest_checkpoint.resolve():
+ latest_path.unlink()
+ barrier()
+
+ def restore_sharded_checkpoint(
+ self,
+ load_path: PathOrStr,
+ local_cache: Optional[PathOrStr] = None,
+ *,
+ load_optimizer_state: bool = True,
+ sharded_checkpointer: Optional[ShardedCheckpointerType] = None,
+ ):
+ # Zero-gradients to avoid gathering them.
+ self.optim.zero_grad(set_to_none=True)
+ checkpointer = build_sharded_checkpointer(self.cfg, name=sharded_checkpointer)
+ trainer_state = checkpointer.restore_checkpoint(
+ load_path,
+ self.fsdp_model,
+ self.optim,
+ local_cache=local_cache,
+ load_optimizer_state=load_optimizer_state,
+ )
+ self.load_trainer_state_dict(trainer_state)
+ barrier()
+
+ def save_unsharded_checkpoint(self) -> Tuple[PathOrStr, Optional[PathOrStr]]:
+ checkpointer = FullCheckpointer(self.cfg)
+ return self._save_checkpoint(checkpointer, CheckpointType.unsharded)
+
+ def remove_unsharded_checkpoint(self, idx: int = 0):
+ barrier()
+ oldest_checkpoint = self.unsharded_checkpoints.pop(idx)
+ if get_global_rank() == 0 and oldest_checkpoint.is_dir():
+ shutil.rmtree(oldest_checkpoint, ignore_errors=True)
+ latest_path = Path(self.cfg.save_folder) / "latest-unsharded"
+ if latest_path.resolve() == oldest_checkpoint.resolve():
+ latest_path.unlink()
+ barrier()
+
+ def restore_unsharded_checkpoint(
+ self, load_path: PathOrStr, local_cache: Optional[PathOrStr] = None, *, load_optimizer_state: bool = True
+ ):
+ # Zero-gradients to avoid gathering them.
+ self.optim.zero_grad(set_to_none=True)
+ checkpointer = FullCheckpointer(self.cfg)
+ trainer_state = checkpointer.restore_checkpoint(
+ load_path,
+ self.fsdp_model,
+ self.optim,
+ local_cache=local_cache,
+ load_optimizer_state=load_optimizer_state,
+ )
+ self.load_trainer_state_dict(trainer_state)
+ barrier()
+
+ def save_checkpoint(
+ self, checkpoint_type: CheckpointType = CheckpointType.sharded
+ ) -> Tuple[PathOrStr, Optional[PathOrStr]]:
+ if checkpoint_type == CheckpointType.sharded:
+ return self.save_sharded_checkpoint()
+ elif checkpoint_type == CheckpointType.unsharded:
+ return self.save_unsharded_checkpoint()
+ else:
+ raise NotImplementedError(checkpoint_type)
+
+ def restore_checkpoint(
+ self,
+ load_path: PathOrStr,
+ *,
+ checkpoint_type: Optional[CheckpointType] = None,
+ local_cache: Optional[PathOrStr] = None,
+ load_optimizer_state: bool = True,
+ sharded_checkpointer: Optional[ShardedCheckpointerType] = None,
+ ):
+ if checkpoint_type == CheckpointType.unsharded or (
+ checkpoint_type is None and str(load_path).rstrip("/").endswith("-unsharded")
+ ):
+ self.restore_unsharded_checkpoint(
+ load_path, local_cache=local_cache, load_optimizer_state=load_optimizer_state
+ )
+ elif checkpoint_type == CheckpointType.sharded or checkpoint_type is None:
+ self.restore_sharded_checkpoint(
+ load_path,
+ local_cache=local_cache,
+ load_optimizer_state=load_optimizer_state,
+ sharded_checkpointer=sharded_checkpointer,
+ )
+ elif checkpoint_type is not None:
+ raise NotImplementedError(checkpoint_type)
+
+ def remove_checkpoint(self, idx: int = 0, checkpoint_type: CheckpointType = CheckpointType.sharded):
+ if checkpoint_type == CheckpointType.sharded:
+ self.remove_sharded_checkpoint(idx=idx)
+ elif checkpoint_type == CheckpointType.unsharded:
+ self.remove_unsharded_checkpoint(idx=idx)
+ else:
+ raise NotImplementedError(checkpoint_type)
+
+ def get_labels(self, batch: Dict[str, Any]) -> torch.Tensor:
+ # Labels are just input IDs shifted to the left (first item is ignored).
+ labels, attention_mask = batch["input_ids"], batch.get("attention_mask")
+ if attention_mask is not None:
+ labels = labels.masked_fill(attention_mask == 0.0, -100)
+ return labels[..., 1:].contiguous()
+
+ def model_forward(
+ self, batch: Dict[str, Any], loss_reduction: str = "mean"
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ # shape: (batch_size, seq_len, vocab_size)
+ logits = self.fsdp_model(
+ input_ids=batch["input_ids"],
+ attention_mask=batch.get("attention_mask"),
+ attention_bias=batch.get("attention_bias"),
+ ).logits
+ logits_for_loss = logits[..., :-1, :].contiguous()
+ # shape: (batch_size * seq_len, vocab_size)
+ logits_for_loss = logits_for_loss.view(-1, logits_for_loss.size(-1))
+ # shape: (batch_size, seq_len)
+ labels = self.get_labels(batch)
+ # shape: (batch_size * seq_len,)
+ labels = labels.view(-1)
+ ce_loss = F.cross_entropy(logits_for_loss, labels, ignore_index=-100, reduction=loss_reduction)
+ if loss_reduction == "none":
+ # Reshape (batch_size * seq_len,) -> (batch_size, seq_len)
+ ce_loss = ce_loss.view(batch["input_ids"].shape[0], -1)
+ return ce_loss, logits
+
+ def train_batch(self, batch: Dict[str, Any]) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ # Split into micro-batches.
+ micro_batches = self.split_batch(batch)
+
+ # In case this helps with memory utilization.
+ del batch
+
+ ce_batch_loss = torch.tensor(0.0, device=self.device)
+ z_batch_loss = None if not self.cfg.softmax_auxiliary_loss else torch.tensor(0.0, device=self.device)
+ for micro_batch in micro_batches:
+ with torch.autocast("cuda", enabled=True, dtype=self.cfg.autocast_precision):
+ # Run forward pass.
+ ce_loss, logits = self.model_forward(micro_batch)
+ ce_loss = ce_loss / len(micro_batches)
+
+ # In case this helps with memory utilization.
+ del micro_batch
+
+ # Update overall CE batch loss.
+ ce_batch_loss += ce_loss.detach()
+
+ # Get loss to optimize for.
+ if self.cfg.softmax_auxiliary_loss:
+ z_squared = logits.logsumexp(-1).pow(2).mean()
+ z_loss = 1e-4 * z_squared / len(micro_batches)
+ loss = ce_loss + z_loss
+
+ # Update overall Z batch loss.
+ z_batch_loss += z_loss.detach()
+ else:
+ loss = ce_loss
+
+ del logits
+
+ # Run backward pass.
+ loss.backward()
+
+ return ce_batch_loss, z_batch_loss
+
+ def train_step(self, batch: Dict[str, Any], reduce_global_loss: bool = True) -> Dict[str, float]:
+ metrics: Dict[str, float] = {}
+
+ # Write data-indices to file.
+ if self.indices_file is not None and "index" in batch:
+ indices = "\t".join(str(int(i)) for i in batch["index"])
+ self.indices_file.write(f"{self.global_step}\t{indices}\n")
+
+ # Zero-gradients.
+ self.optim.zero_grad(set_to_none=True)
+
+ # Move tensors to the right device.
+ batch = move_to_device(batch, self.device)
+
+ # Run forward-backward pass.
+ ce_batch_loss, z_batch_loss = self.train_batch(batch)
+
+ # Collect loss, potentially reducing over all ranks.
+ if reduce_global_loss:
+ dist.reduce(ce_batch_loss, 0)
+ ce_batch_loss.div_(get_world_size())
+ if z_batch_loss is not None:
+ dist.reduce(z_batch_loss, 0)
+ z_batch_loss.div_(get_world_size())
+
+ # Clip gradient norms and collect param/gradient/optim metrics.
+ should_log_optim_metrics_this_step = self.should_log_optim_metrics_this_step()
+ optim_metrics = self.optim.clip_grads_and_collect_metrics(
+ self.global_step, collect_param_metrics=should_log_optim_metrics_this_step
+ )
+
+ # Adjust the learning rate.
+ for group in self.optim.param_groups:
+ # TODO (epwalsh): if we want to enable different LRs or gradient clipping settings per group
+ # we should pass `group["initial_lr"]` or `group["initial_max_grad_norm"]` here instead of
+ # the corresponding values from `self.cfg`.
+ group["lr"] = self.scheduler.get_lr(self.cfg.optimizer.learning_rate, self.global_step, self.max_steps)
+ group["max_grad_norm"] = self.scheduler.get_max_grad_norm(
+ self.cfg.max_grad_norm, self.global_step, self.max_steps
+ )
+ group["max_grad_norm_ratio"] = self.scheduler.get_max_grad_norm(
+ self.cfg.max_grad_norm_ratio, self.global_step, self.max_steps
+ )
+
+ # Optimizer step.
+ self.optim.step()
+
+ # Collect metrics and check for NaN loss.
+ # NOTE: this involves a bunch of host-device syncs so we wait until the last moment to do this.
+ if torch.isnan(ce_batch_loss):
+ raise ValueError("nan loss encountered")
+ if z_batch_loss is not None and torch.isnan(z_batch_loss):
+ raise ValueError("nan loss encountered")
+ for key, value in optim_metrics.items():
+ metrics[f"optim/{key}"] = value.item()
+ self.cur_train_loss = ce_batch_loss.item()
+ self.min_train_loss = min(self.min_train_loss, self.cur_train_loss)
+ metrics["train/CrossEntropyLoss"] = self.cur_train_loss
+ metrics["train/Perplexity"] = math.exp(self.cur_train_loss)
+ if z_batch_loss is not None:
+ metrics["train/ZLoss"] = z_batch_loss.item()
+
+ # Maybe collect post-step optimizer-specific metrics.
+ if should_log_optim_metrics_this_step:
+ optim_metrics = self.optim.get_post_step_metrics(self.fsdp_model)
+ for key, value in optim_metrics.items():
+ metrics[f"optim/{key}"] = value.item()
+
+ return metrics
+
+ def eval_batch(self, batch: Dict[str, Any]) -> Tuple[torch.Tensor, torch.Tensor]:
+ with torch.autocast("cuda", enabled=True, dtype=self.cfg.autocast_precision):
+ ce_loss, logits = self.model_forward(batch, loss_reduction="none")
+ return ce_loss.mean(dim=-1), logits
+
+ def eval_step(self, batch: Dict[str, Any], evaluator: Evaluator) -> None:
+ # Move tensors to the right device.
+ batch = move_to_device(batch, self.device)
+
+ # Run forward pass.
+ with torch.no_grad(): # NOTE: 'torch.inference_mode()' doesn't work with 'torch.compile()'.
+ ce_loss, logits = self.eval_batch(batch)
+
+ # Update metrics.
+ evaluator.update_metrics(
+ batch, ce_loss, logits
+ ) # batch includes all keys that the downstream evaluation needs
+
+ barrier()
+
+ def split_batch(self, batch: Dict[str, Any]) -> List[Dict[str, Any]]:
+ microbatch_size = self.cfg.device_train_microbatch_size
+ batch_size = batch["input_ids"].shape[0]
+ if batch_size <= microbatch_size:
+ return [batch]
+ else:
+ micro_batches = {}
+ for key, value in batch.items():
+ if isinstance(value, torch.Tensor):
+ micro_batches[key] = value.split(microbatch_size, dim=0)
+ elif isinstance(value, list):
+ micro_batches[key] = [
+ value[microbatch_size * i : microbatch_size * i + microbatch_size]
+ for i in range(math.ceil(batch_size / microbatch_size))
+ ]
+ else:
+ raise ValueError(f"unexpected item in batch: '{key}={value}'")
+ return [
+ {key: value[i] for key, value in micro_batches.items()} # type: ignore
+ for i in range(len(micro_batches["input_ids"]))
+ ]
+
+ def system_metrics(self) -> Dict[str, float]:
+ metrics = {}
+ if self.global_step < 3 or self.global_step % 10 == 0:
+ peak_gpu_mb = peak_gpu_memory()
+ if peak_gpu_mb is not None:
+ metrics["System/Peak GPU Memory (MB)"] = peak_gpu_mb
+ return metrics
+
+ def log_metrics_to_console(self, prefix: str, metrics: Dict[str, float]):
+ def format_float(value: float) -> str:
+ if value < 0.0001:
+ return str(value) # scientific notation
+ elif value > 1000:
+ return f"{int(value):,d}"
+ elif value > 100:
+ return f"{value:.1f}"
+ elif value > 10:
+ return f"{value:.2f}"
+ elif value > 1:
+ return f"{value:.3f}"
+ else:
+ return f"{value:.4f}"
+
+ log.info(
+ f"{prefix}\n"
+ + "\n".join(
+ [
+ f" {name}={format_float(value)}"
+ for name, value in metrics.items()
+ if not name.startswith("optim/") # there's too many optimizer metrics
+ ]
+ )
+ )
+
+ def should_log_optim_metrics_this_step(self) -> bool:
+ if self.cfg.wandb is None:
+ # We only log optimizer-specific metrics to W&B, since there are usually too many metrics
+ # to log to the console.
+ return False
+ optim_log_interval = self.cfg.optimizer.metrics_log_interval
+ if optim_log_interval is None:
+ optim_log_interval = self.cfg.wandb.log_interval
+ else:
+ optim_log_interval = max(optim_log_interval, self.cfg.wandb.log_interval)
+ return self.global_step % optim_log_interval == 0
+
+ def should_log_this_step(self) -> bool:
+ if self.global_step % self.cfg.console_log_interval == 0:
+ return True
+ elif self.cfg.wandb is not None and self.global_step % self.cfg.wandb.log_interval == 0:
+ return True
+ else:
+ return False
+
+ def eval(self) -> Dict[str, Any]:
+ # Zero gradients and set model to 'eval' mode.
+ self.optim.zero_grad(set_to_none=True)
+ self.fsdp_model.eval()
+
+ eval_metrics = {}
+ for evaluator in self.evaluators:
+ log.info(f"Running evaluation for '{evaluator.label}'...")
+
+ # Reset metrics.
+ evaluator.reset_metrics()
+
+ # Initialize data loader iterator.
+ eval_batches = iter(evaluator.eval_loader)
+
+ # Adjust how many batches to evaluate on.
+ num_eval_batches = (
+ evaluator.subset_num_batches
+ if evaluator.subset_num_batches is not None
+ else self.cfg.eval_subset_num_batches
+ )
+ if num_eval_batches > 0:
+ num_eval_batches = min(num_eval_batches, len(evaluator.eval_loader))
+ eval_batches = islice(eval_batches, num_eval_batches)
+
+ # Run model over batches.
+ for eval_step, eval_batch in enumerate(eval_batches):
+ self.eval_step(eval_batch, evaluator)
+
+ # Log to console.
+ if eval_step + 1 == num_eval_batches or (eval_step + 1) % self.cfg.console_log_interval == 0:
+ log.info(f"[eval_step={eval_step + 1}/{num_eval_batches}]")
+
+ # Get final metrics.
+ metrics = evaluator.compute_metrics()
+ eval_metrics.update(metrics)
+ self.log_metrics_to_console(f"{evaluator.label}", metrics)
+
+ del eval_batches
+
+ return eval_metrics
+
+ def check_if_cancelled(self) -> bool:
+ should_cancel = False
+ cancel_reason: Optional[str] = None
+ if get_global_rank() == 0:
+ if self.cfg.time_limit is not None and time.time() - self._start_time >= self.cfg.time_limit:
+ # First check if we've reached the training time limit.
+ should_cancel = True
+ cancel_reason = "time limit reached"
+ elif (
+ self.cfg.early_stopping_factor is not None
+ and self.global_step > self.cfg.scheduler.t_warmup
+ and self.cur_train_loss > self.cfg.early_stopping_factor * self.min_train_loss
+ ):
+ # Next check if early stopping loss criteria is met.
+ should_cancel = True
+ cancel_reason = "early stopping from loss increase"
+ elif wandb.run is not None and (api_key := os.environ.get("WANDB_API_KEY")) is not None:
+ # Finally, check if someone canceled the run from W&B by adding the 'cancel' / 'canceled' tag..
+ # We won't see it in the run object. So we have to use the import/export API to check.
+ from requests.exceptions import RequestException
+
+ try:
+ api = wandb.Api(api_key=api_key)
+ run = api.run(wandb.run.path)
+ for tag in run.tags or []:
+ if tag.lower() in {"cancel", "canceled", "cancelled"}:
+ should_cancel = True
+ cancel_reason = "Weights & Biases tag"
+ break
+ except RequestException:
+ pass
+
+ run_canceled = synchronize_flag(should_cancel, self.device)
+ if run_canceled and cancel_reason is not None:
+ log.warning(f"Run canceled due to {cancel_reason}")
+ return run_canceled
+
+ def fit(self):
+ self._start_time = time.time()
+
+ if self.cfg.load_path is not None and self.global_step > 0 and self.cfg.eval_on_load:
+ eval_metrics = self.eval()
+ if wandb.run is not None:
+ wandb.log(eval_metrics, step=self.global_step)
+
+ # Set model to 'train' mode.
+ self.fsdp_model.train()
+
+ # Initialize monitors.
+ assert self.cfg.device_train_batch_size is not None
+ speed_monitor = SpeedMonitor(self.cfg.speed_monitor)
+ lr_monitor = LRMonitor(self.optim)
+
+ # Log system metrics at the start of training.
+ sys_metrics = self.system_metrics()
+ if sys_metrics:
+ self.log_metrics_to_console("Pre-train system metrics", sys_metrics)
+ if wandb.run is not None:
+ wandb.log(sys_metrics, step=0)
+
+ # Python Profiler stuff
+ if self.cfg.python_profiling:
+ python_profiler = cProfile.Profile()
+ else:
+ python_profiler = None
+
+ # PyTorch Profiler stuff
+ if self.cfg.torch_profiling and get_global_rank() == 0:
+ from torch.profiler import schedule
+
+ profiling_schedule = schedule(wait=1, warmup=5, active=3)
+
+ def on_trace_ready(p):
+ profiler_output_dir = Path(self.cfg.save_folder) / "profiler"
+ profiler_output_dir.mkdir(exist_ok=True)
+
+ output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=32)
+ log.info(f"Profile by total GPU time at step {p.step_num}:\n{output}")
+ output = p.key_averages().table(sort_by="self_cpu_time_total", row_limit=32)
+ log.info(f"Profile by total CPU time at step {p.step_num}:\n{output}")
+
+ p.export_chrome_trace(
+ str(trace_path := (profiler_output_dir / f"{p.step_num}.chrome_trace.json.gz"))
+ )
+ if self.cfg.remote_save_folder is not None:
+ upload_folder = f"{self.cfg.remote_save_folder.rstrip('/')}/profiler"
+ log.info(f"Tracing complete, uploading results to '{upload_folder}'...")
+ upload(trace_path, f"{upload_folder}/{trace_path.name}")
+
+ from torch.profiler import ProfilerActivity
+
+ torch_profiler = torch.profiler.profile(
+ activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
+ record_shapes=False,
+ profile_memory=False,
+ with_stack=True,
+ schedule=profiling_schedule,
+ on_trace_ready=on_trace_ready,
+ )
+ del profiling_schedule
+ else:
+ import contextlib
+
+ torch_profiler = contextlib.nullcontext()
+
+ # Train.
+ first_batch: bool = True
+ canceled: bool = False
+
+ with torch_profiler as p:
+ for batch in self.train_loader:
+ # Bookkeeping.
+ # NOTE: To track the global batch size / number of tokens per batch we make the assumption that all
+ # batches see the same number of tokens, which should be the case for language model pre-training
+ # (at least when drop_last=True).
+ # Alternatively we'd have to use a distributed all reduce over seq_len here, but I don't want that
+ # overhead. So for now I'm putting these assertions here so if the assumption is violated it will
+ # fail loudly.
+ batch_size, seq_len = batch["input_ids"].shape
+ assert seq_len == self.cfg.model.max_sequence_length
+ assert batch_size == self.cfg.device_train_batch_size
+ global_batch_size = batch_size * get_world_size() # assumes batch size equal across ranks
+ self.global_step += 1
+ self.global_train_examples_seen_this_epoch += global_batch_size
+ self.global_train_tokens_seen += global_batch_size * seq_len
+ speed_monitor.batch_start(
+ self.global_train_tokens_seen,
+ batch_size * seq_len, # num tokens in batch for this device
+ # We start monitoring speed after the first batch since the first
+ # batch might be an outlier due to compiling and other initialization overhead.
+ record=not first_batch,
+ )
+
+ should_log_this_step = self.should_log_this_step()
+
+ # Run train step on batch.
+ metrics = self.train_step(batch, reduce_global_loss=should_log_this_step)
+
+ # Maybe collect other metrics.
+ if should_log_this_step:
+ # Speed metrics.
+ metrics.update(speed_monitor.check())
+ # System metrics.
+ metrics.update(self.system_metrics())
+ # Learning rate metrics.
+ metrics.update(lr_monitor.check())
+
+ # Log metrics to console.
+ if self.global_step % self.cfg.console_log_interval == 0:
+ self.log_metrics_to_console(f"[step={self.global_step}/{self.max_steps}]", metrics)
+
+ # Log metrics to W&B.
+ if (
+ wandb.run is not None
+ and self.cfg.wandb is not None
+ and self.global_step % self.cfg.wandb.log_interval == 0
+ ):
+ wandb.log(metrics, step=self.global_step)
+
+ # Check if run should be canceled.
+ if self.cfg.stop_at is not None and self.global_step >= self.cfg.stop_at:
+ canceled = True
+ elif self.global_step % self.cfg.canceled_check_interval == 0:
+ canceled = self.check_if_cancelled()
+
+ # Maybe save sharded checkpoint.
+ if canceled or (
+ self.global_step % self.cfg.save_interval == 0 and self.cfg.save_num_checkpoints_to_keep != 0
+ ):
+ log.info("Saving checkpoint...")
+ checkpoint_path, _ = self.save_checkpoint(CheckpointType.sharded)
+ log.info(f"Checkpoint saved to {checkpoint_path}")
+
+ # Reset speed monitor so that we don't count the time taken to save checkpoints.
+ speed_monitor.reset()
+
+ # Maybe save unsharded checkpoint.
+ if (
+ not canceled # we already save a sharded checkpoint when canceled
+ and self.cfg.save_interval_unsharded is not None
+ and self.global_step % self.cfg.save_interval_unsharded == 0
+ and self.cfg.save_num_unsharded_checkpoints_to_keep != 0
+ ):
+ log.info("Saving unsharded checkpoint...")
+ checkpoint_path, _ = self.save_checkpoint(CheckpointType.unsharded)
+ log.info(f"Unsharded checkpoint saved to {checkpoint_path}")
+
+ # Reset speed monitor so that we don't count the time taken to save checkpoints.
+ speed_monitor.reset()
+
+ # Maybe run evaluations.
+ if not canceled and self.global_step % self.cfg.eval_interval == 0:
+ eval_metrics = self.eval()
+
+ # Log metrics to W&B.
+ if wandb.run is not None:
+ wandb.log(eval_metrics, step=self.global_step)
+
+ # Reset speed monitor so that we don't count the time taken to run evaluations.
+ speed_monitor.reset()
+
+ # Reset model to 'train' mode.
+ self.fsdp_model.train()
+
+ # End of batch.
+ first_batch = False
+ if p is not None:
+ p.step()
+
+ if canceled:
+ break
+
+ # Python Profiler stuff
+ # We do this now, at the bottom of this loop, so we capture the work of getting the next batch.
+ if python_profiler is not None:
+ if self.global_step == 5:
+ python_profiler.enable()
+ elif self.global_step == 8:
+ python_profiler.disable()
+ python_profiler.print_stats(sort=SortKey.CUMULATIVE)
+ python_profiler = None
+ else:
+ log.info("Training loop complete")
+
+ # Save final unsharded model-only checkpoint.
+ if not canceled and self.cfg.save_interval_unsharded is not None:
+ log.info("Saving final unsharded model checkpoint...")
+ checkpoint_path, _ = self.save_checkpoint(CheckpointType.unsharded)
+ log.info(f"Unsharded checkpoint saved to {checkpoint_path}")
+
+ def close(self, exit_code: int = 0) -> None:
+ if self.indices_file is not None:
+ self.indices_file.flush()
+ self.indices_file.close()
+ if wandb.run is not None:
+ wandb.finish(exit_code=exit_code, quiet=True)
+
+ def __enter__(self) -> Trainer:
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
+ del exc_val, exc_tb
+ self.close(0 if exc_type is None else 1)
diff --git a/venv/lib/python3.10/site-packages/olmo/util.py b/venv/lib/python3.10/site-packages/olmo/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bc971d1f60cea692ec14385eccaa95f4b3123ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/util.py
@@ -0,0 +1,652 @@
+import logging
+import os
+import re
+import socket
+import sys
+import time
+import warnings
+from datetime import datetime
+from enum import Enum
+from functools import cache
+from itertools import cycle, islice
+from pathlib import Path
+from queue import Queue
+from threading import Thread
+from typing import Any, Callable, Dict, Optional, Union
+
+import boto3
+import botocore.exceptions as boto_exceptions
+import rich
+from botocore.config import Config
+from rich.console import Console, ConsoleRenderable
+from rich.highlighter import NullHighlighter
+from rich.progress import Progress
+from rich.text import Text
+from rich.traceback import Traceback
+
+from .aliases import PathOrStr
+from .exceptions import (
+ OlmoCliError,
+ OlmoEnvironmentError,
+ OlmoError,
+ OlmoNetworkError,
+ OlmoThreadError,
+)
+from .torch_util import get_global_rank, get_local_rank, get_node_rank, is_distributed
+
+
+class StrEnum(str, Enum):
+ """
+ This is equivalent to Python's :class:`enum.StrEnum` since version 3.11.
+ We include this here for compatibility with older version of Python.
+ """
+
+ def __str__(self) -> str:
+ return self.value
+
+ def __repr__(self) -> str:
+ return f"'{str(self)}'"
+
+
+_log_extra_fields: Dict[str, Any] = {}
+log = logging.getLogger(__name__)
+
+
+class LogFilterType(StrEnum):
+ rank0_only = "rank0_only"
+ local_rank0_only = "local_rank0_only"
+
+
+def log_extra_field(field_name: str, field_value: Any) -> None:
+ global _log_extra_fields
+ if field_value is None:
+ if field_name in _log_extra_fields:
+ del _log_extra_fields[field_name]
+ else:
+ _log_extra_fields[field_name] = field_value
+
+
+def setup_logging(log_filter_type: LogFilterType = LogFilterType.rank0_only) -> None:
+ """
+ :param rank0_only: INFO and below messages will only be emitted on the rank0 process.
+ """
+ log_extra_field("hostname", socket.gethostname())
+ if is_distributed():
+ log_extra_field("node_rank", get_node_rank())
+ log_extra_field("local_rank", get_local_rank())
+ log_extra_field("global_rank", get_global_rank())
+ else:
+ log_extra_field("node_rank", 0)
+ log_extra_field("local_rank", 0)
+ log_extra_field("global_rank", 0)
+
+ old_log_record_factory = logging.getLogRecordFactory()
+
+ def log_record_factory(*args, **kwargs) -> logging.LogRecord:
+ record = old_log_record_factory(*args, **kwargs)
+ for field_name, field_value in _log_extra_fields.items():
+ setattr(record, field_name, field_value)
+ return record
+
+ logging.setLogRecordFactory(log_record_factory)
+
+ handler: logging.Handler
+ if (
+ os.environ.get("OLMo_NONINTERACTIVE", False)
+ or os.environ.get("DEBIAN_FRONTEND", None) == "noninteractive"
+ or not sys.stdout.isatty()
+ ):
+ handler = logging.StreamHandler(sys.stdout)
+ formatter = logging.Formatter(
+ "%(asctime)s\t%(hostname)s:%(local_rank)s\t%(name)s:%(lineno)s\t%(levelname)s\t%(message)s"
+ )
+ formatter.default_time_format = "%Y-%m-%d %H:%M:%S"
+ formatter.default_msec_format = "%s.%03d"
+ handler.setFormatter(formatter)
+ else:
+ handler = RichHandler()
+
+ def rank0_filter(record: logging.LogRecord) -> int:
+ if record.levelno > logging.INFO:
+ return 1
+ if getattr(record, "global_rank", 0) == 0:
+ return 1
+ else:
+ return 0
+
+ def local_rank0_filter(record: logging.LogRecord) -> int:
+ if record.levelno > logging.INFO:
+ return 1
+ if getattr(record, "local_rank", 0) == 0:
+ return 1
+ else:
+ return 0
+
+ filter = None
+ if log_filter_type == LogFilterType.rank0_only:
+ filter = rank0_filter
+ elif log_filter_type == LogFilterType.local_rank0_only:
+ filter = local_rank0_filter # type: ignore
+ else:
+ raise ValueError(log_filter_type)
+
+ if filter is not None:
+ handler.addFilter(filter) # type: ignore
+ logging.basicConfig(handlers=[handler], level=logging.INFO)
+
+ logzio_token = os.environ.get("LOGZIO_TOKEN", None)
+ if logzio_token:
+ from logzio.handler import LogzioHandler
+
+ logzio_handler = LogzioHandler(logzio_token)
+ if filter is not None:
+ logzio_handler.addFilter(filter) # type: ignore
+ logging.getLogger().addHandler(logzio_handler)
+
+ logging.captureWarnings(True)
+ logging.getLogger("urllib3").setLevel(logging.ERROR)
+
+
+def excepthook(exctype, value, traceback):
+ """
+ Used to patch `sys.excepthook` in order to log exceptions.
+ """
+ if issubclass(exctype, KeyboardInterrupt):
+ sys.__excepthook__(exctype, value, traceback)
+ elif issubclass(exctype, OlmoCliError):
+ rich.get_console().print(f"[yellow]{value}[/]", highlight=False)
+ elif issubclass(exctype, OlmoError):
+ rich.get_console().print(Text(f"{exctype.__name__}:", style="red"), value, highlight=False)
+ else:
+ log.critical("Uncaught %s: %s", exctype.__name__, value, exc_info=(exctype, value, traceback))
+
+
+def install_excepthook():
+ sys.excepthook = excepthook
+
+
+def filter_warnings():
+ # Filter internal deprecation warnings from torch
+ warnings.filterwarnings(
+ action="ignore",
+ category=UserWarning,
+ message="torch.distributed.*_base is a private function and will be deprecated.*",
+ )
+ warnings.filterwarnings(
+ action="ignore",
+ category=UserWarning,
+ message="TypedStorage is deprecated.*",
+ )
+ warnings.filterwarnings(
+ action="ignore",
+ category=UserWarning,
+ message="Please use DTensor instead.*",
+ )
+ # Torchvision warnings. We don't actually use torchvision.
+ warnings.filterwarnings(
+ action="ignore",
+ message="failed to load.*",
+ module="torchvision.io.image",
+ )
+
+
+def set_env_variables():
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+
+def prepare_cli_environment(log_filter_type: Optional[LogFilterType] = None):
+ if log_filter_type is None:
+ log_filter_type = LogFilterType(os.environ.get("LOG_FILTER_TYPE", "rank0_only"))
+ rich.reconfigure(width=max(rich.get_console().width, 180), soft_wrap=True)
+ setup_logging(log_filter_type=log_filter_type)
+ install_excepthook()
+ filter_warnings()
+ set_env_variables()
+
+
+def clean_opt(arg: str) -> str:
+ if "=" not in arg:
+ arg = f"{arg}=True"
+ name, val = arg.split("=", 1)
+ name = name.strip("-").replace("-", "_")
+ return f"{name}={val}"
+
+
+class RichHandler(logging.Handler):
+ """
+ A simplified version of rich.logging.RichHandler from
+ https://github.com/Textualize/rich/blob/master/rich/logging.py
+ """
+
+ def __init__(
+ self,
+ *,
+ level: Union[int, str] = logging.NOTSET,
+ console: Optional[Console] = None,
+ markup: bool = False,
+ ) -> None:
+ super().__init__(level=level)
+ self.console = console or rich.get_console()
+ self.highlighter = NullHighlighter()
+ self.markup = markup
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ if hasattr(record.msg, "__rich__") or hasattr(record.msg, "__rich_console__"):
+ self.console.print(record.msg)
+ else:
+ msg: Any = record.msg
+ if isinstance(record.msg, str):
+ msg = self.render_message(record=record, message=record.getMessage())
+ renderables = [
+ self.get_time_text(record),
+ self.get_level_text(record),
+ self.get_location_text(record),
+ msg,
+ ]
+ if record.exc_info is not None:
+ tb = Traceback.from_exception(*record.exc_info) # type: ignore
+ renderables.append(tb)
+ self.console.print(*renderables)
+ except Exception:
+ self.handleError(record)
+
+ def render_message(self, *, record: logging.LogRecord, message: str) -> ConsoleRenderable:
+ use_markup = getattr(record, "markup", self.markup)
+ message_text = Text.from_markup(message) if use_markup else Text(message)
+
+ highlighter = getattr(record, "highlighter", self.highlighter)
+ if highlighter:
+ message_text = highlighter(message_text)
+
+ return message_text
+
+ def get_time_text(self, record: logging.LogRecord) -> Text:
+ log_time = datetime.fromtimestamp(record.created)
+ time_str = log_time.strftime("[%Y-%m-%d %X]")
+ return Text(time_str, style="log.time", end=" ")
+
+ def get_level_text(self, record: logging.LogRecord) -> Text:
+ level_name = record.levelname
+ level_text = Text.styled(level_name.ljust(8), f"logging.level.{level_name.lower()}")
+ level_text.style = "log.level"
+ level_text.end = " "
+ return level_text
+
+ def get_location_text(self, record: logging.LogRecord) -> Text:
+ name_and_line = f"{record.name}:{record.lineno}" if record.name != "root" else "root"
+ text = f"[{name_and_line}, rank={record.local_rank}]" # type: ignore
+ return Text(text, style="log.path")
+
+
+def wait_for(condition: Callable[[], bool], description: str, timeout: float = 10.0):
+ """Wait for the condition function to return True."""
+ start_time = time.monotonic()
+ while not condition():
+ time.sleep(0.5)
+ if time.monotonic() - start_time > timeout:
+ raise TimeoutError(f"{description} timed out")
+
+
+def is_url(path: PathOrStr) -> bool:
+ return re.match(r"[a-z0-9]+://.*", str(path)) is not None
+
+
+def dir_is_empty(dir: PathOrStr) -> bool:
+ dir = Path(dir)
+ if not dir.is_dir():
+ return True
+ try:
+ next(dir.glob("*"))
+ return False
+ except StopIteration:
+ return True
+
+
+def get_progress_bar() -> Progress:
+ from cached_path import get_download_progress
+
+ return get_download_progress()
+
+
+def resource_path(
+ folder: PathOrStr, fname: str, local_cache: Optional[PathOrStr] = None, progress: Optional[Progress] = None
+) -> Path:
+ if local_cache is not None and (local_path := Path(local_cache) / fname).is_file():
+ log.info(f"Found local cache of {fname} at {local_path}")
+ return local_path
+ else:
+ from cached_path import cached_path
+
+ return cached_path(f"{str(folder).rstrip('/')}/{fname}", progress=progress)
+
+
+def file_size(path: PathOrStr) -> int:
+ """
+ Get the size of a local or remote file in bytes.
+ """
+ if is_url(path):
+ from urllib.parse import urlparse
+
+ parsed = urlparse(str(path))
+ if parsed.scheme == "gs":
+ return _gcs_file_size(parsed.netloc, parsed.path.strip("/"))
+ elif parsed.scheme in ("s3", "r2"):
+ return _s3_file_size(parsed.scheme, parsed.netloc, parsed.path.strip("/"))
+ elif parsed.scheme == "file":
+ return file_size(str(path).replace("file://", "", 1))
+ else:
+ raise NotImplementedError(f"file size not implemented for '{parsed.scheme}' files")
+ else:
+ return os.stat(path).st_size
+
+
+def upload(source: PathOrStr, target: str, save_overwrite: bool = False):
+ """Upload source file to a target location on GCS or S3."""
+ from urllib.parse import urlparse
+
+ source = Path(source)
+ assert source.is_file()
+ parsed = urlparse(target)
+ if parsed.scheme == "gs":
+ _gcs_upload(source, parsed.netloc, parsed.path.strip("/"), save_overwrite=save_overwrite)
+ elif parsed.scheme in ("s3", "r2"):
+ _s3_upload(source, parsed.scheme, parsed.netloc, parsed.path.strip("/"), save_overwrite=save_overwrite)
+ else:
+ raise NotImplementedError(f"Upload not implemented for '{parsed.scheme}' scheme")
+
+
+def get_bytes_range(source: PathOrStr, bytes_start: int, num_bytes: int) -> bytes:
+ if is_url(source):
+ from urllib.parse import urlparse
+
+ parsed = urlparse(str(source))
+ if parsed.scheme == "gs":
+ return _gcs_get_bytes_range(parsed.netloc, parsed.path.strip("/"), bytes_start, num_bytes)
+ elif parsed.scheme in ("s3", "r2"):
+ return _s3_get_bytes_range(
+ parsed.scheme, parsed.netloc, parsed.path.strip("/"), bytes_start, num_bytes
+ )
+ elif parsed.scheme == "file":
+ return get_bytes_range(str(source).replace("file://", "", 1), bytes_start, num_bytes)
+ else:
+ raise NotImplementedError(f"file size not implemented for '{parsed.scheme}' files")
+ else:
+ with open(source, "rb") as f:
+ f.seek(bytes_start)
+ return f.read(num_bytes)
+
+
+def find_latest_checkpoint(dir: PathOrStr) -> Optional[PathOrStr]:
+ if is_url(dir):
+ from urllib.parse import urlparse
+
+ parsed = urlparse(str(dir))
+ if parsed.scheme == "gs":
+ raise NotImplementedError
+ elif parsed.scheme in ("s3", "r2"):
+ return _s3_find_latest_checkpoint(parsed.scheme, parsed.netloc, parsed.path.strip("/"))
+ elif parsed.scheme == "file":
+ return find_latest_checkpoint(str(dir).replace("file://", "", 1))
+ else:
+ raise NotImplementedError(f"find_latest_checkpoint not implemented for '{parsed.scheme}' files")
+ else:
+ latest_step = 0
+ latest_checkpoint: Optional[Path] = None
+ for path in Path(dir).glob("step*"):
+ if path.is_dir():
+ try:
+ step = int(path.name.replace("step", "").replace("-unsharded", ""))
+ except ValueError:
+ continue
+ # We prioritize sharded checkpoints over unsharded checkpoints.
+ if step > latest_step or (step == latest_step and not path.name.endswith("-unsharded")):
+ latest_step = step
+ latest_checkpoint = path
+ return latest_checkpoint
+
+
+def _gcs_upload(source: Path, bucket_name: str, key: str, save_overwrite: bool = False):
+ from google.cloud import storage as gcs
+
+ storage_client = gcs.Client()
+ bucket = storage_client.bucket(bucket_name)
+ blob = bucket.blob(key)
+ if not save_overwrite and blob.exists():
+ raise FileExistsError(f"gs://{bucket_name}/{key} already exists. Use save_overwrite to overwrite it.")
+ blob.upload_from_filename(source)
+
+
+def _gcs_file_size(bucket_name: str, key: str) -> int:
+ from google.api_core.exceptions import NotFound
+ from google.cloud import storage as gcs
+
+ storage_client = gcs.Client()
+ bucket = storage_client.bucket(bucket_name)
+ blob = bucket.blob(key)
+ try:
+ blob.reload()
+ except NotFound:
+ raise FileNotFoundError(f"gs://{bucket_name}/{key}")
+ assert blob.size is not None
+ return blob.size
+
+
+def _gcs_get_bytes_range(bucket_name: str, key: str, bytes_start: int, num_bytes: int) -> bytes:
+ from google.api_core.exceptions import NotFound
+ from google.cloud import storage as gcs
+
+ storage_client = gcs.Client()
+ bucket = storage_client.bucket(bucket_name)
+ blob = bucket.blob(key)
+ try:
+ blob.reload()
+ except NotFound:
+ raise FileNotFoundError(f"gs://{bucket_name}/{key}")
+ return blob.download_as_bytes(start=bytes_start, end=bytes_start + num_bytes - 1)
+
+
+def _get_s3_profile_name(scheme: str) -> Optional[str]:
+ if scheme == "s3":
+ # For backwards compatibility, we assume S3 uses the default profile if S3_PROFILE is not set.
+ return os.environ.get("S3_PROFILE")
+ if scheme == "r2":
+ profile_name = os.environ.get("R2_PROFILE")
+ if profile_name is None:
+ raise OlmoEnvironmentError(
+ "R2 profile name is not set. Did you forget to set the 'R2_PROFILE' env var?"
+ )
+
+ return profile_name
+
+ raise NotImplementedError(f"Cannot get profile name for scheme {scheme}")
+
+
+def _get_s3_endpoint_url(scheme: str) -> Optional[str]:
+ if scheme == "s3":
+ return None
+ if scheme == "r2":
+ r2_endpoint_url = os.environ.get("R2_ENDPOINT_URL")
+ if r2_endpoint_url is None:
+ raise OlmoEnvironmentError(
+ "R2 endpoint url is not set. Did you forget to set the 'R2_ENDPOINT_URL' env var?"
+ )
+
+ return r2_endpoint_url
+
+ raise NotImplementedError(f"Cannot get endpoint url for scheme {scheme}")
+
+
+@cache
+def _get_s3_client(scheme: str):
+ session = boto3.Session(profile_name=_get_s3_profile_name(scheme))
+ return session.client(
+ "s3",
+ endpoint_url=_get_s3_endpoint_url(scheme),
+ config=Config(retries={"max_attempts": 10, "mode": "standard"}),
+ use_ssl=not int(os.environ.get("OLMO_NO_SSL", "0")),
+ )
+
+
+def _wait_before_retry(attempt: int):
+ time.sleep(min(0.5 * 2**attempt, 3.0))
+
+
+def _s3_upload(
+ source: Path, scheme: str, bucket_name: str, key: str, save_overwrite: bool = False, max_attempts: int = 3
+):
+ err: Optional[Exception] = None
+ if not save_overwrite:
+ for attempt in range(1, max_attempts + 1):
+ try:
+ _get_s3_client(scheme).head_object(Bucket=bucket_name, Key=key)
+ raise FileExistsError(
+ f"s3://{bucket_name}/{key} already exists. Use save_overwrite to overwrite it."
+ )
+ except boto_exceptions.ClientError as e:
+ if int(e.response["Error"]["Code"]) == 404:
+ err = None
+ break
+ err = e
+
+ if attempt < max_attempts:
+ log.warning("%s failed attempt %d with retriable error: %s", _s3_upload.__name__, attempt, err)
+ _wait_before_retry(attempt)
+
+ if err is not None:
+ raise OlmoNetworkError("Failed to check object existence during s3 upload") from err
+
+ try:
+ _get_s3_client(scheme).upload_file(source, bucket_name, key)
+ except boto_exceptions.ClientError as e:
+ raise OlmoNetworkError("Failed to upload to s3") from e
+
+
+def _s3_file_size(scheme: str, bucket_name: str, key: str, max_attempts: int = 3) -> int:
+ err: Optional[Exception] = None
+ for attempt in range(1, max_attempts + 1):
+ try:
+ return _get_s3_client(scheme).head_object(Bucket=bucket_name, Key=key)["ContentLength"]
+ except boto_exceptions.ClientError as e:
+ if int(e.response["Error"]["Code"]) == 404:
+ raise FileNotFoundError(f"s3://{bucket_name}/{key}") from e
+ err = e
+
+ if attempt < max_attempts:
+ log.warning("%s failed attempt %d with retriable error: %s", _s3_file_size.__name__, attempt, err)
+ _wait_before_retry(attempt)
+
+ raise OlmoNetworkError("Failed to get s3 file size") from err
+
+
+def _s3_get_bytes_range(
+ scheme: str, bucket_name: str, key: str, bytes_start: int, num_bytes: int, max_attempts: int = 3
+) -> bytes:
+ err: Optional[Exception] = None
+ for attempt in range(1, max_attempts + 1):
+ try:
+ return (
+ _get_s3_client(scheme)
+ .get_object(
+ Bucket=bucket_name, Key=key, Range=f"bytes={bytes_start}-{bytes_start + num_bytes - 1}"
+ )["Body"]
+ .read()
+ )
+ except boto_exceptions.ClientError as e:
+ if int(e.response["Error"]["Code"]) == 404:
+ raise FileNotFoundError(f"s3://{bucket_name}/{key}") from e
+ err = e
+ except (boto_exceptions.HTTPClientError, boto_exceptions.ConnectionError) as e:
+ # ResponseStreamingError (subclass of HTTPClientError) can happen as
+ # a result of a failed read from the stream (http.client.IncompleteRead).
+ # Retrying can help in this case.
+ err = e
+
+ if attempt < max_attempts:
+ log.warning(
+ "%s failed attempt %d with retriable error: %s", _s3_get_bytes_range.__name__, attempt, err
+ )
+ _wait_before_retry(attempt)
+
+ # When torch's DataLoader intercepts exceptions, it may try to re-raise them
+ # by recalling their constructor with a single message arg. Torch has some
+ # logic to deal with the absence of a single-parameter constructor, but it
+ # doesn't gracefully handle other possible failures in calling such a constructor
+ # This can cause an irrelevant exception (e.g. KeyError: 'error'), resulting
+ # in us losing the true exception info. To avoid this, we change the exception
+ # to a type that has a single-parameter constructor.
+ raise OlmoNetworkError("Failed to get bytes range from s3") from err
+
+
+def _s3_find_latest_checkpoint(scheme: str, bucket_name: str, prefix: str) -> Optional[str]:
+ if not prefix.endswith("/"):
+ prefix = f"{prefix}/"
+ response = _get_s3_client(scheme).list_objects(Bucket=bucket_name, Prefix=prefix, Delimiter="/")
+ assert not response["IsTruncated"] # need to handle this if it happens
+ latest_step = 0
+ latest_checkpoint: Optional[str] = None
+ for item in response["CommonPrefixes"]:
+ prefix = item["Prefix"].strip("/")
+ checkpoint_name = os.path.split(prefix)[-1]
+ if not checkpoint_name.startswith("step"):
+ continue
+ try:
+ step = int(checkpoint_name.replace("step", "").replace("-unsharded", ""))
+ except ValueError:
+ continue
+ # We prioritize sharded checkpoints over unsharded ones.
+ if step > latest_step or (step == latest_step and not checkpoint_name.endswith("-unsharded")):
+ latest_step = step
+ latest_checkpoint = f"s3://ai2-llm/{prefix}"
+ return latest_checkpoint
+
+
+def default_thread_count() -> int:
+ return int(os.environ.get("OLMO_NUM_THREADS") or min(32, (os.cpu_count() or 1) + 4))
+
+
+def pass_through_fn(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+
+def threaded_generator(g, maxsize: int = 16, thread_name: Optional[str] = None):
+ q: Queue = Queue(maxsize=maxsize)
+
+ sentinel = object()
+
+ def fill_queue():
+ try:
+ for value in g:
+ q.put(value)
+ except Exception as e:
+ q.put(e)
+ finally:
+ q.put(sentinel)
+
+ thread_name = thread_name or repr(g)
+ thread = Thread(name=thread_name, target=fill_queue, daemon=True)
+ thread.start()
+
+ for x in iter(q.get, sentinel):
+ if isinstance(x, Exception):
+ raise OlmoThreadError(f"generator thread {thread_name} failed") from x
+ else:
+ yield x
+
+
+def roundrobin(*iterables):
+ """
+ Call the given iterables in a round-robin fashion. For example:
+ ``roundrobin('ABC', 'D', 'EF') --> A D E B F C``
+ """
+ # Adapted from https://docs.python.org/3/library/itertools.html#itertools-recipes
+ num_active = len(iterables)
+ nexts = cycle(iter(it).__next__ for it in iterables)
+ while num_active:
+ try:
+ for next in nexts:
+ yield next()
+ except StopIteration:
+ # Remove the iterator we just exhausted from the cycle.
+ num_active -= 1
+ nexts = cycle(islice(nexts, num_active))
diff --git a/venv/lib/python3.10/site-packages/olmo/version.py b/venv/lib/python3.10/site-packages/olmo/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2120dded6b9ae5c940074c6f5afbc7df99884b32
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/olmo/version.py
@@ -0,0 +1,11 @@
+_MAJOR = "0"
+_MINOR = "2"
+# On main and in a nightly release the patch should be one ahead of the last
+# released build.
+_PATCH = "1"
+# This is mainly for nightly builds which have the suffix ".dev$DATE". See
+# https://semver.org/#is-v123-a-semantic-version for the semantics.
+_SUFFIX = ""
+
+VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR)
+VERSION = "{0}.{1}.{2}{3}".format(_MAJOR, _MINOR, _PATCH, _SUFFIX)
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..e4146c050b5063dd4e9bb1c5addfeee9ff638545
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/METADATA
@@ -0,0 +1,55 @@
+Metadata-Version: 2.3
+Name: opentelemetry-exporter-otlp-proto-http
+Version: 1.26.0
+Summary: OpenTelemetry Collector Protobuf over HTTP Exporter
+Project-URL: Homepage, https://github.com/open-telemetry/opentelemetry-python/tree/main/exporter/opentelemetry-exporter-otlp-proto-http
+Author-email: OpenTelemetry Authors
+License: Apache-2.0
+License-File: LICENSE
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Framework :: OpenTelemetry
+Classifier: Framework :: OpenTelemetry :: Exporters
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Requires-Python: >=3.8
+Requires-Dist: deprecated>=1.2.6
+Requires-Dist: googleapis-common-protos~=1.52
+Requires-Dist: opentelemetry-api~=1.15
+Requires-Dist: opentelemetry-exporter-otlp-proto-common==1.26.0
+Requires-Dist: opentelemetry-proto==1.26.0
+Requires-Dist: opentelemetry-sdk~=1.26.0
+Requires-Dist: requests~=2.7
+Description-Content-Type: text/x-rst
+
+OpenTelemetry Collector Protobuf over HTTP Exporter
+===================================================
+
+|pypi|
+
+.. |pypi| image:: https://badge.fury.io/py/opentelemetry-exporter-otlp-proto-http.svg
+ :target: https://pypi.org/project/opentelemetry-exporter-otlp-proto-http/
+
+This library allows to export data to the OpenTelemetry Collector using the OpenTelemetry Protocol using Protobuf over HTTP.
+
+Installation
+------------
+
+::
+
+ pip install opentelemetry-exporter-otlp-proto-http
+
+
+References
+----------
+
+* `OpenTelemetry Collector Exporter `_
+* `OpenTelemetry Collector `_
+* `OpenTelemetry `_
+* `OpenTelemetry Protocol Specification `_
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..34acad67920f6f4064b44c2fd57406a87c7809c0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/RECORD
@@ -0,0 +1,19 @@
+opentelemetry/exporter/otlp/proto/http/__init__.py,sha256=hQMloW_5Afp-m1j0g_7Dqm_asTEdMbDoQgdf_pk-kyQ,2682
+opentelemetry/exporter/otlp/proto/http/__pycache__/__init__.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/__pycache__/version.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/_log_exporter/__init__.py,sha256=_OGE04GxzcP80WEIjcsY4e9zl7x1C05upCU4kZZTg1Q,6582
+opentelemetry/exporter/otlp/proto/http/_log_exporter/__pycache__/__init__.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py,sha256=49fLKWLk9v95gZe9NYdGCquuZeUtkxheeAp-qsukhCY,8169
+opentelemetry/exporter/otlp/proto/http/metric_exporter/__pycache__/__init__.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+opentelemetry/exporter/otlp/proto/http/trace_exporter/__init__.py,sha256=g4tm7GRkeHVuAr1PnbpGmUsGjDrdbLmLd9Hyd-xC9jo,6750
+opentelemetry/exporter/otlp/proto/http/trace_exporter/__pycache__/__init__.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__init__.py,sha256=2emGlr87xvvEcTnycFO6Cj9b3pU0IbpPSapcZhnzX5c,2340
+opentelemetry/exporter/otlp/proto/http/trace_exporter/encoder/__pycache__/__init__.cpython-310.pyc,,
+opentelemetry/exporter/otlp/proto/http/version.py,sha256=ANYEMcxW_7kp7m-QhNKZUKat8Jf1JBtQ3N9YJF-3SLU,608
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/METADATA,sha256=PIrAnCmfGvV11dwb4x-71dZPp48AHrbQxxRwzrC2FEo,2260
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/RECORD,,
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/entry_points.txt,sha256=WOPQvujWzUUMIYKy8EI0C5Z_DC42MahQqP20_oL67B8,365
+opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..cdd68a497cdfa8d3f2b837225beacef711b85047
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.25.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bac8436faba93c8e2fa9d7caf3f1dd555ecd61ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/entry_points.txt
@@ -0,0 +1,8 @@
+[opentelemetry_logs_exporter]
+otlp_proto_http = opentelemetry.exporter.otlp.proto.http._log_exporter:OTLPLogExporter
+
+[opentelemetry_metrics_exporter]
+otlp_proto_http = opentelemetry.exporter.otlp.proto.http.metric_exporter:OTLPMetricExporter
+
+[opentelemetry_traces_exporter]
+otlp_proto_http = opentelemetry.exporter.otlp.proto.http.trace_exporter:OTLPSpanExporter
diff --git a/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/opentelemetry_exporter_otlp_proto_http-1.26.0.dist-info/licenses/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..090132eeeaa640b8042fdc0bd97d3dbe6a253a18
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2022 Tim Schwenke
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..00e41799c95d55e3ab876e914071903cf99f6780
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/METADATA
@@ -0,0 +1,343 @@
+Metadata-Version: 2.3
+Name: prometheus-fastapi-instrumentator
+Version: 7.1.0
+Summary: Instrument your FastAPI app with Prometheus metrics
+License: ISC
+Keywords: prometheus,instrumentation,fastapi,exporter,metrics
+Author: Tim Schwenke
+Author-email: tim@trallnag.com
+Requires-Python: >=3.8
+Classifier: License :: OSI Approved
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Requires-Dist: prometheus-client (>=0.8.0,<1.0.0)
+Requires-Dist: starlette (>=0.30.0,<1.0.0)
+Project-URL: Homepage, https://github.com/trallnag/prometheus-fastapi-instrumentator
+Description-Content-Type: text/markdown
+
+# Prometheus FastAPI Instrumentator
+
+[](https://pypi.python.org/pypi/prometheus-fastapi-instrumentator)
+[](https://pypi.python.org/pypi/prometheus-fastapi-instrumentator)
+[](https://pepy.tech/project/prometheus-fastapi-instrumentator/month)
+[](https://github.com/trallnag/kubestatus2cloudwatch/actions)
+[](https://codecov.io/gh/trallnag/prometheus-fastapi-instrumentator)
+
+A configurable and modular Prometheus Instrumentator for your FastAPI. Install
+`prometheus-fastapi-instrumentator` from
+[PyPI](https://pypi.python.org/pypi/prometheus-fastapi-instrumentator/). Here is
+the fast track to get started with a pre-configured instrumentator. Import the
+instrumentator class:
+
+```python
+from prometheus_fastapi_instrumentator import Instrumentator
+```
+
+Instrument your app with default metrics and expose the metrics:
+
+```python
+Instrumentator().instrument(app).expose(app)
+```
+
+Depending on your code you might have to use the following instead:
+
+```python
+instrumentator = Instrumentator().instrument(app)
+
+@app.on_event("startup")
+async def _startup():
+ instrumentator.expose(app)
+```
+
+With this, your FastAPI is instrumented and metrics are ready to be scraped. The
+defaults give you:
+
+- Counter `http_requests_total` with `handler`, `status` and `method`. Total
+ number of requests.
+- Summary `http_request_size_bytes` with `handler`. Added up total of the
+ content lengths of all incoming requests.
+- Summary `http_response_size_bytes` with `handler`. Added up total of the
+ content lengths of all outgoing responses.
+- Histogram `http_request_duration_seconds` with `handler` and `method`. Only a
+ few buckets to keep cardinality low.
+- Histogram `http_request_duration_highr_seconds` without any labels. Large
+ number of buckets (>20).
+
+In addition, following behavior is active:
+
+- Status codes are grouped into `2xx`, `3xx` and so on.
+- Requests without a matching template are grouped into the handler `none`.
+
+If one of these presets does not suit your needs you can do one of multiple
+things:
+
+- Pick one of the already existing closures from
+ [`metrics`](./src/prometheus_fastapi_instrumentator/metrics.py) and pass it to
+ the instrumentator instance. See [here](#adding-metrics) how to do that.
+- Create your own instrumentation function that you can pass to an
+ instrumentator instance. See [here](#creating-new-metrics) to learn how more.
+- Don't use this package at all and just use the source code as inspiration on
+ how to instrument your FastAPI.
+
+## Table of Contents
+
+
+
+- [Disclaimer](#disclaimer)
+- [Features](#features)
+- [Advanced Usage](#advanced-usage)
+ - [Creating the Instrumentator](#creating-the-instrumentator)
+ - [Adding metrics](#adding-metrics)
+ - [Creating new metrics](#creating-new-metrics)
+ - [Perform instrumentation](#perform-instrumentation)
+ - [Specify namespace and subsystem](#specify-namespace-and-subsystem)
+ - [Exposing endpoint](#exposing-endpoint)
+- [Contributing](#contributing)
+- [Licensing](#licensing)
+
+
+
+## Disclaimer
+
+Not made for generic Prometheus instrumentation in Python. Use the Prometheus
+client library for that. This packages uses it as well.
+
+All the generic middleware and instrumentation code comes with a cost in
+performance that can become noticeable.
+
+## Features
+
+Beyond the fast track, this instrumentator is **highly configurable** and it is
+very easy to customize and adapt to your specific use case. Here is a list of
+some of these options you may opt-in to:
+
+- Regex patterns to ignore certain routes.
+- Completely ignore untemplated routes.
+- Control instrumentation and exposition with an env var.
+- Rounding of latencies to a certain decimal number.
+- Renaming of labels and the metric.
+- Metrics endpoint can compress data with gzip.
+- Opt-in metric to monitor the number of requests in progress.
+
+It also features a **modular approach to metrics** that should instrument all
+FastAPI endpoints. You can either choose from a set of already existing metrics
+or create your own. And every metric function by itself can be configured as
+well.
+
+## Advanced Usage
+
+This chapter contains an example on the advanced usage of the Prometheus FastAPI
+Instrumentator to showcase most of it's features.
+
+### Creating the Instrumentator
+
+We start by creating an instance of the Instrumentator. Notice the additional
+`metrics` import. This will come in handy later.
+
+```python
+from prometheus_fastapi_instrumentator import Instrumentator, metrics
+
+instrumentator = Instrumentator(
+ should_group_status_codes=False,
+ should_ignore_untemplated=True,
+ should_respect_env_var=True,
+ should_instrument_requests_inprogress=True,
+ excluded_handlers=[".*admin.*", "/metrics"],
+ env_var_name="ENABLE_METRICS",
+ inprogress_name="inprogress",
+ inprogress_labels=True,
+ custom_labels={"service": "example-label"}
+)
+```
+
+Unlike in the fast track example, now the instrumentation and exposition will
+only take place if the environment variable `ENABLE_METRICS` is `true` at
+run-time. This can be helpful in larger deployments with multiple services
+depending on the same base FastAPI.
+
+### Adding metrics
+
+Let's say we also want to instrument the size of requests and responses. For
+this we use the `add()` method. This method does nothing more than taking a
+function and adding it to a list. Then during run-time every time FastAPI
+handles a request all functions in this list will be called while giving them a
+single argument that stores useful information like the request and response
+objects. If no `add()` at all is used, the default metric gets added in the
+background. This is what happens in the fast track example.
+
+All instrumentation functions are stored as closures in the `metrics` module.
+
+Closures come in handy here because it allows us to configure the functions
+within.
+
+```python
+instrumentator.add(metrics.latency(buckets=(1, 2, 3,)))
+```
+
+This simply adds the metric you also get in the fast track example with a
+modified buckets argument. But we would also like to record the size of all
+requests and responses.
+
+```python
+instrumentator.add(
+ metrics.request_size(
+ should_include_handler=True,
+ should_include_method=False,
+ should_include_status=True,
+ metric_namespace="a",
+ metric_subsystem="b",
+ custom_labels={"service": "example-label"}
+ )
+).add(
+ metrics.response_size(
+ should_include_handler=True,
+ should_include_method=False,
+ should_include_status=True,
+ metric_namespace="namespace",
+ metric_subsystem="subsystem",
+ custom_labels={"service": "example-label"}
+ )
+)
+```
+
+You can add as many metrics you like to the instrumentator.
+
+### Creating new metrics
+
+As already mentioned, it is possible to create custom functions to pass on to
+`add()`. This is also how the default metrics are implemented.
+
+The basic idea is that the instrumentator creates an `info` object that contains
+everything necessary for instrumentation based on the configuration of the
+instrumentator. This includes the raw request and response objects but also the
+modified handler, grouped status code and duration. Next, all registered
+instrumentation functions are called. They get `info` as their single argument.
+
+Let's say we want to count the number of times a certain language has been
+requested.
+
+```python
+from typing import Callable
+from prometheus_fastapi_instrumentator.metrics import Info
+from prometheus_client import Counter
+
+def http_requested_languages_total() -> Callable[[Info], None]:
+ METRIC = Counter(
+ "http_requested_languages_total",
+ "Number of times a certain language has been requested.",
+ labelnames=("langs",)
+ )
+
+ def instrumentation(info: Info) -> None:
+ langs = set()
+ lang_str = info.request.headers["Accept-Language"]
+ for element in lang_str.split(","):
+ element = element.split(";")[0].strip().lower()
+ langs.add(element)
+ for language in langs:
+ METRIC.labels(language).inc()
+
+ return instrumentation
+```
+
+The function `http_requested_languages_total` is used for persistent elements
+that are stored between all instrumentation executions (for example the metric
+instance itself). Next comes the closure. This function must adhere to the shown
+interface. It will always get an `Info` object that contains the request,
+response and a few other modified informations. For example the (grouped) status
+code or the handler. Finally, the closure is returned.
+
+**Important:** The response object inside `info` can either be the response
+object or `None`. In addition, errors thrown in the handler are not caught by
+the instrumentator. I recommend to check the documentation and/or the source
+code before creating your own metrics.
+
+To use it, we hand over the closure to the instrumentator object.
+
+```python
+instrumentator.add(http_requested_languages_total())
+```
+
+### Perform instrumentation
+
+Up to this point, the FastAPI has not been touched at all. Everything has been
+stored in the `instrumentator` only. To actually register the instrumentation
+with FastAPI, the `instrument()` method has to be called.
+
+```python
+instrumentator.instrument(app)
+```
+
+Notice that this will do nothing if `should_respect_env_var` has been set during
+construction of the instrumentator object and the respective env var is not
+found.
+
+### Specify namespace and subsystem
+
+You can specify the namespace and subsystem of the metrics by passing them in
+the instrument method.
+
+```python
+from prometheus_fastapi_instrumentator import Instrumentator
+
+@app.on_event("startup")
+async def startup():
+ Instrumentator().instrument(app, metric_namespace='myproject', metric_subsystem='myservice').expose(app)
+```
+
+Then your metrics will contain the namespace and subsystem in the metric name.
+
+```sh
+# TYPE myproject_myservice_http_request_duration_highr_seconds histogram
+myproject_myservice_http_request_duration_highr_seconds_bucket{le="0.01"} 0.0
+```
+
+### Exposing endpoint
+
+To expose an endpoint for the metrics either follow
+[Prometheus Python Client](https://github.com/prometheus/client_python) and add
+the endpoint manually to the FastAPI or serve it on a separate server. You can
+also use the included `expose` method. It will add an endpoint to the given
+FastAPI. With `should_gzip` you can instruct the endpoint to compress the data
+as long as the client accepts gzip encoding. Prometheus for example does by
+default. Beware that network bandwith is often cheaper than CPU cycles.
+
+```python
+instrumentator.expose(app, include_in_schema=False, should_gzip=True)
+```
+
+Notice that this will to nothing if `should_respect_env_var` has been set during
+construction of the instrumentator object and the respective env var is not
+found.
+
+## Contributing
+
+Please refer to [`CONTRIBUTING.md`](CONTRIBUTING).
+
+Consult [`DEVELOPMENT.md`](DEVELOPMENT.md) for guidance regarding development.
+
+Read [`RELEASE.md`](RELEASE.md) for details about the release process.
+
+## Licensing
+
+The default license for this project is the
+[ISC License](https://choosealicense.com/licenses/isc). A permissive license
+functionally equivalent to the BSD 2-Clause and MIT licenses, removing some
+language that is no longer necessary. See [`LICENSE`](LICENSE) for the license
+text.
+
+The [BSD 3-Clause License](https://choosealicense.com/licenses/bsd-3-clause) is
+used as the license for the
+[`routing`](src/prometheus_fastapi_instrumentator/routing.py) module. This is
+due to it containing code from
+[elastic/apm-agent-python](https://github.com/elastic/apm-agent-python). BSD
+3-Clause is a permissive license similar to the BSD 2-Clause License, but with a
+3rd clause that prohibits others from using the name of the copyright holder or
+its contributors to promote derived products without written consent. The
+license text is included in the module itself.
+
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..2e6fae6b07520529c6fac8182d194d2c9b67ab88
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/RECORD
@@ -0,0 +1,16 @@
+prometheus_fastapi_instrumentator-7.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+prometheus_fastapi_instrumentator-7.1.0.dist-info/LICENSE,sha256=1Bb46zX6e7vYSh8YDT_6oXB-XpP6E2AyHdQtnXY9Cfw,762
+prometheus_fastapi_instrumentator-7.1.0.dist-info/METADATA,sha256=fDP9dUvP1jvg0v_NAfUztFIDpk2J99LeOD5TWuv2nC4,13279
+prometheus_fastapi_instrumentator-7.1.0.dist-info/RECORD,,
+prometheus_fastapi_instrumentator-7.1.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
+prometheus_fastapi_instrumentator/__init__.py,sha256=41QGBLtG6FAmH41NhhEgeLP3L0UtocwCyWpqa1zcsYg,134
+prometheus_fastapi_instrumentator/__pycache__/__init__.cpython-310.pyc,,
+prometheus_fastapi_instrumentator/__pycache__/instrumentation.cpython-310.pyc,,
+prometheus_fastapi_instrumentator/__pycache__/metrics.cpython-310.pyc,,
+prometheus_fastapi_instrumentator/__pycache__/middleware.cpython-310.pyc,,
+prometheus_fastapi_instrumentator/__pycache__/routing.cpython-310.pyc,,
+prometheus_fastapi_instrumentator/instrumentation.py,sha256=ZZlvPfEvIhzi0PVbxEWo3AXjNcZe56EjxkNHYl-422A,13750
+prometheus_fastapi_instrumentator/metrics.py,sha256=zKaXwd4GWyp4uQJ27oEpFzRLL5vzUI6QugpynCaCswQ,29802
+prometheus_fastapi_instrumentator/middleware.py,sha256=jv25kg1mZAzQovHtODKtHwgy7pAUTLqm7khvaeUrgJo,9606
+prometheus_fastapi_instrumentator/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+prometheus_fastapi_instrumentator/routing.py,sha256=uQ0I9gHF7IIkVjBmfAy8Ax8A3wOChLTmH0aUXRgshfs,4028
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..cafd7e15ace76facf4f1bcec42710b31e59c1ae3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator-7.1.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: poetry-core 2.0.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__init__.py b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4595768815830da4ea305ba0a76598a5dd130305
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__init__.py
@@ -0,0 +1,5 @@
+from .instrumentation import PrometheusFastApiInstrumentator
+
+__version__ = "7.1.0"
+
+Instrumentator = PrometheusFastApiInstrumentator
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c8e09f3880d65d7c248c0817ce49dd157c46f20
Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/instrumentation.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/instrumentation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a585d1237dbef8c4608e95da0bc5a308d15f4e3b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/instrumentation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/metrics.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/metrics.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b8c27dee175f491505976bebbfb63934111d9a6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/metrics.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/middleware.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/middleware.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84a9db1f4b69816c069e7686ab505be0209e5eda
Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/middleware.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/routing.cpython-310.pyc b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/routing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5769644f470f7186620162a94612fde5e7fab246
Binary files /dev/null and b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/__pycache__/routing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/instrumentation.py b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/instrumentation.py
new file mode 100644
index 0000000000000000000000000000000000000000..13cdadcc6d298fe41e6638aa46d02ab9f8c48f1a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/instrumentation.py
@@ -0,0 +1,344 @@
+import asyncio
+import gzip
+import importlib.util
+import os
+import re
+import warnings
+from enum import Enum
+from typing import Any, Awaitable, Callable, List, Optional, Sequence, Union, cast
+
+from prometheus_client import (
+ CONTENT_TYPE_LATEST,
+ REGISTRY,
+ CollectorRegistry,
+ generate_latest,
+ multiprocess,
+)
+from starlette.applications import Starlette
+from starlette.requests import Request
+from starlette.responses import Response
+
+from prometheus_fastapi_instrumentator import metrics
+from prometheus_fastapi_instrumentator.middleware import (
+ PrometheusInstrumentatorMiddleware,
+)
+
+
+class PrometheusFastApiInstrumentator:
+ def __init__(
+ self,
+ should_group_status_codes: bool = True,
+ should_ignore_untemplated: bool = False,
+ should_group_untemplated: bool = True,
+ should_round_latency_decimals: bool = False,
+ should_respect_env_var: bool = False,
+ should_instrument_requests_inprogress: bool = False,
+ should_exclude_streaming_duration: bool = False,
+ excluded_handlers: List[str] = [],
+ body_handlers: List[str] = [],
+ round_latency_decimals: int = 4,
+ env_var_name: str = "ENABLE_METRICS",
+ inprogress_name: str = "http_requests_inprogress",
+ inprogress_labels: bool = False,
+ registry: Union[CollectorRegistry, None] = None,
+ ) -> None:
+ """Create a Prometheus FastAPI (and Starlette) Instrumentator.
+
+ Args:
+ should_group_status_codes (bool): Should status codes be grouped into
+ `2xx`, `3xx` and so on? Defaults to `True`.
+
+ should_ignore_untemplated (bool): Should requests without a matching
+ template be ignored? Defaults to `False`. This means that by
+ default a request like `curl -X GET localhost:80/doesnotexist`
+ will be ignored.
+
+ should_group_untemplated (bool): Should requests without a matching
+ template be grouped to handler `none`? Defaults to `True`.
+
+ should_round_latency_decimals: Should recorded latencies be
+ rounded to a certain number of decimals?
+
+ should_respect_env_var (bool): Should the instrumentator only work - for
+ example the methods `instrument()` and `expose()` - if a
+ certain environment variable is set to `true`? Usecase: A base
+ FastAPI app that is used by multiple distinct apps. The apps
+ only have to set the variable to be instrumented. Defaults to
+ `False`.
+
+ should_instrument_requests_inprogress (bool): Enables a gauge that shows
+ the inprogress requests. See also the related args starting
+ with `inprogress`. Defaults to `False`.
+
+ should_exclude_streaming_duration: Should the streaming duration be
+ excluded? Only relevant if default metrics are used. Defaults
+ to `False`.
+
+ excluded_handlers (List[str]): List of strings that will be compiled
+ to regex patterns. All matches will be skipped and not
+ instrumented. Defaults to `[]`.
+
+ body_handlers (List[str]): List of strings that will be compiled
+ to regex patterns to match handlers for the middleware to
+ pass through response bodies to instrumentations. So only
+ relevant for instrumentations that access `info.response.body`.
+ Note that this has a noticeable negative impact on performance
+ with responses larger than a few MBs. Defaults to `[]`.
+
+ round_latency_decimals (int): Number of decimals latencies should be
+ rounded to. Ignored unless `should_round_latency_decimals` is
+ `True`. Defaults to `4`.
+
+ env_var_name (str): Any valid os environment variable name that will
+ be checked for existence before instrumentation. Ignored unless
+ `should_respect_env_var` is `True`. Defaults to `"ENABLE_METRICS"`.
+
+ inprogress_name (str): Name of the gauge. Defaults to
+ `http_requests_inprogress`. Ignored unless
+ `should_instrument_requests_inprogress` is `True`.
+
+ inprogress_labels (bool): Should labels `method` and `handler` be
+ part of the inprogress label? Ignored unless
+ `should_instrument_requests_inprogress` is `True`. Defaults to `False`.
+
+ registry (CollectorRegistry): A custom Prometheus registry to use. If not
+ provided, the default `REGISTRY` will be used. This can be useful if
+ you need to run multiple apps at the same time, with their own
+ registries, for example during testing.
+
+ Raises:
+ ValueError: If `PROMETHEUS_MULTIPROC_DIR` env var is found but
+ doesn't point to a valid directory.
+ """
+
+ self.should_group_status_codes = should_group_status_codes
+ self.should_ignore_untemplated = should_ignore_untemplated
+ self.should_group_untemplated = should_group_untemplated
+ self.should_round_latency_decimals = should_round_latency_decimals
+ self.should_respect_env_var = should_respect_env_var
+ self.should_instrument_requests_inprogress = should_instrument_requests_inprogress
+ self.should_exclude_streaming_duration = should_exclude_streaming_duration
+
+ self.round_latency_decimals = round_latency_decimals
+ self.env_var_name = env_var_name
+ self.inprogress_name = inprogress_name
+ self.inprogress_labels = inprogress_labels
+
+ self.excluded_handlers = [re.compile(path) for path in excluded_handlers]
+ self.body_handlers = [re.compile(path) for path in body_handlers]
+
+ self.instrumentations: List[Callable[[metrics.Info], None]] = []
+ self.async_instrumentations: List[Callable[[metrics.Info], Awaitable[None]]] = []
+
+ if (
+ "prometheus_multiproc_dir" in os.environ
+ and "PROMETHEUS_MULTIPROC_DIR" not in os.environ
+ ):
+ os.environ["PROMETHEUS_MULTIPROC_DIR"] = os.environ[
+ "prometheus_multiproc_dir"
+ ]
+ warnings.warn(
+ "prometheus_multiproc_dir variable has been deprecated in favor of the upper case naming PROMETHEUS_MULTIPROC_DIR",
+ DeprecationWarning,
+ )
+
+ if registry:
+ self.registry = registry
+ else:
+ self.registry = REGISTRY
+
+ if "PROMETHEUS_MULTIPROC_DIR" in os.environ:
+ pmd = os.environ["PROMETHEUS_MULTIPROC_DIR"]
+ if not os.path.isdir(pmd):
+ raise ValueError(
+ f"Env var PROMETHEUS_MULTIPROC_DIR='{pmd}' not a directory."
+ )
+
+ def instrument(
+ self,
+ app: Starlette,
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_only_respect_2xx_for_highr: bool = False,
+ latency_highr_buckets: Sequence[Union[float, str]] = (
+ 0.01,
+ 0.025,
+ 0.05,
+ 0.075,
+ 0.1,
+ 0.25,
+ 0.5,
+ 0.75,
+ 1,
+ 1.5,
+ 2,
+ 2.5,
+ 3,
+ 3.5,
+ 4,
+ 4.5,
+ 5,
+ 7.5,
+ 10,
+ 30,
+ 60,
+ ),
+ latency_lowr_buckets: Sequence[Union[float, str]] = (0.1, 0.5, 1),
+ ) -> "PrometheusFastApiInstrumentator":
+ """Performs the instrumentation by adding middleware.
+
+ The middleware iterates through all `instrumentations` and executes them.
+
+ Args:
+ app: Starlette app instance. Note that every FastAPI app is a
+ Starlette app.
+
+ Raises:
+ e: Only raised if app itself throws an exception.
+
+ Returns:
+ self: Instrumentator. Builder Pattern.
+ """
+
+ if self.should_respect_env_var and not self._should_instrumentate():
+ return self
+
+ app.add_middleware(
+ PrometheusInstrumentatorMiddleware,
+ should_group_status_codes=self.should_group_status_codes,
+ should_ignore_untemplated=self.should_ignore_untemplated,
+ should_group_untemplated=self.should_group_untemplated,
+ should_round_latency_decimals=self.should_round_latency_decimals,
+ should_respect_env_var=self.should_respect_env_var,
+ should_instrument_requests_inprogress=self.should_instrument_requests_inprogress,
+ should_exclude_streaming_duration=self.should_exclude_streaming_duration,
+ round_latency_decimals=self.round_latency_decimals,
+ env_var_name=self.env_var_name,
+ inprogress_name=self.inprogress_name,
+ inprogress_labels=self.inprogress_labels,
+ instrumentations=self.instrumentations,
+ async_instrumentations=self.async_instrumentations,
+ excluded_handlers=self.excluded_handlers,
+ body_handlers=self.body_handlers,
+ metric_namespace=metric_namespace,
+ metric_subsystem=metric_subsystem,
+ should_only_respect_2xx_for_highr=should_only_respect_2xx_for_highr,
+ latency_highr_buckets=latency_highr_buckets,
+ latency_lowr_buckets=latency_lowr_buckets,
+ registry=self.registry,
+ )
+ return self
+
+ def expose(
+ self,
+ app: Starlette,
+ should_gzip: bool = False,
+ endpoint: str = "/metrics",
+ include_in_schema: bool = True,
+ tags: Optional[List[Union[str, Enum]]] = None,
+ **kwargs: Any,
+ ) -> "PrometheusFastApiInstrumentator":
+ """Exposes endpoint for metrics.
+
+ Args:
+ app: App instance. Endpoint will be added to this app. This can be
+ a Starlette app or a FastAPI app. If it is a Starlette app, `tags`
+ `kwargs` will be ignored.
+
+ should_gzip: Should the endpoint return compressed data? It will
+ also check for `gzip` in the `Accept-Encoding` header.
+ Compression consumes more CPU cycles. In most cases it's best
+ to just leave this option off since network bandwidth is usually
+ cheaper than CPU cycles. Defaults to `False`.
+
+ endpoint: Endpoint on which metrics should be exposed.
+
+ include_in_schema: Should the endpoint show up in the documentation?
+
+ tags (List[str], optional): If you manage your routes with tags.
+ Defaults to None. Only passed to FastAPI app.
+
+ kwargs: Will be passed to app. Only passed to FastAPI app.
+
+ Returns:
+ self: Instrumentator. Builder Pattern.
+ """
+
+ if self.should_respect_env_var and not self._should_instrumentate():
+ return self
+
+ def metrics(request: Request) -> Response:
+ """Endpoint that serves Prometheus metrics."""
+
+ ephemeral_registry = self.registry
+ if "PROMETHEUS_MULTIPROC_DIR" in os.environ:
+ ephemeral_registry = CollectorRegistry()
+ multiprocess.MultiProcessCollector(ephemeral_registry)
+
+ if should_gzip and "gzip" in request.headers.get("Accept-Encoding", ""):
+ resp = Response(
+ content=gzip.compress(generate_latest(ephemeral_registry))
+ )
+ resp.headers["Content-Type"] = CONTENT_TYPE_LATEST
+ resp.headers["Content-Encoding"] = "gzip"
+ else:
+ resp = Response(content=generate_latest(ephemeral_registry))
+ resp.headers["Content-Type"] = CONTENT_TYPE_LATEST
+
+ return resp
+
+ route_configured = False
+ if importlib.util.find_spec("fastapi"):
+ from fastapi import FastAPI
+
+ if isinstance(app, FastAPI):
+ fastapi_app: FastAPI = app
+ fastapi_app.get(
+ endpoint, include_in_schema=include_in_schema, tags=tags, **kwargs
+ )(metrics)
+ route_configured = True
+ if not route_configured:
+ app.add_route(
+ path=endpoint, route=metrics, include_in_schema=include_in_schema
+ )
+
+ return self
+
+ def add(
+ self,
+ *instrumentation_function: Optional[
+ Callable[[metrics.Info], Union[None, Awaitable[None]]]
+ ],
+ ) -> "PrometheusFastApiInstrumentator":
+ """Adds function to list of instrumentations.
+
+ Args:
+ instrumentation_function: Function
+ that will be executed during every request handler call (if
+ not excluded). See above for detailed information on the
+ interface of the function.
+
+ Returns:
+ self: Instrumentator. Builder Pattern.
+ """
+
+ for func in instrumentation_function:
+ if func:
+ if asyncio.iscoroutinefunction(func):
+ self.async_instrumentations.append(
+ cast(
+ Callable[[metrics.Info], Awaitable[None]],
+ func,
+ )
+ )
+ else:
+ self.instrumentations.append(
+ cast(Callable[[metrics.Info], None], func)
+ )
+
+ return self
+
+ def _should_instrumentate(self) -> bool:
+ """Checks if instrumentation should be performed based on env var."""
+
+ return os.getenv(self.env_var_name, "False").lower() in ["true", "1"]
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/metrics.py b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..04be27061ebc4c685b94c2c439cc8f561c7983b9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/metrics.py
@@ -0,0 +1,828 @@
+"""
+This module contains ready-to-use functions that can be passed on to the
+instrumentator instance with the `add()` method. The idea behind this is to
+make the types of metrics you want to export with the instrumentation easily
+customizable. The default instrumentation function `default` can also be found
+here.
+
+If your requirements are really specific or very extensive it makes sense to
+create your own instrumentation function instead of combining several functions
+from this module.
+"""
+
+from typing import Callable, List, Optional, Sequence, Tuple, Union
+
+from prometheus_client import REGISTRY, CollectorRegistry, Counter, Histogram, Summary
+from starlette.requests import Request
+from starlette.responses import Response
+
+
+# ------------------------------------------------------------------------------
+class Info:
+ def __init__(
+ self,
+ request: Request,
+ response: Optional[Response],
+ method: str,
+ modified_handler: str,
+ modified_status: str,
+ modified_duration: float,
+ modified_duration_without_streaming: float = 0.0,
+ ):
+ """Creates Info object that is used for instrumentation functions.
+
+ This is the only argument that is passed to the instrumentation functions.
+
+ Args:
+ request (Request): Python Requests request object.
+ response (Response or None): Python Requests response object.
+ method (str): Unmodified method of the request.
+ modified_handler (str): Handler representation after processing by
+ instrumentator. For example grouped to `none` if not templated.
+ modified_status (str): Status code representation after processing
+ by instrumentator. For example grouping into `2xx`, `3xx` and so on.
+ modified_duration (float): Latency representation after processing
+ by instrumentator. For example rounding of decimals. Seconds.
+ modified_duration_without_streaming (float): Latency between request arrival and response starts (i.e. first chunk duration).
+ Excluding the streaming duration. Defaults to 0.
+ """
+
+ self.request = request
+ self.response = response
+ self.method = method
+ self.modified_handler = modified_handler
+ self.modified_status = modified_status
+ self.modified_duration = modified_duration
+ self.modified_duration_without_streaming = modified_duration_without_streaming
+
+
+def _build_label_attribute_names(
+ should_include_handler: bool,
+ should_include_method: bool,
+ should_include_status: bool,
+) -> Tuple[List[str], List[str]]:
+ """Builds up tuple with to be used label and attribute names.
+
+ Args:
+ should_include_handler (bool): Should the `handler` label be part of the metric?
+ should_include_method (bool): Should the `method` label be part of the metric?
+ should_include_status (bool): Should the `status` label be part of the metric?
+
+ Returns:
+ Tuple with two list elements.
+
+ First element: List with all labels to be used.
+ Second element: List with all attribute names to be used from the
+ `Info` object. Done like this to enable dynamic on / off of labels.
+ """
+
+ label_names = []
+ info_attribute_names = []
+
+ if should_include_handler:
+ label_names.append("handler")
+ info_attribute_names.append("modified_handler")
+
+ if should_include_method:
+ label_names.append("method")
+ info_attribute_names.append("method")
+
+ if should_include_status:
+ label_names.append("status")
+ info_attribute_names.append("modified_status")
+
+ return label_names, info_attribute_names
+
+
+def _is_duplicated_time_series(error: ValueError) -> bool:
+ return any(
+ map(
+ error.args[0].__contains__,
+ [
+ "Duplicated timeseries in CollectorRegistry:",
+ "Duplicated time series in CollectorRegistry:",
+ ],
+ )
+ )
+
+
+# ------------------------------------------------------------------------------
+# Instrumentation / Metrics functions
+
+
+def latency(
+ metric_name: str = "http_request_duration_seconds",
+ metric_doc: str = "Duration of HTTP requests in seconds",
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_include_handler: bool = True,
+ should_include_method: bool = True,
+ should_include_status: bool = True,
+ should_exclude_streaming_duration: bool = False,
+ buckets: Sequence[Union[float, str]] = Histogram.DEFAULT_BUCKETS,
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Default metric for the Prometheus Starlette Instrumentator.
+
+ Args:
+ metric_name (str, optional): Name of the metric to be created. Must be
+ unique. Defaults to "http_request_duration_seconds".
+
+ metric_doc (str, optional): Documentation of the metric. Defaults to
+ "Duration of HTTP requests in seconds".
+
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+
+ should_include_handler: Should the `handler` label be part of the
+ metric? Defaults to `True`.
+
+ should_include_method: Should the `method` label be part of the
+ metric? Defaults to `True`.
+
+ should_include_status: Should the `status` label be part of the
+ metric? Defaults to `True`.
+
+ should_exclude_streaming_duration: Should the streaming duration be
+ excluded? Defaults to `False`.
+
+ buckets: Buckets for the histogram. Defaults to Prometheus default.
+ Defaults to default buckets from Prometheus client library.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+
+ if buckets[-1] != float("inf"):
+ buckets = [*buckets, float("inf")]
+
+ label_names, info_attribute_names = _build_label_attribute_names(
+ should_include_handler, should_include_method, should_include_status
+ )
+ for key in custom_labels:
+ label_names.append(key)
+ info_attribute_names.append(key)
+
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ try:
+ if label_names:
+ METRIC = Histogram(
+ metric_name,
+ metric_doc,
+ labelnames=label_names,
+ buckets=buckets,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+ else:
+ METRIC = Histogram(
+ metric_name,
+ metric_doc,
+ buckets=buckets,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ duration = info.modified_duration
+ if should_exclude_streaming_duration:
+ duration = info.modified_duration_without_streaming
+ else:
+ duration = info.modified_duration
+
+ if label_names:
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in info_attribute_names
+ ]
+
+ METRIC.labels(*label_values).observe(duration)
+ else:
+ METRIC.observe(duration)
+
+ return instrumentation
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
+
+
+def request_size(
+ metric_name: str = "http_request_size_bytes",
+ metric_doc: str = "Content bytes of requests.",
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_include_handler: bool = True,
+ should_include_method: bool = True,
+ should_include_status: bool = True,
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Record the content length of incoming requests.
+
+ If content length is missing 0 will be assumed.
+
+ Args:
+ metric_name (str, optional): Name of the metric to be created. Must be
+ unique. Defaults to "http_request_size_bytes".
+ metric_doc (str, optional): Documentation of the metric. Defaults to
+ "Content bytes of requests.".
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+ should_include_handler: Should the `handler` label be part of the
+ metric? Defaults to `True`.
+ should_include_method: Should the `method` label be part of the
+ metric? Defaults to `True`.
+ should_include_status: Should the `status` label be part of the metric?
+ Defaults to `True`.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+
+ label_names, info_attribute_names = _build_label_attribute_names(
+ should_include_handler, should_include_method, should_include_status
+ )
+ for key in custom_labels:
+ label_names.append(key)
+ info_attribute_names.append(key)
+
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ try:
+ if label_names:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ labelnames=label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+ else:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ content_length = info.request.headers.get("Content-Length", 0)
+ if label_names:
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in info_attribute_names
+ ]
+
+ METRIC.labels(*label_values).observe(int(content_length))
+ else:
+ METRIC.observe(int(content_length))
+
+ return instrumentation
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
+
+
+def response_size(
+ metric_name: str = "http_response_size_bytes",
+ metric_doc: str = "Content bytes of responses.",
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_include_handler: bool = True,
+ should_include_method: bool = True,
+ should_include_status: bool = True,
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Record the content length of outgoing responses.
+
+ If content length is missing 0 will be assumed.
+
+ Args:
+ metric_name (str, optional): Name of the metric to be created. Must be
+ unique. Defaults to "http_response_size_bytes".
+
+ metric_doc (str, optional): Documentation of the metric. Defaults to
+ "Content bytes of responses.".
+
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+
+ should_include_handler: Should the `handler` label be part of the
+ metric? Defaults to `True`.
+
+ should_include_method: Should the `method` label be part of the metric?
+ Defaults to `True`.
+
+ should_include_status: Should the `status` label be part of the metric?
+ Defaults to `True`.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+
+ label_names, info_attribute_names = _build_label_attribute_names(
+ should_include_handler, should_include_method, should_include_status
+ )
+ for key in custom_labels:
+ label_names.append(key)
+ info_attribute_names.append(key)
+
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ try:
+ if label_names:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ labelnames=label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+ else:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ if info.response and hasattr(info.response, "headers"):
+ content_length = info.response.headers.get("Content-Length", 0)
+ else:
+ content_length = 0
+
+ if label_names:
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in info_attribute_names
+ ]
+
+ METRIC.labels(*label_values).observe(int(content_length))
+ else:
+ METRIC.observe(int(content_length))
+
+ return instrumentation
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
+
+
+def combined_size(
+ metric_name: str = "http_combined_size_bytes",
+ metric_doc: str = "Content bytes of requests and responses.",
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_include_handler: bool = True,
+ should_include_method: bool = True,
+ should_include_status: bool = True,
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Record the combined content length of requests and responses.
+
+ If content length is missing 0 will be assumed.
+
+ Args:
+ metric_name (str, optional): Name of the metric to be created. Must be
+ unique. Defaults to "http_combined_size_bytes".
+
+ metric_doc (str, optional): Documentation of the metric. Defaults to
+ "Content bytes of requests and responses.".
+
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+
+ should_include_handler: Should the `handler` label be part of the
+ metric? Defaults to `True`.
+
+ should_include_method: Should the `method` label be part of the metric?
+ Defaults to `True`.
+
+ should_include_status: Should the `status` label be part of the metric?
+ Defaults to `True`.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+
+ label_names, info_attribute_names = _build_label_attribute_names(
+ should_include_handler, should_include_method, should_include_status
+ )
+ for key in custom_labels:
+ label_names.append(key)
+ info_attribute_names.append(key)
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ try:
+ if label_names:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ labelnames=label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+ else:
+ METRIC = Summary(
+ metric_name,
+ metric_doc,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ request_cl = info.request.headers.get("Content-Length", 0)
+
+ if info.response and hasattr(info.response, "headers"):
+ response_cl = info.response.headers.get("Content-Length", 0)
+ else:
+ response_cl = 0
+
+ content_length = int(request_cl) + int(response_cl)
+
+ if label_names:
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in info_attribute_names
+ ]
+
+ METRIC.labels(*label_values).observe(int(content_length))
+ else:
+ METRIC.observe(int(content_length))
+
+ return instrumentation
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
+
+
+def requests(
+ metric_name: str = "http_requests_total",
+ metric_doc: str = "Total number of requests by method, status and handler.",
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_include_handler: bool = True,
+ should_include_method: bool = True,
+ should_include_status: bool = True,
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Record the number of requests.
+
+ Args:
+ metric_name (str, optional): Name of the metric to be created. Must
+ be unique. Defaults to "http_requests_total".
+
+ metric_doc (str, optional): Documentation of the metric. Defaults to
+ "Total number of requests by method, status and handler.".
+
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+
+ should_include_handler (bool, optional): Should the `handler` label
+ be part of the metric? Defaults to `True`.
+
+ should_include_method (bool, optional): Should the `method` label be
+ part of the metric? Defaults to `True`.
+
+ should_include_status (bool, optional): Should the `status` label be
+ part of the metric? Defaults to `True`.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+
+ label_names, info_attribute_names = _build_label_attribute_names(
+ should_include_handler, should_include_method, should_include_status
+ )
+ for key in custom_labels:
+ label_names.append(key)
+ info_attribute_names.append(key)
+
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ try:
+ if label_names:
+ METRIC = Counter(
+ metric_name,
+ metric_doc,
+ labelnames=label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+ else:
+ METRIC = Counter(
+ metric_name,
+ metric_doc,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ if label_names:
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in info_attribute_names
+ ]
+
+ METRIC.labels(*label_values).inc()
+ else:
+ METRIC.inc()
+
+ return instrumentation
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
+
+
+def _map_label_name_value(label_name: tuple) -> list[str]:
+ attribute_names = []
+ mapping = {
+ "handler": "modified_handler",
+ "status": "modified_status",
+ "duration": "modified_duration",
+ }
+ for item in label_name:
+ if item in mapping:
+ attribute_names.append(mapping[item])
+ else:
+ attribute_names.append(item)
+ return attribute_names
+
+
+def default(
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_only_respect_2xx_for_highr: bool = False,
+ should_exclude_streaming_duration: bool = False,
+ latency_highr_buckets: Sequence[Union[float, str]] = (
+ 0.01,
+ 0.025,
+ 0.05,
+ 0.075,
+ 0.1,
+ 0.25,
+ 0.5,
+ 0.75,
+ 1,
+ 1.5,
+ 2,
+ 2.5,
+ 3,
+ 3.5,
+ 4,
+ 4.5,
+ 5,
+ 7.5,
+ 10,
+ 30,
+ 60,
+ ),
+ latency_lowr_buckets: Sequence[Union[float, str]] = (0.1, 0.5, 1),
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+) -> Optional[Callable[[Info], None]]:
+ """Contains multiple metrics to cover multiple things.
+
+ Combines several metrics into a single function. Also more efficient than
+ multiple separate instrumentation functions that do more or less the same.
+
+ You get the following:
+
+ * `http_requests_total` (`handler`, `status`, `method`): Total number of
+ requests by handler, status and method.
+ * `http_request_size_bytes` (`handler`): Total number of incoming
+ content length bytes by handler.
+ * `http_response_size_bytes` (`handler`): Total number of outgoing
+ content length bytes by handler.
+ * `http_request_duration_highr_seconds` (no labels): High number of buckets
+ leading to more accurate calculation of percentiles.
+ * `http_request_duration_seconds` (`handler`, `method`):
+ Kepp the bucket count very low. Only put in SLIs.
+
+ Args:
+ metric_namespace (str, optional): Namespace of all metrics in this
+ metric function. Defaults to "".
+
+ metric_subsystem (str, optional): Subsystem of all metrics in this
+ metric function. Defaults to "".
+
+ should_only_respect_2xx_for_highr (str, optional): Should the metric
+ `http_request_duration_highr_seconds` only include latencies of
+ requests / responses that have a status code starting with `2`?
+ Defaults to `False`.
+
+ should_exclude_streaming_duration: Should the streaming duration be
+ excluded? Defaults to `False`.
+
+ latency_highr_buckets (tuple[float], optional): Buckets tuple for high
+ res histogram. Can be large because no labels are used. Defaults to
+ (0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5,
+ 3, 3.5, 4, 4.5, 5, 7.5, 10, 30, 60).
+
+ latency_lowr_buckets (tuple[float], optional): Buckets tuple for low
+ res histogram. Should be very small as all possible labels are
+ included. Defaults to `(0.1, 0.5, 1)`.
+
+ Returns:
+ Function that takes a single parameter `Info`.
+ """
+ if latency_highr_buckets[-1] != float("inf"):
+ latency_highr_buckets = [*latency_highr_buckets, float("inf")]
+
+ if latency_lowr_buckets[-1] != float("inf"):
+ latency_lowr_buckets = [*latency_lowr_buckets, float("inf")]
+
+ # Starlette will call app.build_middleware_stack() with every new middleware
+ # added, which will call all this again, which will make the registry
+ # complain about duplicated metrics.
+ #
+ # The Python Prometheus client currently doesn't seem to have a way to
+ # verify if adding a metric will cause errors or not, so the only way to
+ # handle it seems to be with this try block.
+ additional_label_names = tuple([key for key in custom_labels])
+ try:
+ total_label_names = (
+ "method",
+ "status",
+ "handler",
+ )
+ TOTAL = Counter(
+ name="http_requests_total",
+ documentation="Total number of requests by method, status and handler.",
+ labelnames=total_label_names + additional_label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ in_size_names = ("handler",)
+ IN_SIZE = Summary(
+ name="http_request_size_bytes",
+ documentation=(
+ "Content length of incoming requests by handler. "
+ "Only value of header is respected. Otherwise ignored. "
+ "No percentile calculated. "
+ ),
+ labelnames=in_size_names + additional_label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ out_size_names = ("handler",)
+ OUT_SIZE = Summary(
+ name="http_response_size_bytes",
+ documentation=(
+ "Content length of outgoing responses by handler. "
+ "Only value of header is respected. Otherwise ignored. "
+ "No percentile calculated. "
+ ),
+ labelnames=out_size_names + additional_label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ LATENCY_HIGHR = Histogram(
+ name="http_request_duration_highr_seconds",
+ documentation=(
+ "Latency with many buckets but no API specific labels. "
+ "Made for more accurate percentile calculations. "
+ ),
+ buckets=latency_highr_buckets,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ latency_lower_names = (
+ "method",
+ "handler",
+ )
+ LATENCY_LOWR = Histogram(
+ name="http_request_duration_seconds",
+ documentation=(
+ "Latency with only few buckets by handler. "
+ "Made to be only used if aggregation by handler is important. "
+ ),
+ buckets=latency_lowr_buckets,
+ labelnames=latency_lower_names + additional_label_names,
+ namespace=metric_namespace,
+ subsystem=metric_subsystem,
+ registry=registry,
+ )
+
+ def instrumentation(info: Info) -> None:
+ duration = info.modified_duration
+ if should_exclude_streaming_duration:
+ duration = info.modified_duration_without_streaming
+ else:
+ duration = info.modified_duration
+
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in _map_label_name_value(total_label_names)
+ ] + list(custom_labels.values())
+ TOTAL.labels(*label_values).inc()
+
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in _map_label_name_value(in_size_names)
+ ] + list(custom_labels.values())
+ IN_SIZE.labels(*label_values).observe(
+ int(info.request.headers.get("Content-Length", 0))
+ )
+
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in _map_label_name_value(out_size_names)
+ ] + list(custom_labels.values())
+ if info.response and hasattr(info.response, "headers"):
+ OUT_SIZE.labels(*label_values).observe(
+ int(info.response.headers.get("Content-Length", 0))
+ )
+ else:
+ OUT_SIZE.labels(*label_values).observe(0)
+
+ if not should_only_respect_2xx_for_highr or info.modified_status.startswith(
+ "2"
+ ):
+ LATENCY_HIGHR.observe(duration)
+
+ label_values = [
+ getattr(info, attribute_name)
+ for attribute_name in _map_label_name_value(latency_lower_names)
+ ] + list(custom_labels.values())
+ LATENCY_LOWR.labels(*label_values).observe(duration)
+
+ return instrumentation
+
+ except ValueError as e:
+ if not _is_duplicated_time_series(e):
+ raise e
+
+ return None
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/middleware.py b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce4257bda0681261ede1256b98ed2418e5c0b5eb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/middleware.py
@@ -0,0 +1,261 @@
+from __future__ import annotations
+
+import asyncio
+import re
+from http import HTTPStatus
+from timeit import default_timer
+from typing import Awaitable, Callable, Optional, Sequence, Tuple, Union
+
+from prometheus_client import REGISTRY, CollectorRegistry, Gauge
+from starlette.applications import Starlette
+from starlette.datastructures import Headers
+from starlette.requests import Request
+from starlette.responses import Response
+from starlette.types import Message, Receive, Scope, Send
+
+from prometheus_fastapi_instrumentator import metrics, routing
+
+
+class PrometheusInstrumentatorMiddleware:
+ def __init__(
+ self,
+ app: Starlette,
+ *,
+ should_group_status_codes: bool = True,
+ should_ignore_untemplated: bool = False,
+ should_group_untemplated: bool = True,
+ should_round_latency_decimals: bool = False,
+ should_respect_env_var: bool = False,
+ should_instrument_requests_inprogress: bool = False,
+ should_exclude_streaming_duration: bool = False,
+ excluded_handlers: Sequence[str] = (),
+ body_handlers: Sequence[str] = (),
+ round_latency_decimals: int = 4,
+ env_var_name: str = "ENABLE_METRICS",
+ inprogress_name: str = "http_requests_inprogress",
+ inprogress_labels: bool = False,
+ instrumentations: Sequence[Callable[[metrics.Info], None]] = (),
+ async_instrumentations: Sequence[Callable[[metrics.Info], Awaitable[None]]] = (),
+ metric_namespace: str = "",
+ metric_subsystem: str = "",
+ should_only_respect_2xx_for_highr: bool = False,
+ latency_highr_buckets: Sequence[Union[float, str]] = (
+ 0.01,
+ 0.025,
+ 0.05,
+ 0.075,
+ 0.1,
+ 0.25,
+ 0.5,
+ 0.75,
+ 1,
+ 1.5,
+ 2,
+ 2.5,
+ 3,
+ 3.5,
+ 4,
+ 4.5,
+ 5,
+ 7.5,
+ 10,
+ 30,
+ 60,
+ ),
+ latency_lowr_buckets: Sequence[Union[float, str]] = (0.1, 0.5, 1),
+ registry: CollectorRegistry = REGISTRY,
+ custom_labels: dict = {},
+ ) -> None:
+ self.app = app
+
+ self.should_group_status_codes = should_group_status_codes
+ self.should_ignore_untemplated = should_ignore_untemplated
+ self.should_group_untemplated = should_group_untemplated
+ self.should_round_latency_decimals = should_round_latency_decimals
+ self.should_respect_env_var = should_respect_env_var
+ self.should_instrument_requests_inprogress = should_instrument_requests_inprogress
+
+ self.round_latency_decimals = round_latency_decimals
+ self.env_var_name = env_var_name
+ self.inprogress_name = inprogress_name
+ self.inprogress_labels = inprogress_labels
+ self.registry = registry
+ self.custom_labels = custom_labels
+
+ self.excluded_handlers = [re.compile(path) for path in excluded_handlers]
+ self.body_handlers = [re.compile(path) for path in body_handlers]
+
+ if instrumentations:
+ self.instrumentations = instrumentations
+ else:
+ default_instrumentation = metrics.default(
+ metric_namespace=metric_namespace,
+ metric_subsystem=metric_subsystem,
+ should_only_respect_2xx_for_highr=should_only_respect_2xx_for_highr,
+ should_exclude_streaming_duration=should_exclude_streaming_duration,
+ latency_highr_buckets=latency_highr_buckets,
+ latency_lowr_buckets=latency_lowr_buckets,
+ registry=self.registry,
+ custom_labels=custom_labels,
+ )
+ if default_instrumentation:
+ self.instrumentations = [default_instrumentation]
+ else:
+ self.instrumentations = []
+
+ self.async_instrumentations = async_instrumentations
+
+ self.inprogress: Optional[Gauge] = None
+ if self.should_instrument_requests_inprogress:
+ labels = (
+ (
+ "method",
+ "handler",
+ )
+ if self.inprogress_labels
+ else ()
+ )
+ self.inprogress = Gauge(
+ name=self.inprogress_name,
+ documentation="Number of HTTP requests in progress.",
+ labelnames=labels,
+ multiprocess_mode="livesum",
+ )
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http":
+ return await self.app(scope, receive, send)
+
+ request = Request(scope)
+ start_time = default_timer()
+
+ handler, is_templated = self._get_handler(request)
+ is_excluded = self._is_handler_excluded(handler, is_templated)
+ handler = (
+ "none" if not is_templated and self.should_group_untemplated else handler
+ )
+
+ if not is_excluded and self.inprogress:
+ if self.inprogress_labels:
+ inprogress = self.inprogress.labels(request.method, handler)
+ else:
+ inprogress = self.inprogress
+ inprogress.inc()
+
+ status_code = 500
+ headers = []
+ body = b""
+ response_start_time = None
+
+ # Message body collected for handlers matching body_handlers patterns.
+ if any(pattern.search(handler) for pattern in self.body_handlers):
+
+ async def send_wrapper(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ nonlocal status_code, headers, response_start_time
+ headers = message["headers"]
+ status_code = message["status"]
+ response_start_time = default_timer()
+ elif message["type"] == "http.response.body" and message["body"]:
+ nonlocal body
+ body += message["body"]
+ await send(message)
+
+ else:
+
+ async def send_wrapper(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ nonlocal status_code, headers, response_start_time
+ headers = message["headers"]
+ status_code = message["status"]
+ response_start_time = default_timer()
+ await send(message)
+
+ try:
+ await self.app(scope, receive, send_wrapper)
+ except Exception as exc:
+ raise exc
+ finally:
+ status = (
+ str(status_code.value)
+ if isinstance(status_code, HTTPStatus)
+ else str(status_code)
+ )
+
+ if not is_excluded:
+ duration = max(default_timer() - start_time, 0.0)
+ duration_without_streaming = 0.0
+
+ if response_start_time:
+ duration_without_streaming = max(
+ response_start_time - start_time, 0.0
+ )
+
+ if self.should_instrument_requests_inprogress:
+ inprogress.dec()
+
+ if self.should_round_latency_decimals:
+ duration = round(duration, self.round_latency_decimals)
+ duration_without_streaming = round(
+ duration_without_streaming, self.round_latency_decimals
+ )
+
+ if self.should_group_status_codes:
+ status = status[0] + "xx"
+
+ response = Response(
+ content=body, headers=Headers(raw=headers), status_code=status_code
+ )
+
+ info = metrics.Info(
+ request=request,
+ response=response,
+ method=request.method,
+ modified_handler=handler,
+ modified_status=status,
+ modified_duration=duration,
+ modified_duration_without_streaming=duration_without_streaming,
+ )
+
+ for instrumentation in self.instrumentations:
+ instrumentation(info)
+
+ await asyncio.gather(
+ *[
+ instrumentation(info)
+ for instrumentation in self.async_instrumentations
+ ]
+ )
+
+ def _get_handler(self, request: Request) -> Tuple[str, bool]:
+ """Extracts either template or (if no template) path.
+
+ Args:
+ request (Request): Python Requests request object.
+
+ Returns:
+ Tuple[str, bool]: Tuple with two elements. First element is either
+ template or if no template the path. Second element tells you
+ if the path is templated or not.
+ """
+ route_name = routing.get_route_name(request)
+ return route_name or request.url.path, True if route_name else False
+
+ def _is_handler_excluded(self, handler: str, is_templated: bool) -> bool:
+ """Determines if the handler should be ignored.
+
+ Args:
+ handler (str): Handler that handles the request.
+ is_templated (bool): Shows if the request is templated.
+
+ Returns:
+ bool: `True` if excluded, `False` if not.
+ """
+
+ if not is_templated and self.should_ignore_untemplated:
+ return True
+
+ if any(pattern.search(handler) for pattern in self.excluded_handlers):
+ return True
+
+ return False
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/py.typed b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/routing.py b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/routing.py
new file mode 100644
index 0000000000000000000000000000000000000000..43d964f1bb14b3fd63e97a0445cad6b3aab85acc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/routing.py
@@ -0,0 +1,93 @@
+# BSD 3-Clause License
+#
+# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details
+# Copyright (c) 2019, Elasticsearch BV
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# * Neither the name of the copyright holder nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+
+"""Helper module for routing.
+
+The two functions in this module are licensed under the BSD 3-Clause License
+instead of the ISC License like the rest of the project. Therefore the code
+is contained in a dedicated module.
+
+Based on code from [elastic/apm-agent-python](https://github.com/elastic/apm-agent-python/blob/527f62c0c50842f94ef90fda079853372539319a/elasticapm/contrib/starlette/__init__.py).
+"""
+
+from typing import List, Optional
+
+from starlette.requests import HTTPConnection
+from starlette.routing import Match, Mount, Route
+from starlette.types import Scope
+
+
+def _get_route_name(
+ scope: Scope, routes: List[Route], route_name: Optional[str] = None
+) -> Optional[str]:
+ """Gets route name for given scope taking mounts into account."""
+
+ for route in routes:
+ match, child_scope = route.matches(scope)
+ if match == Match.FULL:
+ route_name = route.path
+ child_scope = {**scope, **child_scope}
+ if isinstance(route, Mount) and route.routes:
+ child_route_name = _get_route_name(child_scope, route.routes, route_name)
+ if child_route_name is None:
+ route_name = None
+ else:
+ route_name += child_route_name
+ return route_name
+ elif match == Match.PARTIAL and route_name is None:
+ route_name = route.path
+ return None
+
+
+def get_route_name(request: HTTPConnection) -> Optional[str]:
+ """Gets route name for given request taking mounts into account."""
+
+ app = request.app
+ scope = request.scope
+ routes = app.routes
+ route_name = _get_route_name(scope, routes)
+
+ # Starlette magically redirects requests if the path matches a route name
+ # with a trailing slash appended or removed. To not spam the transaction
+ # names list, we do the same here and put these redirects all in the
+ # same "redirect trailing slashes" transaction name.
+ if not route_name and app.router.redirect_slashes and scope["path"] != "/":
+ redirect_scope = dict(scope)
+ if scope["path"].endswith("/"):
+ redirect_scope["path"] = scope["path"][:-1]
+ trim = True
+ else:
+ redirect_scope["path"] = scope["path"] + "/"
+ trim = False
+
+ route_name = _get_route_name(redirect_scope, routes)
+ if route_name is not None:
+ route_name = route_name + "/" if trim else route_name[:-1]
+ return route_name
diff --git a/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/LICENSE b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..19b305b00060a774a9180fb916c14b49edb2008f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/LICENSE
@@ -0,0 +1,32 @@
+Copyright 2008 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Code generated by the Protocol Buffer compiler is owned by the owner
+of the input file used when generating it. This code is not
+standalone and requires a support library to be linked with it. This
+support library is itself covered by the above license.
diff --git a/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/METADATA b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..0b35c1ca2567d5423a9b157018a4d20e79bb66bf
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/METADATA
@@ -0,0 +1,16 @@
+Metadata-Version: 2.1
+Name: protobuf
+Author: protobuf@googlegroups.com
+Author-email: protobuf@googlegroups.com
+Home-page: https://developers.google.com/protocol-buffers/
+License: 3-Clause BSD License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Requires-Python: >=3.8
+Version: 4.25.8
+
+UNKNOWN
diff --git a/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/RECORD b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..0eba8fc7d5f900ca4db2e1258852feca21a96051
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/RECORD
@@ -0,0 +1,102 @@
+google/_upb/_message.abi3.so,sha256=Ryvmfg1i0lxZRgC-vPoBfMGaD_SCvhp6IgQ0G3Qk3hU,371296
+google/protobuf/__init__.py,sha256=eh8AXg2dZqZ7w5vdT83SBceYLyuHx5EgeUi2d9y-dNw,346
+google/protobuf/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/__pycache__/any_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/api_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/descriptor.cpython-310.pyc,,
+google/protobuf/__pycache__/descriptor_database.cpython-310.pyc,,
+google/protobuf/__pycache__/descriptor_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/descriptor_pool.cpython-310.pyc,,
+google/protobuf/__pycache__/duration_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/empty_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/field_mask_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/json_format.cpython-310.pyc,,
+google/protobuf/__pycache__/message.cpython-310.pyc,,
+google/protobuf/__pycache__/message_factory.cpython-310.pyc,,
+google/protobuf/__pycache__/proto_builder.cpython-310.pyc,,
+google/protobuf/__pycache__/reflection.cpython-310.pyc,,
+google/protobuf/__pycache__/service.cpython-310.pyc,,
+google/protobuf/__pycache__/service_reflection.cpython-310.pyc,,
+google/protobuf/__pycache__/source_context_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/struct_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/symbol_database.cpython-310.pyc,,
+google/protobuf/__pycache__/text_encoding.cpython-310.pyc,,
+google/protobuf/__pycache__/text_format.cpython-310.pyc,,
+google/protobuf/__pycache__/timestamp_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/type_pb2.cpython-310.pyc,,
+google/protobuf/__pycache__/unknown_fields.cpython-310.pyc,,
+google/protobuf/__pycache__/wrappers_pb2.cpython-310.pyc,,
+google/protobuf/any_pb2.py,sha256=w6QxYHuLmTqTfMPks3nnHBvgWL4ZsQiFXXxF9geg9vg,1477
+google/protobuf/api_pb2.py,sha256=erM62QZzXoGPr0dMEZdUCEI4vUEJPADnd-buO2vELvY,2897
+google/protobuf/compiler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+google/protobuf/compiler/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/compiler/__pycache__/plugin_pb2.cpython-310.pyc,,
+google/protobuf/compiler/plugin_pb2.py,sha256=NgNSGjLNkljuDC2-ZXzU5jVb3yUAU_pBFu8CvBf54Sg,3407
+google/protobuf/descriptor.py,sha256=951A9b3Mi_hGNhgaBdRvUVZvJRxV-Oa_8mS0naWD1bM,47604
+google/protobuf/descriptor_database.py,sha256=GDiSu-vBZBZ-L1YHQXSTsbsJMRNY-20icb6pj3ER8E8,5444
+google/protobuf/descriptor_pb2.py,sha256=3OPhqPGp_CAADPz_Fu9idk13imaYpMcLSYUXsFG5C60,174338
+google/protobuf/descriptor_pool.py,sha256=xaiIrIHMgMxxU1rGijdUkX3-kAwy1wYHRm7w2ZaRxdQ,45758
+google/protobuf/duration_pb2.py,sha256=TO4Yfe7Hro3dFSIWWhfYdZe0jLgh9VG_c4tv8SwH0o8,1552
+google/protobuf/empty_pb2.py,sha256=cD1fxhRl8k2t5_E_WQ9IJa_HpFMEh84LJVaBTPKCakk,1419
+google/protobuf/field_mask_pb2.py,sha256=7L2nxz8hqpIaMyX7U9Xz4DGqh_yEZv_Xr0q-rHkJtak,1510
+google/protobuf/internal/__init__.py,sha256=8d_k1ksNWIuqPDEEEtOjgC3Xx8kAXD2-04R7mxJlSbs,272
+google/protobuf/internal/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/_parameterized.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/api_implementation.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/builder.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/containers.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/decoder.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/encoder.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/extension_dict.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/field_mask.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/message_listener.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/python_message.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/testing_refleaks.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/type_checkers.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/well_known_types.cpython-310.pyc,,
+google/protobuf/internal/__pycache__/wire_format.cpython-310.pyc,,
+google/protobuf/internal/_parameterized.py,sha256=_LLIH2kmUrI1hZfUlIF8OBcBbbQXgRnm39uB9TpzaHU,14073
+google/protobuf/internal/api_implementation.py,sha256=iWReqnDw2SI3Q3qGJWr_SRXcnbpn1f1BH3CXkmu9R8U,4751
+google/protobuf/internal/builder.py,sha256=TaNII7ojWiJplPwkeLZ8T2l8MBC3F92WKspwzFFy2UA,4082
+google/protobuf/internal/containers.py,sha256=HbkZx7miXGw6tWURYfmxximKbRBwjvkxYB0e7dffIqU,22031
+google/protobuf/internal/decoder.py,sha256=fh08eGirU8f9Mhtx6JkKk2rysoszFSTXu5uoXyFgWXM,39417
+google/protobuf/internal/encoder.py,sha256=Vujp3bU10dLBasUnRaGZKD-ZTLq7zEGA8wKh7mVLR-g,27297
+google/protobuf/internal/enum_type_wrapper.py,sha256=9eWhuHhgzX3piT33HMx9y8_Y1KTudyGhIoDpPP00-Cg,3462
+google/protobuf/internal/extension_dict.py,sha256=7bT-5iqa_qw4wkk3QNtCPzGlfPU2h9FDyc5TjF2wiTo,7225
+google/protobuf/internal/field_mask.py,sha256=Ek2eDU8mY1Shj-V2wRmOggXummBv_brbL3XOEVFR6c0,10416
+google/protobuf/internal/message_listener.py,sha256=uh8viU_MvWdDe4Kl14CromKVFAzBMPlMzFZ4vew_UJc,2008
+google/protobuf/internal/python_message.py,sha256=HU7yrw7kELfsGI5QS8PBq3tp1zQO1RNLxlXy3341a_Q,57282
+google/protobuf/internal/testing_refleaks.py,sha256=Pp-e8isZv-IwZDOzPaLo9WujUXj_XghNrbV-rHswvL4,4080
+google/protobuf/internal/type_checkers.py,sha256=YFJUluNszW97kzWpwm7WMlFmBdSeuQQtVtVTnH-6vx0,15450
+google/protobuf/internal/well_known_types.py,sha256=aMyNWTz6JopfEWDECU5kwqRPuAt5qfBUzQx9HloO_8w,19236
+google/protobuf/internal/wire_format.py,sha256=EbAXZdb23iCObCZxNgaMx8-VRF2UjgyPrBCTtV10Rx8,7087
+google/protobuf/json_format.py,sha256=AXle74NhSGr0op8N-OrOXoL0LQ_ChsLkxiSbwxQFozk,34889
+google/protobuf/message.py,sha256=vrTuKXeg649pduamTlvu4C6TFjyJuSyQ4MpWRrtlJ1M,12959
+google/protobuf/message_factory.py,sha256=POODzg8xr7J2YL7WgtWeJy23KAfjqz2meUzmmIUDD6E,8271
+google/protobuf/proto_builder.py,sha256=pGU2L_pPEYkylZkrvHMCUH2PFWvc9wI-awwT7F5i740,4203
+google/protobuf/pyext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+google/protobuf/pyext/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/pyext/__pycache__/cpp_message.cpython-310.pyc,,
+google/protobuf/pyext/cpp_message.py,sha256=tRWXzttU9M_Mm8ivTmxp1WIaAmg78mSuiR4Ow3rv5Zw,1704
+google/protobuf/reflection.py,sha256=VLTQNavswAooyl3kIbFLeB8iyytAjuHRANby0e4oWjU,2413
+google/protobuf/service.py,sha256=C63Fw-OMGXowsTmajKk0lQ6S3ODx8cGWCn2Fm-xlkTw,7787
+google/protobuf/service_reflection.py,sha256=WHElGnPgywDtn3X8xKVNsZZOCgJOTzgpAyTd-rmCKGU,10058
+google/protobuf/source_context_pb2.py,sha256=nG5UYyjkh53UE3MylpJIo0-kwd87JKiMd3Ue1IbUS0o,1532
+google/protobuf/struct_pb2.py,sha256=tWW8Lmh9NbUkCsdPXoWCazBXi24iMO7CpInJsnzrOS0,2803
+google/protobuf/symbol_database.py,sha256=ruKrtrkuxmFe7uzbJGMgOD7D6Qs2g6jFIRC3aS9NNvU,6709
+google/protobuf/testdata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+google/protobuf/testdata/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/text_encoding.py,sha256=bC9K7fzuy0eMwFTankA4CIv9bBMRLiht9lZaSJGC_l0,3342
+google/protobuf/text_format.py,sha256=j-oi5pw27mAExpeDebHAB2ftUfU9U4csdlZ1lLmwNk0,62611
+google/protobuf/timestamp_pb2.py,sha256=XqS_r4Gsjf9U5C75feWOiy6-IOQGLeC7y9pS-_ABFBI,1561
+google/protobuf/type_pb2.py,sha256=xrNdnPga5S3_f6jWDPYCEGjfeJ0LIm11jQHpMILpHf8,5189
+google/protobuf/unknown_fields.py,sha256=RVMDxyiZcObbb40dMK-xXCAvc5pkyLNSL1y2qzPAUbA,3127
+google/protobuf/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+google/protobuf/util/__pycache__/__init__.cpython-310.pyc,,
+google/protobuf/wrappers_pb2.py,sha256=2GmYImLrSwsBfeD0z_C2vkYu7U_hmY47erzy_aO73LI,2784
+protobuf-4.25.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+protobuf-4.25.8.dist-info/LICENSE,sha256=bl4RcySv2UTc9n82zzKYQ7wakiKajNm7Vz16gxMP6n0,1732
+protobuf-4.25.8.dist-info/METADATA,sha256=rNsIwJcGihK8IFNXdx50pJdADSkdoZJC5RJp3OgQ_Bs,541
+protobuf-4.25.8.dist-info/RECORD,,
+protobuf-4.25.8.dist-info/WHEEL,sha256=4VIymEBu-Fq15Rt-htNgEW3w9shnYEMphHPsRXlq35o,110
diff --git a/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/WHEEL b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..9f99cc94b0db1c8f6fcedfd060542385c9ac916e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/protobuf-4.25.8.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: bazel-wheelmaker 1.0
+Root-Is-Purelib: false
+Tag: cp37-abi3-manylinux2014_x86_64
diff --git a/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/LICENSE.txt b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..89ea6cc185fd429822d98f0ef25f2348728e9917
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/LICENSE.txt
@@ -0,0 +1,458 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
diff --git a/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..adfc287edadf6de67175e9b8f340ca7eef55532b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/METADATA
@@ -0,0 +1,409 @@
+Metadata-Version: 2.1
+Name: pycountry
+Version: 24.6.1
+Summary: ISO country, subdivision, language, currency and script definitions and their translations
+Home-page: https://github.com/flyingcircusio/pycountry
+License: LGPL-2.1-only
+Keywords: country,subdivision,language,currency,iso,3166,639,4217,15924,3166-1,3166-2,3166-3
+Author: Christian Theune
+Author-email: ct@flyingcircus.io
+Maintainer: Nate Schimmoller
+Maintainer-email: nschimmo@gmail.com
+Requires-Python: >=3.8
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: License :: OSI Approved
+Classifier: License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Software Development :: Internationalization
+Classifier: Topic :: Software Development :: Localization
+Requires-Dist: importlib-resources (>5.12.0) ; python_version < "3.9"
+Project-URL: Repository, https://github.com/flyingcircusio/pycountry
+Description-Content-Type: text/x-rst
+
+###########
+ pycountry
+###########
+
+..
+ image:g: https://travis-ci.org/flyingcircusio/pycountry.svg?branch=master
+
+pycountry provides the ISO databases for the standards:
+
+- `639-3 `_ Languages
+- `3166 `_ Codes for
+ representation of names of countries and their subdivisions
+- `3166-1 `_ Countries
+- `3166-3 `_ Deleted
+ countries
+- `3166-2 `_ Subdivisions of
+ countries
+- `4217 `_ Currencies
+- `15924 `_ Scripts
+
+The package includes a copy from Debian's `pkg-isocodes
+`_ and makes the data
+accessible through a Python API.
+
+Translation files for the various strings are included as well.
+
+********************
+ Data update policy
+********************
+
+No changes to the data will be accepted into pycountry. This is a pure
+wrapper around the ISO standard using the ``pkg-isocodes`` database from
+Debian *as is*. If you need changes to the political situation in the
+world, please talk to the ISO or Debian people, not me.
+
+******************************
+ Donations / Monetary Support
+******************************
+
+This is a small project that I maintain in my personal time. I am not
+interested in personal financial gain. However, if you would like to
+support the project then I would love if you would donate to `Feminist
+Frequency `_ instead. Also, let
+the world know you did so, so that others can follow your path.
+
+***************
+ Contributions
+***************
+
+The code lives in a `git repository on GitHub
+`_, and issues must be reported
+in there as well.
+
+************************
+ Countries (ISO 3166-1)
+************************
+
+Countries are accessible through a database object that is already
+configured upon import of pycountry and works as an iterable:
+
+.. code:: pycon
+
+ >>> import pycountry
+ >>> len(pycountry.countries)
+ 249
+ >>> list(pycountry.countries)[0]
+ Country(alpha_2='AF', alpha_3='AFG', name='Afghanistan', numeric='004', official_name='Islamic Republic of Afghanistan')
+
+Specific countries can be looked up by their various codes and provide
+the information included in the standard as attributes:
+
+.. code:: pycon
+
+ >>> germany = pycountry.countries.get(alpha_2='DE')
+ >>> germany
+ Country(alpha_2='DE', alpha_3='DEU', name='Germany', numeric='276', official_name='Federal Republic of Germany')
+ >>> germany.alpha_2
+ 'DE'
+ >>> germany.alpha_3
+ 'DEU'
+ >>> germany.numeric
+ '276'
+ >>> germany.name
+ 'Germany'
+ >>> germany.official_name
+ 'Federal Republic of Germany'
+
+There's also a "fuzzy" search to help people discover "proper" countries
+for names that might only actually be subdivisions. The fuzziness also
+includes normalizing unicode accents. There's also a bit of
+prioritization included to prefer matches on country names before
+subdivision names and have countries with more matches be listed before
+ones with fewer matches:
+
+.. code:: pycon
+
+ >>> pycountry.countries.search_fuzzy('England')
+ [Country(alpha_2='GB', alpha_3='GBR', name='United Kingdom', numeric='826', official_name='United Kingdom of Great Britain and Northern Ireland')]
+
+ >>> pycountry.countries.search_fuzzy('Cote')
+ [Country(alpha_2='CI', alpha_3='CIV', name="Côte d'Ivoire", numeric='384', official_name="Republic of Côte d'Ivoire"),
+ Country(alpha_2='FR', alpha_3='FRA', name='France', numeric='250', official_name='French Republic'),
+ Country(alpha_2='HN', alpha_3='HND', name='Honduras', numeric='340', official_name='Republic of Honduras')]
+
+Attributes for the country class can be accessed using the
+``__getattr__`` method. If the requested attribute is a key for the
+country class, it will return the corresponding value. In the special
+cases of missing 'common_name' or 'official_name' attributes,
+``__getattr__`` will return 'name'. Here are some examples:
+
+.. code:: pycon
+
+ >>> aland = pycountry.countries.get(alpha_2='AX')
+
+ >>> print(aland)
+ Country(alpha_2='AX', alpha_3='ALA', flag='🇦🇽', name='Åland Islands', numeric='248')
+
+ >>> aland.common_name
+ UserWarning: Country's common_name not found. Country name provided instead.
+ warnings.warn(warning_message, UserWarning)
+ 'Åland Islands'
+
+ >>> aland.official_name
+ Country's official_name not found. Country name provided instead.
+ warnings.warn(warning_message, UserWarning)
+ 'Åland Islands'
+
+ >>> aland.flag
+ '🇦🇽'
+
+ >>> aland.foo # Raises AttributeError
+
+*********************************
+ Historic Countries (ISO 3166-3)
+*********************************
+
+The ``historic_countries`` database contains former countries that have
+been removed from the standard and are now included in ISO 3166-3,
+excluding existing ones:
+
+.. code:: pycon
+
+ >>> ussr = pycountry.historic_countries.get(alpha_3='SUN')
+ >>> ussr
+ Country(alpha_3='SUN', alpha_4='SUHH', withdrawal_date='1992-08-30', name='USSR, Union of Soviet Socialist Republics', numeric='810')
+ >>> ussr.alpha_4
+ 'SUHH'
+ >>> ussr.alpha_3
+ 'SUN'
+ >>> ussr.name
+ 'USSR, Union of Soviet Socialist Republics'
+ >>> ussr.withdrawal_date
+ '1992-08-30'
+
+***********************************
+ Country subdivisions (ISO 3166-2)
+***********************************
+
+The country subdivisions are a little more complex than the countries
+itself because they provide a nested and typed structure.
+
+All subdivisons can be accessed directly:
+
+.. code:: pycon
+
+ >>> len(pycountry.subdivisions)
+ 4847
+ >>> list(pycountry.subdivisions)[0]
+ Subdivision(code='AD-07', country_code='AD', name='Andorra la Vella', parent_code=None, type='Parish')
+
+Subdivisions can be accessed using their unique code. The resulting
+object will provide at least their code, name and type:
+
+.. code:: pycon
+
+ >>> de_st = pycountry.subdivisions.get(code='DE-ST')
+ >>> de_st.code
+ 'DE-ST'
+ >>> de_st.name
+ 'Sachsen-Anhalt'
+ >>> de_st.type
+ 'State'
+ >>> de_st.country
+ Country(alpha_2='DE', alpha_3='DEU', name='Germany', numeric='276', official_name='Federal Republic of Germany')
+
+Some subdivisions specify another subdivision as a parent:
+
+.. code:: pycon
+
+ >>> al_br = pycountry.subdivisions.get(code='AL-BU')
+ >>> al_br.code
+ 'AL-BU'
+ >>> al_br.name
+ 'Bulqiz\xeb'
+ >>> al_br.type
+ 'District'
+ >>> al_br.parent_code
+ 'AL-09'
+ >>> al_br.parent
+ Subdivision(code='AL-09', country_code='AL', name='Dib\xebr', parent_code=None, type='County')
+ >>> al_br.parent.name
+ 'Dib\xebr'
+
+The divisions of a single country can be queried using the country_code
+index:
+
+.. code:: pycon
+
+ >>> len(pycountry.subdivisions.get(country_code='DE'))
+ 16
+
+ >>> len(pycountry.subdivisions.get(country_code='US'))
+ 57
+
+Similar to countries, the ``search_fuzzy`` method has been implemented
+for subdivisions to facilitate finding relevant subdivision entries.
+This method includes unicode normalization for accents and prioritizes
+matches on subdivision names. The search algorithm is designed to return
+more relevant matches first:
+
+This method is especially useful for cases where the exact name or code
+of the subdivision is not known.
+
+.. code:: pycon
+
+ >>> pycountry.subdivisions.search_fuzzy('York')
+ [Subdivision(code='GB-YOR', country_code='GB', name='York', parent='GB-ENG', parent_code='GB-GB-ENG', type='Unitary authority')
+ Subdivision(code='GB-ERY', country_code='GB', name='East Riding of Yorkshire', parent='GB-ENG', parent_code='GB-GB-ENG', type='Unitary authority')
+ Subdivision(code='GB-NYK', country_code='GB', name='North Yorkshire', parent='GB-ENG', parent_code='GB-GB-ENG', type='Two-tier county')
+ Subdivision(code='US-NY', country_code='US', name='New York', parent_code=None, type='State')]
+
+*********************
+ Scripts (ISO 15924)
+*********************
+
+Scripts are available from a database similar to the countries:
+
+.. code:: pycon
+
+ >>> len(pycountry.scripts)
+ 169
+ >>> list(pycountry.scripts)[0]
+ Script(alpha_4='Afak', name='Afaka', numeric='439')
+
+ >>> latin = pycountry.scripts.get(name='Latin')
+ >>> latin
+ Script(alpha_4='Latn', name='Latin', numeric='215')
+ >>> latin.alpha4
+ 'Latn'
+ >>> latin.name
+ 'Latin'
+ >>> latin.numeric
+ '215'
+
+***********************
+ Currencies (ISO 4217)
+***********************
+
+The currencies database is, again, similar to the ones before:
+
+.. code:: pycon
+
+ >>> len(pycountry.currencies)
+ 182
+ >>> list(pycountry.currencies)[0]
+ Currency(alpha_3='AED', name='UAE Dirham', numeric='784')
+ >>> argentine_peso = pycountry.currencies.get(alpha_3='ARS')
+ >>> argentine_peso
+ Currency(alpha_3='ARS', name='Argentine Peso', numeric='032')
+ >>> argentine_peso.alpha_3
+ 'ARS'
+ >>> argentine_peso.name
+ 'Argentine Peso'
+ >>> argentine_peso.numeric
+ '032'
+
+***********************
+ Languages (ISO 639-3)
+***********************
+
+The languages database is similar too:
+
+.. code:: pycon
+
+ >>> len(pycountry.languages)
+ 7874
+ >>> list(pycountry.languages)[0]
+ Language(alpha_3='aaa', name='Ghotuo', scope='I', type='L')
+
+ >>> aragonese = pycountry.languages.get(alpha_2='an')
+ >>> aragonese.alpha_2
+ 'an'
+ >>> aragonese.alpha_3
+ 'arg'
+ >>> aragonese.name
+ 'Aragonese'
+
+ >>> bengali = pycountry.languages.get(alpha_2='bn')
+ >>> bengali.name
+ 'Bengali'
+ >>> bengali.common_name
+ 'Bangla'
+
+*********
+ Locales
+*********
+
+Locales are available in the ``pycountry.LOCALES_DIR`` subdirectory of
+this package. The translation domains are called ``isoXXX`` according to
+the standard they provide translations for. The directory is structured
+in a way compatible to Python's gettext module.
+
+Here is an example translating language names:
+
+.. code:: pycon
+
+ >>> import gettext
+ >>> german = gettext.translation('iso3166-1', pycountry.LOCALES_DIR,
+ ... languages=['de'])
+ >>> german.install()
+ >>> _('Germany')
+ 'Deutschland'
+
+*********
+ Lookups
+*********
+
+For each database (countries, languages, scripts, etc.), you can also
+look up entities case insensitively without knowing which key the value
+may match. For example:
+
+.. code:: pycon
+
+ >>> pycountry.countries.lookup('de')
+
+
+The search ends with the first match, which is returned.
+
+********************
+ Dict Compatibility
+********************
+
+You can cast each object type into a ``dict``:
+
+.. code:: pycon
+
+ >>> country = pycountry.countries.lookup('de')
+ >>> dict(country)
+ {'alpha_2': 'DE', 'name': 'Germany', ...}
+
+******************
+ Custom Countries
+******************
+
+While pycountry will not be adding non-ISO values to its standard
+library, you can add or remove entries at runtime to fit your needs.
+
+Add a non-ISO country:
+
+.. code:: pycon
+
+ >>> pycountry.countries.add_entry(alpha_2="XK", alpha_3="XXK", name="Kosovo", numeric="926")
+
+Remove a country from a database:
+
+.. code:: pycon
+
+ >>> pycountry.countries.remove_entry(alpha_2="XK")
+
+***************************
+ PyInstaller Compatibility
+***************************
+
+Some users have reported issues using PyCountry with PyInstaller
+guidance on how to handle the issues can be found in the `PyInstaller
+Google Group
+`_.
+
diff --git a/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..4da86efe2531ba0a693278605459fbfd73236091
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/RECORD
@@ -0,0 +1,601 @@
+pycountry-24.6.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pycountry-24.6.1.dist-info/LICENSE.txt,sha256=P6OcbhijpEEQgrZMFk3q4dj0ewOk1FMEwfCuR4Ym44I,24463
+pycountry-24.6.1.dist-info/METADATA,sha256=ovhjGjtIMMO7d-i-1ONzmA2DTYCSdjoA-PVOBm0bzT0,12984
+pycountry-24.6.1.dist-info/RECORD,,
+pycountry-24.6.1.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
+pycountry/COPYRIGHT.txt,sha256=9LAWFwZLzZ6f49ti7Jxu-NCvzDiN2ljZspNaVR15YOQ,2054
+pycountry/__init__.py,sha256=YLNhtu9WmoG-K6yDc3MwQFHlCk5o-kLiA6BfSdf65xE,10577
+pycountry/__pycache__/__init__.cpython-310.pyc,,
+pycountry/__pycache__/db.cpython-310.pyc,,
+pycountry/databases/iso15924.json,sha256=Z009yLGKO5ma9xlvd5QopGXl-wr0FNBxlX0QNIvJgX4,17097
+pycountry/databases/iso3166-1.json,sha256=8BuBK1f7qfMf9iG_M-fHVwoBlk2-tb4hZ-lN7PU4yJ8,43284
+pycountry/databases/iso3166-2.json,sha256=Td3W3F6nzH26HuKJxlnJTGHUWBPw5feXNj3ii_Po4po,498094
+pycountry/databases/iso3166-3.json,sha256=65LRzOPjUlWfYQ5g4qyyNofrHPB7I2dfsRKGOldBpvo,6193
+pycountry/databases/iso4217.json,sha256=ycN7QmMXgJpv_gZ9o6M0oxUPQklPrpGCNVevt70aQTU,16584
+pycountry/databases/iso639-3.json,sha256=ljbOUmYFOGdicUDOWtofmqiXygenUBMCwbFLjRFHzdo,874782
+pycountry/databases/iso639-5.json,sha256=EswG_z7ZXrgJF0pobLKuczFfPLFlgs9v5CZ856KtYZg,8486
+pycountry/db.py,sha256=DZOSHXrX7B9nfbUyUBUA7qUWyCxrXnSE18dlAI1hvNU,5730
+pycountry/locales/ab/LC_MESSAGES/iso3166-1.mo,sha256=k3uGEcGMyUV9r-Lb71LOqXroLQp_IhkTAhr0PD3U9e0,528
+pycountry/locales/ab/LC_MESSAGES/iso639-5.mo,sha256=5Gbou7M6kfDcvKTN-rjYaO5EhzF19peITObAKV4GBlM,371
+pycountry/locales/ace/LC_MESSAGES/iso3166-1.mo,sha256=6Vkm8uXyq25_SQj_rzs-GBpNZPd8IXKAoQ9XIfeXpFk,524
+pycountry/locales/ach/LC_MESSAGES/iso3166-1.mo,sha256=2usbjDzDqMgZazSwE-vdgc08TO7cgtvCtsoJL4fJJ34,9144
+pycountry/locales/af/LC_MESSAGES/iso3166-1.mo,sha256=4VxdeFM3YYXCgtjcd_oHRZRCtOwlIm8OSJHZ29UtVCc,22487
+pycountry/locales/af/LC_MESSAGES/iso3166-3.mo,sha256=3s548xWglPw-c-szsi2VPtStJA9YZMKN5skK3wmT4Q4,1001
+pycountry/locales/af/LC_MESSAGES/iso639-3.mo,sha256=FmEu-2iY9g700VLvruD8LVEGIuHofjxuUaSFl7OAST8,5414
+pycountry/locales/ak/LC_MESSAGES/iso3166-1.mo,sha256=HfKQMjsWhW9Ni7ac9nqeQzSrODe_IO9Yb7O5yXWxwlk,522
+pycountry/locales/am/LC_MESSAGES/iso3166-1.mo,sha256=3jsi1iJsfthdvxkmCv1VhvHOzpDeh-4GzyhCE0qTmbU,6413
+pycountry/locales/am/LC_MESSAGES/iso3166-3.mo,sha256=vyw6Cwq3SQOIWP6gDRI0eexeoydR0B3GqirUxe-t418,476
+pycountry/locales/am/LC_MESSAGES/iso639-3.mo,sha256=yF1yOdiBBo1pwOMtA8RCUfGs_rMfwV5oMUdA5p23dTg,5797
+pycountry/locales/an/LC_MESSAGES/iso3166-1.mo,sha256=l_6UPVkRZtiPLwYYTpz5vUgM52bXK0Yao39PnirHuBo,3810
+pycountry/locales/ar/LC_MESSAGES/iso15924.mo,sha256=zUUHbVE7omuduSRbiQ-T5SL5gOO2a8IbzMvGUy3FhdE,4112
+pycountry/locales/ar/LC_MESSAGES/iso3166-1.mo,sha256=qLUx_EDLoLwRssI3x6SEZxdkiXrzupYXM2AnR2gNLK8,28339
+pycountry/locales/ar/LC_MESSAGES/iso3166-3.mo,sha256=Rahaka3wBXrsvWs9uEA-sFjIF1866PG1ayEpULmMHhs,3225
+pycountry/locales/ar/LC_MESSAGES/iso4217.mo,sha256=-QMYzQARcJ7io3jZbGkGGmfNH3zYqTlzPGffRTwgk7c,8672
+pycountry/locales/ar/LC_MESSAGES/iso639-3.mo,sha256=xPkXdFG-wDN63PWutDf95H5-szO1V4xu6_2_9anOzBU,8284
+pycountry/locales/as/LC_MESSAGES/iso3166-1.mo,sha256=vHPXBAhS2ZQq_YYDOfXpU-iwW8Mw9hzR03F_XsYAViM,33554
+pycountry/locales/as/LC_MESSAGES/iso3166-3.mo,sha256=5vD8t0dokLtK1gPNKt1Olg3ZvOYKpzp0s9RSU41E_Qc,4070
+pycountry/locales/ast/LC_MESSAGES/iso15924.mo,sha256=oiGUX_ZTtunE4RLegO39k_klYJSYIt6FQved3j4UGEU,372
+pycountry/locales/ast/LC_MESSAGES/iso3166-1.mo,sha256=R_MeKZ0zClp2m9y9w9W8UlhaB2g2hASXKw4Rh_V90o8,22752
+pycountry/locales/ast/LC_MESSAGES/iso3166-2.mo,sha256=_MhjBaxHk5eg6-ntsvqEnmYxp5DD5Rt4apKOAMSjEeQ,373
+pycountry/locales/ast/LC_MESSAGES/iso3166-3.mo,sha256=rmQaVdr-XS2nXnO6abzuyU2EFEG6YEYgQFzI2ORqt_o,2670
+pycountry/locales/ast/LC_MESSAGES/iso4217.mo,sha256=KNPjXdmAfShoiU3wJvyox22mFd-N6UAobV_DmiyshZg,371
+pycountry/locales/ast/LC_MESSAGES/iso639-3.mo,sha256=YMAQ-2GWeKLqMZz8GB0lNta2Tz6rabkwQI4v1qg93-0,311331
+pycountry/locales/ast/LC_MESSAGES/iso639-5.mo,sha256=qn-We9gdhe_PEYMLPhrc3q4vAOe5Bgk2JtfotbOGMew,4029
+pycountry/locales/ay/LC_MESSAGES/iso3166-1.mo,sha256=cBggVpg-cvg496_r1P2iP8c6pXeV5tXAWHeI4MUGjS8,521
+pycountry/locales/az/LC_MESSAGES/iso3166-1.mo,sha256=YVWW1lokxjKqOJutVRom6sIwd2Kgg2_-9Dex0GUvy20,10337
+pycountry/locales/az/LC_MESSAGES/iso3166-2.mo,sha256=KOq3mDw9DYUS-rjkJuUPnx4Gy-UAOi8VNSuEi4V4lRA,3341
+pycountry/locales/az/LC_MESSAGES/iso3166-3.mo,sha256=CSPNosZvIUgoOmmqhyT0oSeV2mfloubjv1rZWB2WUMA,497
+pycountry/locales/az/LC_MESSAGES/iso639-3.mo,sha256=CjljkA8FBDD0PsX0EKqyLHqqAj-H5Swl8IfWeSQCYto,1431
+pycountry/locales/ba/LC_MESSAGES/iso3166-1.mo,sha256=V-M118MNtoP1d8Ieo28BjZUm8rNt7_hv5tIWWdeIx-g,526
+pycountry/locales/bar/LC_MESSAGES/iso3166-1.mo,sha256=ZIp9uz675vRJx3f83vGmkkz0X_BI4K1ECL2tlz4HYhg,6864
+pycountry/locales/be/LC_MESSAGES/iso15924.mo,sha256=_N0zYkRXhRxc6OY_uM0nEdTTQGkJemjPJbweseMkY-E,12701
+pycountry/locales/be/LC_MESSAGES/iso3166-1.mo,sha256=BLzhRMgKoRbCdH_-IR2ktrxoUlv7umx3i3vLhmbpMtA,30045
+pycountry/locales/be/LC_MESSAGES/iso3166-2.mo,sha256=7dvTbx2XXzaGDM77eZuOGunGghqlWF_Qr1cwR1BsQ2c,194548
+pycountry/locales/be/LC_MESSAGES/iso3166-3.mo,sha256=NY8tsH-xZAISTaPkv-sZoeSe4pS1XwLo0UevpYfPE9M,3661
+pycountry/locales/be/LC_MESSAGES/iso4217.mo,sha256=LWwT3Fk73ol8TAPhKJYvN7wC9i2FFQZFIkmnr3uhZ3M,12256
+pycountry/locales/be/LC_MESSAGES/iso639-3.mo,sha256=6n5MlHRR5j8DFbjEWxgX5_cLsvRcI-n84-tpxuYMFto,18766
+pycountry/locales/be/LC_MESSAGES/iso639-5.mo,sha256=71r8IrsY_YGNzqaX4W6IwaWRRkdg_GJXemcQlDCozRI,9437
+pycountry/locales/bg/LC_MESSAGES/iso15924.mo,sha256=ek0OdIRZK1sg51aer-aBKmTWPTvANA2j6IXDG3GbktA,2003
+pycountry/locales/bg/LC_MESSAGES/iso3166-1.mo,sha256=XiHw6_WKu_Z80bstGu7AxWA_t4Z3HxLLyd14pUIgE0Y,28945
+pycountry/locales/bg/LC_MESSAGES/iso3166-2.mo,sha256=Rfv2XakO8KebOwl5UgAW4x68txJMo0-sHruTk4F82Ck,15883
+pycountry/locales/bg/LC_MESSAGES/iso3166-3.mo,sha256=ajS_H5nLTATojKgYS-VUJHBblcGMlKy4c3xzZfIbZIU,3381
+pycountry/locales/bg/LC_MESSAGES/iso639-3.mo,sha256=K_5aQ06aBayWyvHGM7PyzKV32vYDEpI81U6cYs51vR0,24471
+pycountry/locales/bi/LC_MESSAGES/iso3166-1.mo,sha256=_VIBxp1rhKVdnoUMCJGdHw7tunzjUH_VjXYpz9soUrU,526
+pycountry/locales/bn/LC_MESSAGES/iso3166-1.mo,sha256=ashBjzxU8D7XQxzZLsuAm2D6xkeqcoxtkRacjN8T74w,35751
+pycountry/locales/bn/LC_MESSAGES/iso3166-3.mo,sha256=PUeYbYkNPrt_VO7Ex_zt51qqrI20ANBQpQTI9de2S_c,4015
+pycountry/locales/bn/LC_MESSAGES/iso4217.mo,sha256=4oYedxUp0lHxdllCSVGv7VShAeRHqxaaiLFTZtQJam8,6448
+pycountry/locales/bn/LC_MESSAGES/iso639-3.mo,sha256=TfCKcL6WYGVXojn6_r9S1wqCYUfGCzdEzgY2REioGRc,96597
+pycountry/locales/bn/LC_MESSAGES/iso639-5.mo,sha256=GDRlAiAPncL-NNs1DjcvszQ-Wk9RkO4L65zyO-H1vHY,5688
+pycountry/locales/bn_BD/LC_MESSAGES/iso15924.mo,sha256=ovwmvIRPtPMDH4T9o4efoMjZZ2odclx7JjsbBNGMl6E,14811
+pycountry/locales/bn_BD/LC_MESSAGES/iso3166-2.mo,sha256=QXTOHWYkINzQgpTWYgc9kwv7eVta683ZrVsccKC-fMI,1161
+pycountry/locales/bn_BD/LC_MESSAGES/iso639-5.mo,sha256=xXfd6IKyzFc2dJtsBSa5_0mBCRBvPz7tCcId3NjDzJ8,2772
+pycountry/locales/bn_IN/LC_MESSAGES/iso3166-1.mo,sha256=5Px391j-95rq_YCKjQgXRZ1zfZXWhjtXCHdtd4ywLNY,36015
+pycountry/locales/bn_IN/LC_MESSAGES/iso3166-3.mo,sha256=pIptGQpE8d5nuzL0jTYJLPv3JZY0gxUuCMWgdXI0TgQ,4091
+pycountry/locales/br/LC_MESSAGES/iso15924.mo,sha256=FHcA4B8HH6tW9s6V38M1RanR8vLCPwT5Uqs0xKUgm1s,6545
+pycountry/locales/br/LC_MESSAGES/iso3166-1.mo,sha256=AXx3h9JbJouvTQcKKT-gjdgd5thutVMognb3Cp36oEI,10555
+pycountry/locales/br/LC_MESSAGES/iso3166-3.mo,sha256=NDwEC3COS46PUyPxviqz3FcXPu4EMPD9mfFf0Ov4MQM,2105
+pycountry/locales/br/LC_MESSAGES/iso4217.mo,sha256=2tpB8EW0tcbLKioS1oV-QncS4Cgt8UB2Um7Y1Ird_wE,4788
+pycountry/locales/br/LC_MESSAGES/iso639-3.mo,sha256=K4JL2FdlhYYeA5JQcTpQW9sIO36BIu0JcX5eF-L_JO0,32879
+pycountry/locales/bs/LC_MESSAGES/iso3166-1.mo,sha256=jXst5_Jspv9qSo37HDE_V88j4dmOnVDLkn0KJj-2Qlc,22283
+pycountry/locales/bs/LC_MESSAGES/iso3166-2.mo,sha256=SqCsAuu_JfoyzdkKdu_h4RRIlvIEhDtKw7Gcfn3BblE,3326
+pycountry/locales/bs/LC_MESSAGES/iso3166-3.mo,sha256=vmd-r__7CfEP7lNLKO5XaTRbl74cD0gf9jXY5gHb0Ys,2593
+pycountry/locales/bs/LC_MESSAGES/iso639-3.mo,sha256=lp3LUAvixy_p_ahI8y5t4b-ZIh8jpGc0bjPMwybcW0o,2394
+pycountry/locales/byn/LC_MESSAGES/iso3166-1.mo,sha256=zmm0ZRkYUfh_6wWfm85FVzwBNaL9weTOmkUrHsJm5wo,5711
+pycountry/locales/byn/LC_MESSAGES/iso3166-3.mo,sha256=hwn6l96WEVf5gMMD0D-seBHNzNNrPRPXUcnNoQNh5A0,474
+pycountry/locales/byn/LC_MESSAGES/iso639-3.mo,sha256=U6uIgSE3nyqvmHEegh5we5qY92PQ2_TQw8vY3FHaPpY,5693
+pycountry/locales/ca/LC_MESSAGES/iso15924.mo,sha256=NLX6H4JPcYkvcS5owWmaNNRjekuyVlyILFyeQ4bQtO0,2945
+pycountry/locales/ca/LC_MESSAGES/iso3166-1.mo,sha256=xiAEFdhGYRlBPfAKHjdbMYckwJa0R9RLoyqMl7WRiTc,23927
+pycountry/locales/ca/LC_MESSAGES/iso3166-2.mo,sha256=wiuZD4uELssC58wznMnURsgBM9ViOcxsNq89sPkgbuQ,4601
+pycountry/locales/ca/LC_MESSAGES/iso3166-3.mo,sha256=rE7KKu_cHR59jP_DXCwZAe7GoAWzbqsPu7hJ3rwJ_IQ,2865
+pycountry/locales/ca/LC_MESSAGES/iso4217.mo,sha256=f8WynUdYDEdufjoEZsEknic0mNrSCMedZfLV95k761w,9059
+pycountry/locales/ca/LC_MESSAGES/iso639-3.mo,sha256=Yr9NecTSkaXNySUggjeqikORLd0UkfzWifmtWUAIzlQ,25765
+pycountry/locales/ce/LC_MESSAGES/iso3166-1.mo,sha256=Ry8LH4ZammiHGSaFExQ2Go7_bsz5PR3oxzXMonsAurY,10819
+pycountry/locales/ch/LC_MESSAGES/iso3166-1.mo,sha256=LKRR9EeT_QvK_YRa4PYZjAjUPCJOXxLOvoX_TVyz96E,1416
+pycountry/locales/chr/LC_MESSAGES/iso3166-1.mo,sha256=dNxi__17QfyJIfXLpTZlOpIDbNhKI-xQNZHWm_iRP7s,5143
+pycountry/locales/ckb/LC_MESSAGES/iso3166-1.mo,sha256=-CG05duYTphKeUL6urQKcq_V-CILrwm_rCWE5MDjwnI,10429
+pycountry/locales/crh/LC_MESSAGES/iso3166-1.mo,sha256=mio4ksDgP3vkAZv35b7vzwvPSLX8XN3b4nYkmoHjr78,21581
+pycountry/locales/crh/LC_MESSAGES/iso3166-2.mo,sha256=PVhzh91jmokj0OMzgIsN5ZNPGuFJrJ3GS4AUVXT5LSk,3684
+pycountry/locales/crh/LC_MESSAGES/iso3166-3.mo,sha256=69s89vyss35u5TfPoPFe35C8GDl461egj-T3XpmMUZY,2773
+pycountry/locales/crh/LC_MESSAGES/iso639-3.mo,sha256=g36ALRhWzI5PM-9Qg50cM44OZAxKBd0lTU5HvbFKsIY,256161
+pycountry/locales/cs/LC_MESSAGES/iso15924.mo,sha256=GHXFTh4eRZIV4XkuyZtuerlprHhST1O1ih3TMR4PWH8,9003
+pycountry/locales/cs/LC_MESSAGES/iso3166-1.mo,sha256=AGt1wa04gJq0kLKw5yh24tyhTb9hziY-sJMvHYvz5gI,24094
+pycountry/locales/cs/LC_MESSAGES/iso3166-2.mo,sha256=NWMUzpPFs_inKaa8KiZWQ--HdMfUr2qgtYkbNYCeagg,9150
+pycountry/locales/cs/LC_MESSAGES/iso3166-3.mo,sha256=XlpGocVlJciJE6HrOH1yri3lvbXfXjqVDPA6LlTBM8A,2879
+pycountry/locales/cs/LC_MESSAGES/iso4217.mo,sha256=xwx_BJqjmzr_mmzYjR5Wt5g3SbWOAk4rUoc1HcNbTZk,9477
+pycountry/locales/cs/LC_MESSAGES/iso639-3.mo,sha256=SzZZh2Z2QGKCbxsolAiDSaUAl6t73j66HGkLbi7Tjpc,14412
+pycountry/locales/cs/LC_MESSAGES/iso639-5.mo,sha256=Us1dtkxGW_FZIiuzaeFgJtihU33i-xIieqlYRywCKlk,3971
+pycountry/locales/csb/LC_MESSAGES/iso3166-1.mo,sha256=O6VFwNjiIBO6J2cQ2THq6nsDRX0Nrj_2HYcjIIwpHeQ,4448
+pycountry/locales/cv/LC_MESSAGES/iso15924.mo,sha256=mt3g5WZ6prfb64-Wo6IGYbhkDetKnwKu7hHTQACh2Qk,10986
+pycountry/locales/cv/LC_MESSAGES/iso3166-1.mo,sha256=x5y2q0VpspabSAL1TzR_t_OaOfi316tLdX45_eI_KGw,10906
+pycountry/locales/cy/LC_MESSAGES/iso15924.mo,sha256=sxBCf6VU1IgCJ-K9OdwRBIC1kEexZEKt23NUKOUCZpM,3619
+pycountry/locales/cy/LC_MESSAGES/iso3166-1.mo,sha256=bZcvDOVpLy693csdzJa9EU6SO6vDi-qcuTWCDNdzFM4,23789
+pycountry/locales/cy/LC_MESSAGES/iso3166-2.mo,sha256=YQcHAwAOE7d0y6KUYZisn3NIn8oDty2Vldbunj51geo,34985
+pycountry/locales/cy/LC_MESSAGES/iso3166-3.mo,sha256=A1pcNJOs0wk8co-v1yRG_lF6i-j-_EyL0jSi88DI_yo,2876
+pycountry/locales/cy/LC_MESSAGES/iso4217.mo,sha256=Q_XAA9wuKeTjIfA1fTyRs3lTPdBbw_qf38HReYkvln8,1790
+pycountry/locales/cy/LC_MESSAGES/iso639-3.mo,sha256=N0JMXN9X2y5oAc3FppwF_2ejp5DdAOOnsbPt2CRaais,14506
+pycountry/locales/cy/LC_MESSAGES/iso639-5.mo,sha256=V2Ow87MXb2B-y4iCVWCZPfXnj3J_NJbN05IvCoQg7m0,2109
+pycountry/locales/da/LC_MESSAGES/iso15924.mo,sha256=Njhq1F6ZvIvdpR2xy3sQGjvYnopq4VmFYqAsHht0yFY,10182
+pycountry/locales/da/LC_MESSAGES/iso3166-1.mo,sha256=sGYEO6DUweOnXEujMTvaDRJfK9DEb2i8EG-keSkpetw,23328
+pycountry/locales/da/LC_MESSAGES/iso3166-2.mo,sha256=eY60uUOd31mrjQ4yxqiURV5lUJ9w7eBqfrWjXJTKWQs,134479
+pycountry/locales/da/LC_MESSAGES/iso3166-3.mo,sha256=ujrGCZUJOjnhZSjYF7zcuG8JLhBtN285ktQjqRlLC8s,2671
+pycountry/locales/da/LC_MESSAGES/iso4217.mo,sha256=sIUU5sEf89-trTQAgxEqT562xPi5z03hUVqRLVzOz9o,8861
+pycountry/locales/da/LC_MESSAGES/iso639-3.mo,sha256=apW4_GcBnKIxA1gTlD47CKInRLioHZ5Bnu8gqsCYbss,19729
+pycountry/locales/da/LC_MESSAGES/iso639-5.mo,sha256=RxLEyc0Xe-CWsmJXY0H7VtXMnOZjiyHaipYE_IEZrAA,3961
+pycountry/locales/de/LC_MESSAGES/iso15924.mo,sha256=ZYrOcYO7mU2HtDKo431U1dlgnsSepnH3PVNIh6lME9k,10383
+pycountry/locales/de/LC_MESSAGES/iso3166-1.mo,sha256=61jN9MqyRZ-QQ0stb44pOn9xFvdny13P0VBksFUXnxs,23454
+pycountry/locales/de/LC_MESSAGES/iso3166-2.mo,sha256=RmqrahSmqr_uTORk80tATDJS0Pbygzbx3alyZY7Xqhk,212230
+pycountry/locales/de/LC_MESSAGES/iso3166-3.mo,sha256=ROp9ZyyraJszLaXxy6ToJSj1h2MTAeDFU9YpzcWvrt4,2815
+pycountry/locales/de/LC_MESSAGES/iso4217.mo,sha256=-WNvFBFdc_F52si4GtVELc94pXQwg1Vek8H6Vi5-lcw,9904
+pycountry/locales/de/LC_MESSAGES/iso639-3.mo,sha256=YCZPZM3duYrFiDvt5uvp2mYy975JdgkU9ub0sngTD0s,395660
+pycountry/locales/de/LC_MESSAGES/iso639-5.mo,sha256=rMJ6B4Yt8rtbeLvWaw-TcDbOxf8ggfytflQOKlKU8jk,7860
+pycountry/locales/dv/LC_MESSAGES/iso3166-1.mo,sha256=XDsoK_W6k_U96CcC5YauBU2pA9kMOFT5cyVl6aR7g2I,11257
+pycountry/locales/dz/LC_MESSAGES/iso3166-1.mo,sha256=uV4vcsy0e-e8-cC5n3m7dQle39x5THKOcuX7ybdQr1g,40229
+pycountry/locales/dz/LC_MESSAGES/iso3166-3.mo,sha256=koBYk1RwabIAOHN43YwxcfrlYMCUE19R5gYVARwtuj0,4758
+pycountry/locales/ee/LC_MESSAGES/iso3166-1.mo,sha256=yEnDc6En7uBp7y4XPGerjfTESbTMdHIp-uk5_ZQfuWQ,522
+pycountry/locales/el/LC_MESSAGES/iso15924.mo,sha256=k9pEyyu1TbQzMbwfW_nvq37P8GVF3nLv1mxgxG0m2RI,1864
+pycountry/locales/el/LC_MESSAGES/iso3166-1.mo,sha256=8BjqMl4_9pEqUF0bXoVFqvpEOFLAznTyha9HYF0_cNA,30772
+pycountry/locales/el/LC_MESSAGES/iso3166-2.mo,sha256=3PIeh6MRCdG0AL_0VN10_pk7uht4yB9VOm_PXOrJziI,9264
+pycountry/locales/el/LC_MESSAGES/iso3166-3.mo,sha256=-EQ2ULB1zDz_-q8E_RoeyNEDulJH0lDiRPg_ukBpKCU,3428
+pycountry/locales/el/LC_MESSAGES/iso4217.mo,sha256=hwuizS_gpzXs17LR0KDg7DCXChAqxbo0OPiI44yOoNw,9431
+pycountry/locales/el/LC_MESSAGES/iso639-3.mo,sha256=A78zCtB-KAgGcc_I_UwlzQ6wEMumiXM38le68DdZ_AU,57390
+pycountry/locales/el/LC_MESSAGES/iso639-5.mo,sha256=7KaqAqDWDQgtpqPIBEYfN2Nn-4oL9651RpjvWFw0EWE,2391
+pycountry/locales/en/LC_MESSAGES/iso3166-2.mo,sha256=8uY3WaRyWfDcgAftUjP9yhLDeO-6_zYHthsBzYncZyc,90768
+pycountry/locales/eo/LC_MESSAGES/iso15924.mo,sha256=OedZ3T7f97tZ8LMMptEh_Vua3VaAZYRaOCTm0p3iZck,8524
+pycountry/locales/eo/LC_MESSAGES/iso3166-1.mo,sha256=dr01nC8FEUgGjZCdOMzXbm7xt8W_4q4NjkoDWaVcAks,23042
+pycountry/locales/eo/LC_MESSAGES/iso3166-2.mo,sha256=Xopo3v14n2Oua8e7yFUdUrRdOS6dzV7R5e_UzVWr5yc,46967
+pycountry/locales/eo/LC_MESSAGES/iso3166-3.mo,sha256=mOFUjyiPsHicME4Lt5_1qHrgLrXhqfcYF-AEmakcJko,2599
+pycountry/locales/eo/LC_MESSAGES/iso4217.mo,sha256=epKWtcArMSTraE47QbQ9ji8vITvxD6Ph1xG3Elnb_Q4,8374
+pycountry/locales/eo/LC_MESSAGES/iso639-3.mo,sha256=8w197bKO5-bipI24moC5t6a1SHcC7-QvAlQcTTi9ckw,48656
+pycountry/locales/eo/LC_MESSAGES/iso639-5.mo,sha256=6WlSyNLvedWIBv04knXYPEwqFH5eTyC4hjWfwGnkwzQ,6705
+pycountry/locales/es/LC_MESSAGES/iso15924.mo,sha256=gdkpJiaiQSKCYw9nomHgm4rSdvg65nWMeaaWeW5Qd-k,10493
+pycountry/locales/es/LC_MESSAGES/iso3166-1.mo,sha256=h3Hzd2DyCMAtOkEu8fjiAKywX4MQPlcn7JTl1IrvkyQ,24037
+pycountry/locales/es/LC_MESSAGES/iso3166-2.mo,sha256=2HCnjjkXXUvGrIZAOwLpb8aAmjIR7Qi8-pzrv5hMTnE,15680
+pycountry/locales/es/LC_MESSAGES/iso3166-3.mo,sha256=MTW-LfPGXXKazp_9140BPRBvk8Ehj1qF9zfPjUd-I8I,2927
+pycountry/locales/es/LC_MESSAGES/iso4217.mo,sha256=zXh9O43AU_gvnJ9zp6l-D_F5RKkmFDMFqTOfOlbfNm4,9745
+pycountry/locales/es/LC_MESSAGES/iso639-3.mo,sha256=R32b8YA1xni3qAwYb0yUmgEkLSH3M7sr1qmn57Gc9zU,33190
+pycountry/locales/et/LC_MESSAGES/iso15924.mo,sha256=bBa-lP-KW8kk92aI6iytdmRso7ckXLn2QRM68D4T0rw,9689
+pycountry/locales/et/LC_MESSAGES/iso3166-1.mo,sha256=JkdyhAU40azro986veHLyFW1WnNx_dKVfXIbTHmrp1A,23059
+pycountry/locales/et/LC_MESSAGES/iso3166-2.mo,sha256=1v3cr3e1XE9miKSntAOB_y42DBq7_8-7JdOpSnRQZ10,12218
+pycountry/locales/et/LC_MESSAGES/iso3166-3.mo,sha256=fWoF_uCGivdUfWpLdcfMbxOIMzPr4Lg3KYtFbp2MjeM,2748
+pycountry/locales/et/LC_MESSAGES/iso4217.mo,sha256=JMU7n6uUa9fQ3ULXCuoJ4EeOlUm8tU_vjS4tK7DkiVI,9565
+pycountry/locales/et/LC_MESSAGES/iso639-3.mo,sha256=02PjBSBx7RHgbNQf8sVbhx0k2LM5xYrXSBGfQP4sVqA,32017
+pycountry/locales/et/LC_MESSAGES/iso639-5.mo,sha256=u2UzyeBVJ4EfgURDtAotsgLFc84jalBE9_OhQqvIu5I,7437
+pycountry/locales/eu/LC_MESSAGES/iso15924.mo,sha256=DGTqul6pkxC1N3_tNru3up577rnHLULk_OvqrD2b7XE,10499
+pycountry/locales/eu/LC_MESSAGES/iso3166-1.mo,sha256=nINnO49UTvGw_P6GqParxGP2Ra-3uBSQHfxx4EcLt3M,23811
+pycountry/locales/eu/LC_MESSAGES/iso3166-2.mo,sha256=VHeL7j9VeX0pmIrevJsIC-lr-XfI2jLMoJZBZZaxHpw,23745
+pycountry/locales/eu/LC_MESSAGES/iso3166-3.mo,sha256=WDxWO7IFnw8NWJT2ozJuWIAG3EDekFDN8NVm7WNd1JY,2745
+pycountry/locales/eu/LC_MESSAGES/iso4217.mo,sha256=_9cNERxaRATG5mlsgcx4OgTlZ52nr_GJKskhk-CldC0,856
+pycountry/locales/eu/LC_MESSAGES/iso639-3.mo,sha256=2ksCA4389wGczCflrrqKOSc93mdOIePvCYndei-QtHQ,20888
+pycountry/locales/fa/LC_MESSAGES/iso15924.mo,sha256=pVoYWVxZZboJzTYmf57zXEyKa3ZrBfAZvYsncb0a6jE,2314
+pycountry/locales/fa/LC_MESSAGES/iso3166-1.mo,sha256=7dFgCzOYnrZZaODsiEqZ0rYdUIX18zatIJO084ypjA0,26404
+pycountry/locales/fa/LC_MESSAGES/iso3166-2.mo,sha256=XdCQ4pAZ91oZSsWapWBa4N_vFfNHnboHAeExmcprOqs,372
+pycountry/locales/fa/LC_MESSAGES/iso3166-3.mo,sha256=dgATH1gPQogKMcVIhGLN3EqSymsx-UwG7FLsQUP92Io,3140
+pycountry/locales/fa/LC_MESSAGES/iso639-3.mo,sha256=WWUyB1VwOCphybCzND1GPh42PsU2q95ngArgmpejWZw,13407
+pycountry/locales/ff/LC_MESSAGES/iso3166-1.mo,sha256=SmjnFB-fFSYNCZKLP04fQOuhtENGAmQOuqgos48y1vU,3704
+pycountry/locales/fi/LC_MESSAGES/iso15924.mo,sha256=30xDiP6wZe9WSIaoGbXd9XbTf3TW9RrhewXOOuByPak,9006
+pycountry/locales/fi/LC_MESSAGES/iso3166-1.mo,sha256=bemhvHKjMonjuuBfwfK0mWieb1xYovqJUDGlbC72SXs,22418
+pycountry/locales/fi/LC_MESSAGES/iso3166-2.mo,sha256=mQtnJpLmI2HOFZvUdgTmKIecmMtoBdXP6pdD2mXLJDA,5183
+pycountry/locales/fi/LC_MESSAGES/iso3166-3.mo,sha256=TVMIlCs7iYo7FJecpg_BYTHfIfnA9ZqIS4X6bcT-93M,2647
+pycountry/locales/fi/LC_MESSAGES/iso4217.mo,sha256=dflS5jOAIcqzJ2XKkTP3LxI8YcxZ2O3QvuBXBbkzFAY,7172
+pycountry/locales/fi/LC_MESSAGES/iso639-3.mo,sha256=hTeZ1_Uz9D26qP5iWfQYM1RNR3JP2aK3iH9b_EV_oYE,13276
+pycountry/locales/fil/LC_MESSAGES/iso15924.mo,sha256=kfOl9pZBZ_rGdCj3sLzzR0Wt0Gd0EYwet9i7y7zuwg8,10473
+pycountry/locales/fil/LC_MESSAGES/iso3166-1.mo,sha256=CYgq3YrtaoqSms_KiG-lw2ljv0ruWqxsm8atAsPvKyk,23844
+pycountry/locales/fil/LC_MESSAGES/iso3166-2.mo,sha256=GRpA98El7KAGhLqrYxt4cExJ8P0LOHVZ6q_ydGzKVwQ,3047
+pycountry/locales/fo/LC_MESSAGES/iso3166-1.mo,sha256=_gC9v3TLsART2i3d83FTHnmWvpmpG9R-Wf4L3evp-ak,5837
+pycountry/locales/fo/LC_MESSAGES/iso3166-3.mo,sha256=5mYU9BUU_7BucS0iceQGWyeamCkcMbIzpTC4ovDYkr8,393
+pycountry/locales/fr/LC_MESSAGES/iso15924.mo,sha256=js32YkDs2dmkHI9_WFvO9eIzJw7Jr0dVRIiykfBt5No,10260
+pycountry/locales/fr/LC_MESSAGES/iso3166-1.mo,sha256=0xquoUO2OaXbl5OPBVw7qCSYqVBJciTZvjgG1ngsO-Y,24340
+pycountry/locales/fr/LC_MESSAGES/iso3166-2.mo,sha256=SOv40Jm_MLFCUQevW7LrXCz0dLb4JL9CBGXjr5NtAd4,160680
+pycountry/locales/fr/LC_MESSAGES/iso3166-3.mo,sha256=_kUqnSih1FWAMxZ6KnF7pETF9kB73nyPHHUSAS0JIGQ,2860
+pycountry/locales/fr/LC_MESSAGES/iso4217.mo,sha256=xkf83c1q_fH-YZ-Lf1GvaUjNVajhD4QVHUoxMN3byTA,9998
+pycountry/locales/fr/LC_MESSAGES/iso639-3.mo,sha256=woJzt9pMpa8c-6vdkHAhmjevosuIvYWaqWunEnGn3O4,418827
+pycountry/locales/fr/LC_MESSAGES/iso639-5.mo,sha256=w4gK091KSpZ-h5jsHMUO8rBqh25CaI-DCrGAZOBAALU,7943
+pycountry/locales/frp/LC_MESSAGES/iso3166-1.mo,sha256=IvjxXG0W4tSh-ltlxuhP-mCS-nUhu0T6CiPPw_25HWE,9173
+pycountry/locales/fur/LC_MESSAGES/iso3166-1.mo,sha256=0BP25keqdfR4xusOFaQ8bKMADYINpzMjOJm2_Szzbrg,23950
+pycountry/locales/fur/LC_MESSAGES/iso3166-3.mo,sha256=hvBD-ZkMSEuNqYjQvRJH5C_y-Fn99zy82p8b2RmT3z8,1483
+pycountry/locales/fur/LC_MESSAGES/iso639-3.mo,sha256=7ldEmDsfzEH735euvsKTDxGe85NseqCoLjssaXeVnJo,755
+pycountry/locales/fur/LC_MESSAGES/iso639-5.mo,sha256=P1rvQRKyur4ODVrNHFCT_3v4kp8CpILKMTtx9wGzhKo,7791
+pycountry/locales/fy/LC_MESSAGES/iso3166-1.mo,sha256=KYhmJx_lEHsdCuY7ZdaZtz2gI75ZBkZ888Dd_dZ5pBo,9356
+pycountry/locales/ga/LC_MESSAGES/iso3166-1.mo,sha256=eYYdvb0znruo9eAvmBbnAFZMTNfvb8svRX95q-fs6ng,23528
+pycountry/locales/ga/LC_MESSAGES/iso3166-2.mo,sha256=Hat1IzOSoDduYMlZ0VYqTy6xWW4ctSMCzFN_2IDkcHo,2380
+pycountry/locales/ga/LC_MESSAGES/iso3166-3.mo,sha256=LNuDlZiP2kT3yYnODsAVm5bD4PjuC2VSztuGokSzRP8,2691
+pycountry/locales/ga/LC_MESSAGES/iso4217.mo,sha256=RQDSVe2fsUQrbFFyVQNgqZYlzi7tKt0nlk0z_0r5n8c,4140
+pycountry/locales/ga/LC_MESSAGES/iso639-3.mo,sha256=p_c4KxUcsVXQx9pFPf1Qfc-P3SrtDVRqd7WAXWSHdNw,8814
+pycountry/locales/gez/LC_MESSAGES/iso3166-1.mo,sha256=JpzM7q09FPEDKh2HQYdkuXSdRNwFgdn5MaCKVorP-Ts,5761
+pycountry/locales/gez/LC_MESSAGES/iso3166-3.mo,sha256=zhI0xMndQj3An33A1kwA9Bh-u2gPBX3uYj0MNh1Nhqg,476
+pycountry/locales/gez/LC_MESSAGES/iso639-3.mo,sha256=0fYmG2PNN23wg8tgcO4nVFKXb5ssNIVm0XCvhcS33fc,5696
+pycountry/locales/gl/LC_MESSAGES/iso15924.mo,sha256=5BSkiLq_WtMnGnTJFeLqmwwi8wZ1sakoZabwYvVAcLk,8054
+pycountry/locales/gl/LC_MESSAGES/iso3166-1.mo,sha256=POqwc0GuezY-aRcYDuyK_0g9MBBpBwBZz2rX1AGjVc0,23252
+pycountry/locales/gl/LC_MESSAGES/iso3166-3.mo,sha256=3rMs00uCCQvh7sRz2lYsJXU8yqmRLxHTWtSYMt8UiVg,2695
+pycountry/locales/gl/LC_MESSAGES/iso4217.mo,sha256=K49BpfNZ8Prrick3I5NWbDod0rYAB_kk7l0mrfAF4EE,2840
+pycountry/locales/gl/LC_MESSAGES/iso639-3.mo,sha256=J1p57MndIdeIhb2SJk0qtMEEsDJ_3Xs-TVhwp8MBipE,306888
+pycountry/locales/gn/LC_MESSAGES/iso3166-1.mo,sha256=cfVLYnjOabG7BJAnUytlNFF8gX6oUFmGHigqSGeXHY8,8952
+pycountry/locales/gu/LC_MESSAGES/iso3166-1.mo,sha256=BTbIDjcopoGl-bq5XtmV36jIhMIn1dFbo-36oQWPH74,35101
+pycountry/locales/gu/LC_MESSAGES/iso3166-3.mo,sha256=spiaVCBHo7BSunG1rggmBMDOzsJsx15JWzfEdIxNysI,3904
+pycountry/locales/gu/LC_MESSAGES/iso639-3.mo,sha256=p2PKssMJTYTOYiX5uG9ywTyx2RpA4jCxK8Zh0S2McBs,44025
+pycountry/locales/gv/LC_MESSAGES/iso3166-1.mo,sha256=8rEYVKEPZVSB4SGyNWu0ArnMIiE-FY9MF_LHg3VVfp0,8982
+pycountry/locales/ha/LC_MESSAGES/iso3166-1.mo,sha256=TnHC_7VDELwHJc4d_WYcxzggGhdHlFFekvq2N-Ms6yg,5135
+pycountry/locales/haw/LC_MESSAGES/iso3166-1.mo,sha256=iRcwqDVb2jDSHf5H1PYWmS_0nWvv2g81dpI0c-xRp30,1305
+pycountry/locales/haw/LC_MESSAGES/iso3166-3.mo,sha256=HK1sDsEiXNA_NK6XqUtXKNRfP-dfwjYx9WHUHKLBI6A,395
+pycountry/locales/he/LC_MESSAGES/iso15924.mo,sha256=_3Nlkzr0LiLDKke0T0CsXbgs9x5N0eJOQscqbYH33G8,3410
+pycountry/locales/he/LC_MESSAGES/iso3166-1.mo,sha256=5v6_NYS1q3s5R9-jsoD_VVCiRpFAn8CvAL_FIKccoK8,27802
+pycountry/locales/he/LC_MESSAGES/iso3166-2.mo,sha256=dzm0v3NnXSecuWexx3oW1-PKg2LXnJMgwaWmfqkxJPk,43708
+pycountry/locales/he/LC_MESSAGES/iso3166-3.mo,sha256=F-OSPpj7nitjFo8mJHrJP61KZ3QJPYylusCpad8_e_g,3369
+pycountry/locales/he/LC_MESSAGES/iso639-3.mo,sha256=NuCJOIa-FqJ_FQuDWZ_auFhu06sSOhWYsa5Our3B_5E,5910
+pycountry/locales/hi/LC_MESSAGES/iso3166-1.mo,sha256=Q95AylmMfANJAGv0dhovcs0r6lxjWshQhoa0I_t4xE8,35310
+pycountry/locales/hi/LC_MESSAGES/iso3166-3.mo,sha256=pFd1cAHyRWzwkp_QhgSSiAVz7p_CRgvCzbrcJbjM804,3973
+pycountry/locales/hi/LC_MESSAGES/iso639-3.mo,sha256=luMW2-6Pp3sTvB9buOB34UDI15WZh0hCgPfcbZ1-wBc,6805
+pycountry/locales/hi/LC_MESSAGES/iso639-5.mo,sha256=RTUHKIcxhISyqJCqGfUysfQa2m2nIYwmkA_c7Pc3DfM,632
+pycountry/locales/hr/LC_MESSAGES/iso15924.mo,sha256=vuHO5WUcYSss-53qa4Pu4xuRKMsyhZnIbAtbulE0X2Q,10432
+pycountry/locales/hr/LC_MESSAGES/iso3166-1.mo,sha256=Rdhem8HnWKsJE5evHcxajZ0_NdVXIhXecRZ6vlLwe3Q,23488
+pycountry/locales/hr/LC_MESSAGES/iso3166-2.mo,sha256=eIfp6z7nrt_vdSifl0rwIc7CBUhJCHV2iwM5yNMueYM,25948
+pycountry/locales/hr/LC_MESSAGES/iso3166-3.mo,sha256=X-RNvwujPoNxjm5yRjTCDWGYikvgPPW_3soWw3PARaM,2755
+pycountry/locales/hr/LC_MESSAGES/iso4217.mo,sha256=LKkmodvlp_dTo93mNCsL_fNJ_aWMSrbkKECe2eo7qu8,10437
+pycountry/locales/hr/LC_MESSAGES/iso639-3.mo,sha256=QtArEyn7AdKwmye6VoNo0-dHRcQuoUaqxakqGqArano,52545
+pycountry/locales/hr/LC_MESSAGES/iso639-5.mo,sha256=e4HigZoiybRHAoCU0W5fvIEwcFwXlc6SkiHMUDUftuA,7671
+pycountry/locales/ht/LC_MESSAGES/iso3166-1.mo,sha256=zH-6PntafPCOEc5uX0cMqq8OyBbmOCCZmwGPzsrSPrw,7744
+pycountry/locales/hu/LC_MESSAGES/iso15924.mo,sha256=4yVUZPWcTvsPt3gjXBo_io3IZqzoainMJSopZhPUCJc,10301
+pycountry/locales/hu/LC_MESSAGES/iso3166-1.mo,sha256=I6lBfkjygbj1Bj1vrzuuGDG4AKE5R3uj1iQjtxLO3PQ,24602
+pycountry/locales/hu/LC_MESSAGES/iso3166-2.mo,sha256=h1z536RGjQhxQmx8IfaQO2Wpxffj6-wwYuvuXtK6jaE,68957
+pycountry/locales/hu/LC_MESSAGES/iso3166-3.mo,sha256=4fAqt1b4fSFw63xk8jvdw5bHwfsGe6SXwhzfcHLwkl8,2749
+pycountry/locales/hu/LC_MESSAGES/iso4217.mo,sha256=rLNyDbd0ZzKgCFDngXk82EdYSpqIT_tB20Aw2XArRVY,9822
+pycountry/locales/hu/LC_MESSAGES/iso639-3.mo,sha256=numYY-s-qG2n6jz8yW94gEEmhEIBF8en3CQnbSLBoRc,37180
+pycountry/locales/hu/LC_MESSAGES/iso639-5.mo,sha256=Gi5BDPXcwIMgQMVBmgI1pA3FSp6l0j12yfrmlv9vbcc,7550
+pycountry/locales/hy/LC_MESSAGES/iso3166-1.mo,sha256=SgoKIEZqOiJsfjFAVm-UEbIbO8J-4t-GIsNGi5CVdCc,30567
+pycountry/locales/hy/LC_MESSAGES/iso3166-3.mo,sha256=DFerwwdEXTrsOKykW5P_ShRYkT5sPebh-VPHO6oJd00,3474
+pycountry/locales/ia/LC_MESSAGES/iso15924.mo,sha256=1PBiVydopGdzqCdISFT_li4SvVSbcrdWsZRfs3w_8LE,8085
+pycountry/locales/ia/LC_MESSAGES/iso3166-1.mo,sha256=g8rup6qwLOGQdWBvdLX5wBILn3Xut0ksPwhiczD5U-Y,23347
+pycountry/locales/ia/LC_MESSAGES/iso3166-3.mo,sha256=qhAUSwo3yGpiUNpwuwSzMhGTR-9yF3JQ2h3dTjJO5uQ,2678
+pycountry/locales/id/LC_MESSAGES/iso15924.mo,sha256=3LEl9wkbCLMt9olNSdtyydFD9Sl5MBa2h0_glewmFNE,10195
+pycountry/locales/id/LC_MESSAGES/iso3166-1.mo,sha256=1VlyKfhYIZ431EQldXjUZXkDgLAUkiVpqBu6IMS9cRQ,23086
+pycountry/locales/id/LC_MESSAGES/iso3166-2.mo,sha256=8KzPIwuGBKn0WT6lrCeF8z8G7yZu7dDAZwXPwmG_JZY,159848
+pycountry/locales/id/LC_MESSAGES/iso3166-3.mo,sha256=ozybktlkBokoXXbkf-urGvEv43JWCSxDO1Vda7O7BIw,2702
+pycountry/locales/id/LC_MESSAGES/iso4217.mo,sha256=bZa_WATIF-LFNvAhseqzbtQFaQ6eYFClFJ9RXwFCMsE,9513
+pycountry/locales/id/LC_MESSAGES/iso639-3.mo,sha256=kApzflAdWd4t9eHUq15iJXA-FiHiJ2KBdL3VbSG0yLE,292415
+pycountry/locales/id/LC_MESSAGES/iso639-5.mo,sha256=ek0deioGwFL9VCZz5N0FWLj0CS_iZN31e1qwM24I86g,6346
+pycountry/locales/io/LC_MESSAGES/iso3166-1.mo,sha256=the_kbOffosZWAy_AczRytjRJ-N9Rs0VAjs6bzpijT4,9210
+pycountry/locales/is/LC_MESSAGES/iso15924.mo,sha256=NsRE93o-G5ZqhHFPzJLeExrqh_VKrQEm5-DSSlbjFAo,10637
+pycountry/locales/is/LC_MESSAGES/iso3166-1.mo,sha256=A82F_9dYIwcISOQ-46XaA8OKQ5IEUUwo146oG3NoMZk,24295
+pycountry/locales/is/LC_MESSAGES/iso3166-2.mo,sha256=NJ3kQGeSxOODOH2gFd7L4dMcFqCWXxwWEMqIagCKX90,4405
+pycountry/locales/is/LC_MESSAGES/iso3166-3.mo,sha256=H4DY1fZ_yZh1dFy8DCazWL_wKqEMbBV6i5ZDsevDJNE,2961
+pycountry/locales/is/LC_MESSAGES/iso4217.mo,sha256=9WF-9Tng8xunSKcJfsYuvGL9fGjGnqrTfB1lahTR2-4,9804
+pycountry/locales/is/LC_MESSAGES/iso639-3.mo,sha256=MoMDngccs6iCtwBXty1GnjaajKyV9M8PXToEYTwR72c,149997
+pycountry/locales/is/LC_MESSAGES/iso639-5.mo,sha256=bVNRcpSArWK7djnpmhOM8EGw9uYGTzrVN6_MlBqsCJI,8015
+pycountry/locales/it/LC_MESSAGES/iso15924.mo,sha256=3PcifL8wKpwbWx9dFSHkVeROgTZLqJZvXxle-073dWc,9447
+pycountry/locales/it/LC_MESSAGES/iso3166-1.mo,sha256=PoHfAmyCRWOlnbTgEbxATpn4MxEN9zd1S4FdxpxGdHM,23660
+pycountry/locales/it/LC_MESSAGES/iso3166-2.mo,sha256=ga7v0RIDdcdhbQTAuYGsMkdT0NYLH7vYFN8mbvBUJwc,157445
+pycountry/locales/it/LC_MESSAGES/iso3166-3.mo,sha256=OHn1oi0HReKAuA5iL8UuvcJkTsB1JgfB-QnQivGhtM8,2720
+pycountry/locales/it/LC_MESSAGES/iso4217.mo,sha256=Ho2xKcqhfDiGjSdCPI0rI6_9JIE7nnjnUFaHkaB7Tg8,9244
+pycountry/locales/it/LC_MESSAGES/iso639-3.mo,sha256=aPsP1OZAeba1cMeTwGNnRp-jFStALeX0onPnssISNWQ,369645
+pycountry/locales/it/LC_MESSAGES/iso639-5.mo,sha256=lZR81FkGkil6wZCILOorTOuybp_AdUiw5l5aIPn0HOM,6985
+pycountry/locales/iu/LC_MESSAGES/iso3166-1.mo,sha256=KML26LA8WfyalJ2HpmWRo2vRw3yV0RnxeRouMsEmbx0,1634
+pycountry/locales/ja/LC_MESSAGES/iso15924.mo,sha256=-jJCTC-JMAHR2milX9I6jOURullaz3REgv_WxUr0Rx0,4131
+pycountry/locales/ja/LC_MESSAGES/iso3166-1.mo,sha256=B6HRa1uWbjbpXpYr9oCO3Iut79PvhX9mw7DT5nardY4,24942
+pycountry/locales/ja/LC_MESSAGES/iso3166-2.mo,sha256=9grxJjonmTxBNcbfJ8HmXqygDOkEwup4se4O48MiXr4,99516
+pycountry/locales/ja/LC_MESSAGES/iso3166-3.mo,sha256=fhh7_zTxzd3FhSVEbhqzKUcQ8mwoCkDjTHyHJGV46D8,2724
+pycountry/locales/ja/LC_MESSAGES/iso4217.mo,sha256=OpOggFonS1d7L8ayRakkdMi6PMkUkP3dKtwGNGIy13c,10051
+pycountry/locales/ja/LC_MESSAGES/iso639-3.mo,sha256=FZWYk_X_VAFXgarDvUOlPQg363NhY3ynh_6vvlbL4ao,16790
+pycountry/locales/jam/LC_MESSAGES/iso3166-1.mo,sha256=uwGY95PKQaNhrVHycFQvwW1Rmzxa99R0o5EH_tJeh2I,8321
+pycountry/locales/ka/LC_MESSAGES/iso15924.mo,sha256=X7EaDENBGyFA5t46us0J9PBdS3U1vT8t3ojjPoWXU0I,6755
+pycountry/locales/ka/LC_MESSAGES/iso3166-1.mo,sha256=ZoDszEZ3RoUf0RmmC-ZMWNF0pDRNTex5lucgJdTBFYc,36655
+pycountry/locales/ka/LC_MESSAGES/iso3166-2.mo,sha256=SDWPbTZRDy6cxI4YEGcGiCclTpG4FcNUfZGGOLmQQPM,111221
+pycountry/locales/ka/LC_MESSAGES/iso3166-3.mo,sha256=USd-N-sbW_zNmAuC_-yvitKenHAr8-jgJjUPEtQ8nw0,4426
+pycountry/locales/ka/LC_MESSAGES/iso4217.mo,sha256=3ENLfUSCC793IMX80iSktX4rpj4hd_zDokzEEIcJYJI,13229
+pycountry/locales/ka/LC_MESSAGES/iso639-3.mo,sha256=aC4dBiZ3RhvTpGZlw1y2auiq6kgjWke8ALnIaqhPse4,371
+pycountry/locales/ka/LC_MESSAGES/iso639-5.mo,sha256=9Vm75nkeluDlrDbgxEsVA4u-xeTrBhe5bTKiPgZ07nY,11127
+pycountry/locales/kab/LC_MESSAGES/iso15924.mo,sha256=WQ04VkSplBiAbzyUG5IdEwUd0id88G9Mo915Iy5S2T8,571
+pycountry/locales/kab/LC_MESSAGES/iso3166-1.mo,sha256=wlwveOA7MtH7NnfdppMvke-oizv1Hq0EZLtFyWu4zq4,6371
+pycountry/locales/kab/LC_MESSAGES/iso3166-2.mo,sha256=RZ2aoXFVl9w0mH4-1u2zrE_aVgtuNVjLhcFMNt_xibs,1099
+pycountry/locales/kab/LC_MESSAGES/iso4217.mo,sha256=WEAogp5MgADVviLyZjT64FhWkiIPrCWAgqXua00xtIQ,830
+pycountry/locales/kab/LC_MESSAGES/iso639-3.mo,sha256=JkAo9SMzPrJFc-PurqUQ6kbvPwlxb19xaNzxbQOgf9s,979
+pycountry/locales/kab/LC_MESSAGES/iso639-5.mo,sha256=XJdqi1jdqzyerEao1SFBOOUe_UZgtz58Rshzk2mu2Eg,372
+pycountry/locales/ki/LC_MESSAGES/iso3166-1.mo,sha256=mWIyJogZzDehTwYKmxXK8bdpdk2hlx7pkDX0Rt9FBks,5119
+pycountry/locales/kk/LC_MESSAGES/iso3166-1.mo,sha256=5f5iQLfEVfkHOLbQ0WK-aJB8nMOuGHxaQAjm9Ze5ofU,29652
+pycountry/locales/kk/LC_MESSAGES/iso3166-3.mo,sha256=W5bf02Qa5Psz9AWQR44QFx1BAOC2hzggCk33dz0S8Zs,3237
+pycountry/locales/kl/LC_MESSAGES/iso3166-1.mo,sha256=k81CXX4w66zGYW2eLG_5C_7H8Drqg8-xSneTDtK8pf4,530
+pycountry/locales/km/LC_MESSAGES/iso3166-1.mo,sha256=3FTC8RZ6c4jN1nJ_2Mac5WcZ9SHL43Nzu6g1yFRcorg,36282
+pycountry/locales/km/LC_MESSAGES/iso3166-2.mo,sha256=aRMO25FLuuJsXc_X21V09B9V3Ctds-nG7kB8lx3aJgY,372
+pycountry/locales/km/LC_MESSAGES/iso3166-3.mo,sha256=YklIULLU34pf4DJeUUFs_mJ-gE2V_42-OZs1pyur-94,4069
+pycountry/locales/km/LC_MESSAGES/iso4217.mo,sha256=x6Z9uZDQcGCBpVzDXixvB3b1bZ65ilqxMu1baxQNLds,5396
+pycountry/locales/kmr/LC_MESSAGES/iso3166-1.mo,sha256=zGBNbF0LUNqh1aTAQICfM5h-S_dCY9vdl5hH_Iov_5o,21966
+pycountry/locales/kmr/LC_MESSAGES/iso3166-3.mo,sha256=hyMipX89DXSas_Ut-NJHBxvps90OTLKl4aB1x46Nr6g,2695
+pycountry/locales/kmr/LC_MESSAGES/iso639-3.mo,sha256=zlbjl066YcmcUvZcsar8lCH3EYbjuBPxo7d0W1wjDGs,770
+pycountry/locales/kn/LC_MESSAGES/iso3166-1.mo,sha256=T6dtyPAolD3mTkF-nFzEyjyJSAnaj17isjlWh1Z3_tA,29606
+pycountry/locales/kn/LC_MESSAGES/iso3166-3.mo,sha256=pZnO4_hvideU6kf6qhDNvr7fGsFEQRr-Q0796Tl7rn0,419
+pycountry/locales/kn/LC_MESSAGES/iso639-3.mo,sha256=AYCMdh8NjdapUwVSGDzUCZmrK4wV-u341qo29NLpjSQ,390349
+pycountry/locales/ko/LC_MESSAGES/iso15924.mo,sha256=NkRygCl0Pguf15xKrTF9-NcCY4V-OlDIsUMdcsX9cjg,2668
+pycountry/locales/ko/LC_MESSAGES/iso3166-1.mo,sha256=srf9KWiBvy8MsyrJ1Xj-maVD8ZNlLTtr7C1oJfeyiCo,24296
+pycountry/locales/ko/LC_MESSAGES/iso3166-2.mo,sha256=PveY_Yqmkr4y53TzZ5nikMEiKAAU5uh6k4-anuJDB5o,4513
+pycountry/locales/ko/LC_MESSAGES/iso3166-3.mo,sha256=NkIgm4Bv9odil2Dew18uCTygia4XisFmnivqeBRpH8M,2783
+pycountry/locales/ko/LC_MESSAGES/iso4217.mo,sha256=mSbaU3uFMgEmxVNt_WDwGz96t-hZ26thZ-wE46cnWfM,10767
+pycountry/locales/ko/LC_MESSAGES/iso639-3.mo,sha256=ayL0NVXCjlkiYu6GA5SGDbARF2VH1JTW8P89zNESfTM,18040
+pycountry/locales/kok/LC_MESSAGES/iso639-3.mo,sha256=5S4r9mRLkIXhlEoDoYpjQKOGlaYnIi59kulMJaV0OPM,6584
+pycountry/locales/kv/LC_MESSAGES/iso3166-1.mo,sha256=BZbH8N87ExrFP0-ZJOCdu5XRt3svWGnB3MMdKKXM9Dk,5803
+pycountry/locales/kw/LC_MESSAGES/iso3166-1.mo,sha256=Dxg932KVJl8zZ37knp-LOO-lYXo_rrkinzBJ3DOm2jU,9310
+pycountry/locales/ky/LC_MESSAGES/iso3166-1.mo,sha256=0rvHR3neRAG5sPD_VTZpyZV9rIu8fi2Iqc9PNwmq3bA,29069
+pycountry/locales/ky/LC_MESSAGES/iso3166-2.mo,sha256=YNzhvpBhs7kqZbjtU3OrnVWwR33DkDqTgX2Lncnl4VA,1419
+pycountry/locales/lo/LC_MESSAGES/iso3166-1.mo,sha256=KUVxvsDSnxv1LQ3gc0AAG3y5Ysg5YhwVDSd-x0Otij4,5756
+pycountry/locales/lt/LC_MESSAGES/iso15924.mo,sha256=9QYebB0VXZr3l08a9NlFNI2epclur8RiIxKjF1RS2Es,10170
+pycountry/locales/lt/LC_MESSAGES/iso3166-1.mo,sha256=oWNw_HLnYXVraRY0JYf2q2VqK_ux5zeX7uI7zz1QuLc,24199
+pycountry/locales/lt/LC_MESSAGES/iso3166-2.mo,sha256=Bnp6shUfWxRuWfWdRvYhyUsL-M9qRIfySCBl_9zTzz8,75519
+pycountry/locales/lt/LC_MESSAGES/iso3166-3.mo,sha256=kVA78seKlAPiIVsAurshuYvJCbuw-itdcQGhCL25BCQ,2987
+pycountry/locales/lt/LC_MESSAGES/iso4217.mo,sha256=pWPemu3SsvgecohxWkQydWvrn-YO8Bk082LbIReJoe0,10089
+pycountry/locales/lt/LC_MESSAGES/iso639-3.mo,sha256=c4HrVVFW1WIHg2LoDw1eGki7mgA4EaVl_tIyOefQSfw,31678
+pycountry/locales/lt/LC_MESSAGES/iso639-5.mo,sha256=rQGaYxSU5AAqer2AIW1Xx0JQF63GgaWzNO6aIwT_h8U,7646
+pycountry/locales/lv/LC_MESSAGES/iso15924.mo,sha256=OoS8qucwkeEXxfn1RGtFTltZnRlfO_lvmUs_J3tPNl8,9267
+pycountry/locales/lv/LC_MESSAGES/iso3166-1.mo,sha256=FbigEYJkunPuKaXRK8op-FQBSts_ehkPH7T5UxFm0Os,22888
+pycountry/locales/lv/LC_MESSAGES/iso3166-2.mo,sha256=MaAHhZQbeXynbc_J4_iTsaEwqMj3soPIVsVwSMe8MSE,2565
+pycountry/locales/lv/LC_MESSAGES/iso3166-3.mo,sha256=Ff997ECeSBlB5gzRRBUNhz0aH0LIOsjUu71ajYkkD7A,2671
+pycountry/locales/lv/LC_MESSAGES/iso4217.mo,sha256=AJ8ufVtN-z4M0DtYWFMSBWMxwrWAcj8QIBxNy8ixEk0,7313
+pycountry/locales/lv/LC_MESSAGES/iso639-3.mo,sha256=OQwqiAnV-kje06xMnY5wa_BxOl3ZRtCmsn63vlCAd-o,10625
+pycountry/locales/mai/LC_MESSAGES/iso3166-1.mo,sha256=Q3zMxb1sdp3H11a2ZWPMsxYuE4SSiWEKA2Fv0ZECiJQ,4535
+pycountry/locales/mhr/LC_MESSAGES/iso3166-1.mo,sha256=OV_oQbIiaNsA67k5yfpXqRyVovHcZgnWBePeOB4RcWc,5636
+pycountry/locales/mi/LC_MESSAGES/iso3166-1.mo,sha256=-mgk82qP3F3t5qVkFXlloMNM2idpyR4pF-jllMpknYw,10467
+pycountry/locales/mi/LC_MESSAGES/iso3166-3.mo,sha256=G_QNpnHvyCtiAh5Qio6C9xVPfhbq55uA5DtBJk7lcn4,446
+pycountry/locales/mi/LC_MESSAGES/iso639-3.mo,sha256=A3hPSvsJwEjJanUMFv_gV6wqe_7ITt4cHsU-E9EupQI,1619
+pycountry/locales/mk/LC_MESSAGES/iso3166-1.mo,sha256=f7aGLn5mdmyNHbLVUwO1IuC7FRQy2watIQZq7nlSBG0,27425
+pycountry/locales/mk/LC_MESSAGES/iso3166-3.mo,sha256=7EABtmE5bsAqb8WIiuwnb9Xj0Dgf_C2cOOptNPkwKGo,3238
+pycountry/locales/mk/LC_MESSAGES/iso639-3.mo,sha256=Q_wdjEiWESD75_JaKNgTliv8gRT6F-FS2pVQVuO79sA,2178
+pycountry/locales/ml/LC_MESSAGES/iso15924.mo,sha256=3P2PyoHcd9EwikqSN6Aw7cAAIRXUeNE5WkwafL9Jnm4,1295
+pycountry/locales/ml/LC_MESSAGES/iso3166-1.mo,sha256=moYe_RNoONL6eDJm4OVvhtykxpwYFtOfkTL6yV-8lvs,34752
+pycountry/locales/ml/LC_MESSAGES/iso3166-3.mo,sha256=WdB6nZlhBoIA5A5DrnSZ4oKfKZejUnIfjW6X2X0EB4M,4406
+pycountry/locales/mn/LC_MESSAGES/iso3166-1.mo,sha256=_xQUlpY_x_hWtWV8T8HMorrm24VTjhD5XNndVGhXJs8,10101
+pycountry/locales/mn/LC_MESSAGES/iso3166-3.mo,sha256=Tyr2sUeOHxFeqCxCyKYFR8kz_MMsEf5RIipQXcEceKw,427
+pycountry/locales/mn/LC_MESSAGES/iso4217.mo,sha256=CdhlTrQlm_9TFLzt6d1MxXLFTXlsnMeaMMriyPaC4Bk,5207
+pycountry/locales/mn/LC_MESSAGES/iso639-3.mo,sha256=n_gwivkBpobWRq7mB--L1JdB172cHm78xbwqA_KUNd4,6401
+pycountry/locales/mr/LC_MESSAGES/iso3166-1.mo,sha256=BnSxHnjfkTcXH03VahbT3kxr1b6zbHEYXwh33ERlC7g,35144
+pycountry/locales/mr/LC_MESSAGES/iso3166-3.mo,sha256=KFmyk3-Uf6vDStG14wk9kMk4qx34jDClz6PfLl-kIPs,3916
+pycountry/locales/mr/LC_MESSAGES/iso639-3.mo,sha256=AkCjp5dpBhLUvrBhBIy_mPBCxgHIQRsyiG7jcQldXkA,425099
+pycountry/locales/ms/LC_MESSAGES/iso3166-1.mo,sha256=U_dzi6MSkgaGpnIll9EsrZmWERbcBd_Z_Y0exgxS_lY,12693
+pycountry/locales/ms/LC_MESSAGES/iso3166-3.mo,sha256=rqFgeg2aulLXDqz6J3okbjs6K4gHlr_v5iTmDNWHbw0,473
+pycountry/locales/ms/LC_MESSAGES/iso639-3.mo,sha256=kEePQIWzA6yt7j3TVuiIYdIoZuaNM5C4BnIf-QhSjzo,2386
+pycountry/locales/mt/LC_MESSAGES/iso3166-1.mo,sha256=OhMqW3cJN9BNX-8QIUkNjt6TkCpHX7kYCKqg9ZwGciw,9641
+pycountry/locales/mt/LC_MESSAGES/iso3166-3.mo,sha256=wcDxImw9CGvLGsVLL3vNJFLMbyy5hyg5DHUA_f-jyik,402
+pycountry/locales/mt/LC_MESSAGES/iso639-3.mo,sha256=KyLeF56ABhY1GES7FPy9CNYBpAl5bbbmFSi9cI6Sexg,9694
+pycountry/locales/my/LC_MESSAGES/iso3166-1.mo,sha256=XRheiVAoJlgFplfbVXr4jqmYjHfazkDxHxPbr26tzGQ,15588
+pycountry/locales/na/LC_MESSAGES/iso3166-1.mo,sha256=oHg0zdK3UGG6on99NzrvTpWLNoC2C2mK_TKU4cTtt04,6574
+pycountry/locales/nah/LC_MESSAGES/iso3166-1.mo,sha256=M83IQ32HXa150nN5RqyumBNkBO0vJrgma8AJHU--G7Y,8116
+pycountry/locales/nb_NO/LC_MESSAGES/iso15924.mo,sha256=ZEh0GY5fQesNRed0yWel58JmU-cVr7WiEWeYVPoRCKc,4069
+pycountry/locales/nb_NO/LC_MESSAGES/iso3166-1.mo,sha256=Arn3Zn3jGewiogV__nJGrHjIIS04M1j37an8CJdPwR8,23547
+pycountry/locales/nb_NO/LC_MESSAGES/iso3166-2.mo,sha256=R_aHdRjjiA7PICO2q69-xzk0xtQ2Z_93TVktIMHa7bM,1305
+pycountry/locales/nb_NO/LC_MESSAGES/iso3166-3.mo,sha256=-o90o0KauhkoyIMQ6NuVMQCuRax0jC1HWLlzxO5hCYs,2838
+pycountry/locales/nb_NO/LC_MESSAGES/iso4217.mo,sha256=XyDB11iBY7HYZw0hPntMaEEsPipm6Rlq-fK9He-aOC4,8569
+pycountry/locales/nb_NO/LC_MESSAGES/iso639-3.mo,sha256=l6jiErTbYHJ4AFcfenmlPq9wQtDcy1PvA1SRItdyzKg,5570
+pycountry/locales/nb_NO/LC_MESSAGES/iso639-5.mo,sha256=bidWzaFBsRoOv2OWh_plbhZz00MmUZHuBsGfeZU1BTU,1237
+pycountry/locales/ne/LC_MESSAGES/iso3166-1.mo,sha256=KqYeIe99y3Ew9AHs8RvpYAdkmgxEswtuUaknRtcDSt4,32389
+pycountry/locales/ne/LC_MESSAGES/iso3166-3.mo,sha256=rRjEPNnu3Y-W_VoLzmKc72CnqLhyxFQxWtbPJuMrvoU,3799
+pycountry/locales/nl/LC_MESSAGES/iso15924.mo,sha256=a9799cDp42S4QxtT8ofhkvYRXFh9kn5tUD9P-2D5fKw,10224
+pycountry/locales/nl/LC_MESSAGES/iso3166-1.mo,sha256=sPXfhapd55zYe57bTbiHuIYdiUk0xHIvtG8oQQotSlk,23512
+pycountry/locales/nl/LC_MESSAGES/iso3166-2.mo,sha256=Rnq8tMHb8IsIUcxrK-naH9jIyuRbKFU4kmQmOWOyHtE,215191
+pycountry/locales/nl/LC_MESSAGES/iso3166-3.mo,sha256=QzLPYfbj8ko6LQLQPh0Qfdkx4xRN1RxOLR4DoVUfiaY,2959
+pycountry/locales/nl/LC_MESSAGES/iso4217.mo,sha256=bRJeb7rmRFiMPm6CrJ6fY6vSsmE8v9OYGp5nbTjUp9g,10365
+pycountry/locales/nl/LC_MESSAGES/iso639-3.mo,sha256=4C7AFhBEw3zd8FYYv3_Xbc_FcsrUvoY-d1rPjqFdxzM,86365
+pycountry/locales/nl/LC_MESSAGES/iso639-5.mo,sha256=eqhBfJsw89Ys-a4Kanl3g4X0UWbkhKk9SWgzCJ62C84,7532
+pycountry/locales/nn/LC_MESSAGES/iso15924.mo,sha256=CqbUV23MOxzmzuZgB8WtLMbBB7uwuPM9JI98RlXjrXI,3464
+pycountry/locales/nn/LC_MESSAGES/iso3166-1.mo,sha256=GpNnfkiFwCnCiaT3ujWx3ArZSSm78DuVnvEkosK58WQ,21966
+pycountry/locales/nn/LC_MESSAGES/iso3166-3.mo,sha256=0Mggn7fYr37ZRb2Ooc7MoHqchPbf8_DpDVSp-lGPapM,2601
+pycountry/locales/nn/LC_MESSAGES/iso4217.mo,sha256=32ankGZqOLvRsGGkSHmK8CaY1MiuaQeTu52kr-Hj7E8,7566
+pycountry/locales/nn/LC_MESSAGES/iso639-3.mo,sha256=f_ONciTEpsEqcvJc6GcYUloAONNv9SgYwSjy6e4fQWQ,7462
+pycountry/locales/nso/LC_MESSAGES/iso3166-1.mo,sha256=RCdEiQwrUWbdd2WSrnXmWknjz0zARWdpT2w9nnOhblk,7830
+pycountry/locales/nso/LC_MESSAGES/iso3166-2.mo,sha256=YhnDOB-v4jfMR4TGjv_9cAMqfw-qBGL9Rj4zSRr28NE,932
+pycountry/locales/nso/LC_MESSAGES/iso3166-3.mo,sha256=Ofa3OP2PVJhWdUMJeDgMm208HTQYrqsLu0oiK-Mu7a4,521
+pycountry/locales/nso/LC_MESSAGES/iso639-3.mo,sha256=lAzl_ZZmKdS4Xexh20QcVi1GUiAFsu3v29b8Y5-u_Kc,2872
+pycountry/locales/nv/LC_MESSAGES/iso3166-1.mo,sha256=TvwEZNkDekfC7Pwo98I7s5rEuXo1Sy166H5Pzm_s57M,5808
+pycountry/locales/oc/LC_MESSAGES/iso15924.mo,sha256=JbJNE3pUlwNeuEqWGM8EqRkmYxV2z-fqwfQs-vbVjZ8,1713
+pycountry/locales/oc/LC_MESSAGES/iso3166-1.mo,sha256=x36bwuWld6kT8GQ5hXmTWWyZFb8rTcTtvx9MfYCMcXw,23749
+pycountry/locales/oc/LC_MESSAGES/iso3166-2.mo,sha256=Ig7I7dxfosV1l98AyUlZ3SO15y85pnk_eIGbBy4dGNM,5637
+pycountry/locales/oc/LC_MESSAGES/iso3166-3.mo,sha256=ECpyuk5S_Rnzwley3Qo2mAKyehN2Rl4HwmU3js18OFc,1105
+pycountry/locales/oc/LC_MESSAGES/iso4217.mo,sha256=3w9xX-qdcOvwQE1zILof_dCdCkqLT42X0-9h0zgr0Ow,527
+pycountry/locales/oc/LC_MESSAGES/iso639-3.mo,sha256=XCztvixWxvZdsv7exOJqn_bzvZmqcmEBGeSkwKzlVLA,3446
+pycountry/locales/oc/LC_MESSAGES/iso639-5.mo,sha256=tz9tIGP47WFBJkd3bBCWTV4RdOU1U0FZgbENT7qGiE4,856
+pycountry/locales/or/LC_MESSAGES/iso3166-1.mo,sha256=l_IeB2IJTCvBKpjxpgzsOvx-p7psmaRtW8f_oVeKKAY,34110
+pycountry/locales/or/LC_MESSAGES/iso3166-3.mo,sha256=DzJxc6bigfxYLlpkdUGrcEzb1b8lx2ZVnl_Sr9ITGdo,3975
+pycountry/locales/or/LC_MESSAGES/iso639-3.mo,sha256=yZFsd6SCJlAcMURl06SoxbAGV_jQ2bQbpatjUL3nQ7M,217560
+pycountry/locales/pa/LC_MESSAGES/iso3166-1.mo,sha256=9ErCZdyNlZYAeAPRMvT-2gk7yxbaF3n-9p4kkxibi4g,30877
+pycountry/locales/pa/LC_MESSAGES/iso3166-3.mo,sha256=Tk-lQ6dBpKC8UXjFfTs7q5TTiq2Uk7IFnE_qgBlPIps,3558
+pycountry/locales/pa/LC_MESSAGES/iso639-3.mo,sha256=T54oKUkzOnvS06ffITy4IDNZ6N0biTyUQMdwOrVBOfA,410401
+pycountry/locales/pa_PK/LC_MESSAGES/iso15924.mo,sha256=LJ-WjXSCxdR7deHiNLN_80s1izE8-7Njtgq7JvZQiNk,1418
+pycountry/locales/pa_PK/LC_MESSAGES/iso3166-2.mo,sha256=qlW7oyRPyaCgtkARCmw5qYtL47ULlyJ2hubStN0r3ck,1018
+pycountry/locales/pa_PK/LC_MESSAGES/iso3166-3.mo,sha256=ouL9SO_HROrNz0-ni3vXOI_KcYiDge_V3k8X7qEAAmA,601
+pycountry/locales/pap/LC_MESSAGES/iso3166-1.mo,sha256=FBb09ZfgpfjYTvXwOKXQz7_Fzv-8ZRBc9XtOhCIWIN8,531
+pycountry/locales/pi/LC_MESSAGES/iso3166-1.mo,sha256=pFlBizXn1qcFEftRLHC1OvO5YEY8pXhPYKA1G658Lqk,9264
+pycountry/locales/pl/LC_MESSAGES/iso15924.mo,sha256=ChZDUSPyEhTcn_CmTJkUN-OVScdBsVXnBH-GksUraVM,10158
+pycountry/locales/pl/LC_MESSAGES/iso3166-1.mo,sha256=hwzk101N_IVUvwufamjDcNe1fJ35SvOnrB4Ifwy70y8,23849
+pycountry/locales/pl/LC_MESSAGES/iso3166-2.mo,sha256=dDeL9yhP7MJnUwmHA_qZWXjMcnxVto9d3FIe40tS8t8,203350
+pycountry/locales/pl/LC_MESSAGES/iso3166-3.mo,sha256=DrapsF8pgNEYySgjjUYr4b5_VaSC4rSQaSo2cXcF3FE,3054
+pycountry/locales/pl/LC_MESSAGES/iso4217.mo,sha256=XDBLhQVRL4QgTdo7EgA-l0QUBLAofjT4dDDMjc6n-aM,9807
+pycountry/locales/pl/LC_MESSAGES/iso639-3.mo,sha256=1467OYlnc9nfNzHOWF6yijaZP0YD2alsnaAM5sRww6Y,121821
+pycountry/locales/pl/LC_MESSAGES/iso639-5.mo,sha256=pUck00ME7y7U8wwe2D0tAAGDofM3L5mGV9fOoPKCqFY,7985
+pycountry/locales/ps/LC_MESSAGES/iso3166-1.mo,sha256=xPw4NqIJqKxTIAp2OuKAd_ca5NMfZ4aNkEiD_nYzoHY,7217
+pycountry/locales/ps/LC_MESSAGES/iso3166-3.mo,sha256=erg7jvNw-16he0-ZncGQLITx9EO2y_QqEVcTG3LxZzY,392
+pycountry/locales/ps/LC_MESSAGES/iso639-3.mo,sha256=0XxdqpiZdMeBtRMFFxukxfnK59hpmBW4JSj2EWZ9N8w,1709
+pycountry/locales/pt/LC_MESSAGES/iso15924.mo,sha256=JwYTVlQ3mxSFJ3nM2rteUO-Ea528Jt-wVBE9DLxPSm8,9583
+pycountry/locales/pt/LC_MESSAGES/iso3166-1.mo,sha256=uK1qggQLhfKMdhnIAsa6dHnsM8-fToIyBGGQ8YjStmQ,23926
+pycountry/locales/pt/LC_MESSAGES/iso3166-3.mo,sha256=w5pTDJ8tXLVYy03azTi45nRpHpKG-v98gbi4Ko7eaDc,2716
+pycountry/locales/pt/LC_MESSAGES/iso4217.mo,sha256=YgHNnGn8_rwdixUmkqi2UkxXD9O3Fnt16DOFno8UVjE,9110
+pycountry/locales/pt/LC_MESSAGES/iso639-3.mo,sha256=56AzlSwKl3EY9LejPNhNxVJX2VsHlX_ZGCPse-jO3eA,15062
+pycountry/locales/pt_BR/LC_MESSAGES/iso15924.mo,sha256=8PbEoQcRvIjgHHofQW00hndDMuwmWZYYTNAssU50Gc8,10363
+pycountry/locales/pt_BR/LC_MESSAGES/iso3166-1.mo,sha256=N2ZJSGXno7X6FXWPdIuAwlrY3ogUnwFq55972aw1JQY,24079
+pycountry/locales/pt_BR/LC_MESSAGES/iso3166-2.mo,sha256=7qWV_nMXP2DzALW4yhfdL1hguzywzQvoY0QWszs6g4I,858
+pycountry/locales/pt_BR/LC_MESSAGES/iso3166-3.mo,sha256=DCpWd3635J0iZDReha3WpsMjqMb8hbalzVOwFn3yao8,2874
+pycountry/locales/pt_BR/LC_MESSAGES/iso4217.mo,sha256=4jkfYCQ7l7g2KOYehzby6gX5hZc5nk5cP3GPltz4j_4,9032
+pycountry/locales/pt_BR/LC_MESSAGES/iso639-3.mo,sha256=wZESsoY5izriySsHA-qWdmGwevHu-A_YAmFJSRnyyN0,17829
+pycountry/locales/pt_BR/LC_MESSAGES/iso639-5.mo,sha256=9rvvH1v8spqAF__R_WLf3gLqTS2zjQ_MMrWZsk2GTm0,7751
+pycountry/locales/ro/LC_MESSAGES/iso15924.mo,sha256=1hb54cTl8Ar7XJ6NsRq-I1RB66rFpbQ_aFB_Iyl7okk,10632
+pycountry/locales/ro/LC_MESSAGES/iso3166-1.mo,sha256=9adL4zOH3Uj-U_XzcfBfEyhnhXptt3QhnUKDziTULvo,23486
+pycountry/locales/ro/LC_MESSAGES/iso3166-2.mo,sha256=2AJIFTDrgKN4ZfOk6pfSmMYu1xeth536mNOB25CewZE,229998
+pycountry/locales/ro/LC_MESSAGES/iso3166-3.mo,sha256=6at6aDNhW5PJf9Fu38J8SG8lTrA7x9xZNay5sA8whr0,2987
+pycountry/locales/ro/LC_MESSAGES/iso4217.mo,sha256=uL3NPnUt7wptPaNm19-TrSjuxK1jUExTqu0CIGLoiCA,9977
+pycountry/locales/ro/LC_MESSAGES/iso639-3.mo,sha256=P3QxxTJqqULInvWK8bq25xaJMurvEO2qsqAGEA84AHA,10854
+pycountry/locales/ro/LC_MESSAGES/iso639-5.mo,sha256=Gs01_bLv7tVgk6YHOBMdo8YwxxFzQOegik4j4izamzo,10650
+pycountry/locales/ro_MD/LC_MESSAGES/iso3166-1.mo,sha256=8AiYPq4bSuyBEGrJsLYmgB5O-Bn1AO6IiB0Z2eyO_30,1779
+pycountry/locales/ru/LC_MESSAGES/iso15924.mo,sha256=D5nhIbZqZHViF0o7WCIIhyeto0fXS86S7K8KCnY31rM,12713
+pycountry/locales/ru/LC_MESSAGES/iso3166-1.mo,sha256=9pk6rUxpE7I96m134PUhpMsa0aQdPyepjnE9xfu0Qgg,29823
+pycountry/locales/ru/LC_MESSAGES/iso3166-2.mo,sha256=I-RxALMIdmlGpmVQNOog8kJrJ-guGvFqD-Nhi5R4444,105964
+pycountry/locales/ru/LC_MESSAGES/iso3166-3.mo,sha256=qg0LShA2DRa0FseecDzAwz0KqeSRKjyNtlJGgUf7Pc8,3480
+pycountry/locales/ru/LC_MESSAGES/iso4217.mo,sha256=Ko1sklB9eL6rTchOfDhyijv5p1RfWhjd9q9HJgKAL4A,11510
+pycountry/locales/ru/LC_MESSAGES/iso639-3.mo,sha256=BRjNeHk99_CZr_nyfgDjv0am70NrDdhbNGR04b_PN-4,18412
+pycountry/locales/ru/LC_MESSAGES/iso639-5.mo,sha256=xPQkTh32f-291290kVULkZT6qRxcekL5fA_u_lLvyKk,9598
+pycountry/locales/rw/LC_MESSAGES/iso3166-1.mo,sha256=0dfUtV06-48LrFMpuQb0kKxvmlzNcP8IGJ_P0nUHuks,21974
+pycountry/locales/rw/LC_MESSAGES/iso3166-3.mo,sha256=n8NqLeYepsK71DRZg4ruvP5oQhX83_NZ56vt2QimFdk,560
+pycountry/locales/rw/LC_MESSAGES/iso4217.mo,sha256=p3aVUk8p6Wp0bHdh0bu_N-3HBbXOZSOynm0x4SoLUN8,4998
+pycountry/locales/rw/LC_MESSAGES/iso639-3.mo,sha256=ty7dUCVZtqhhipVkC8FFfjbBpXFbjwZRNT4kUrBpgt4,14237
+pycountry/locales/sc/LC_MESSAGES/iso15924.mo,sha256=puEq5iMH0DSy_PoPfzpm1MJlxgCSSK_6LLX3-P7YeLc,10473
+pycountry/locales/sc/LC_MESSAGES/iso3166-1.mo,sha256=a-5NsP93OJzAomcXMuhAmmUFOGz9PyKXoMhBYtHstYw,24430
+pycountry/locales/sc/LC_MESSAGES/iso3166-2.mo,sha256=I1K9JxJWVrdqqXZiw88INw0Zk-er9UbfITtcgigt5yU,99178
+pycountry/locales/sc/LC_MESSAGES/iso3166-3.mo,sha256=49J-KVKf6uO1GkN1XDla2hfNVn8G_WvfnE-3yLSG9b0,2948
+pycountry/locales/sc/LC_MESSAGES/iso4217.mo,sha256=n9dy-L4xLPMUoK4THCi402jIBwfUicixAqhcop1IZTI,9999
+pycountry/locales/sc/LC_MESSAGES/iso639-3.mo,sha256=g5yoELm4g5lREZ-VW7dD45gr-lRBJnM7_VEhMb_jdAg,19985
+pycountry/locales/sc/LC_MESSAGES/iso639-5.mo,sha256=xZwNntGTvduMcHXwJyb_j_0bQmQENHL6j6V9Rkz5C0o,7679
+pycountry/locales/sd/LC_MESSAGES/iso3166-1.mo,sha256=V3bYIhtjsBccUKR5b3Q6KzceC-V9ZBSFTJDXqAEB1Ac,3785
+pycountry/locales/si/LC_MESSAGES/iso15924.mo,sha256=r8OMAYoDUkZIV8uLQqsl3v6OOIq_qXgjeqklAaGPgVk,600
+pycountry/locales/si/LC_MESSAGES/iso3166-1.mo,sha256=MVytBciZLPiFg1A8hdZjrUUgyasQhm7wBNe44Qg5i-k,31931
+pycountry/locales/si/LC_MESSAGES/iso3166-3.mo,sha256=zsvrlfeeg_GXVuSI0yhZj3nYwCnnqsYBf_5Gpkz6Rc4,3816
+pycountry/locales/sk/LC_MESSAGES/iso15924.mo,sha256=Sfg3wQLW7k337omWSP1sgOk_UtaoMtoXA3BtVAWmGpI,1782
+pycountry/locales/sk/LC_MESSAGES/iso3166-1.mo,sha256=T45425Ar2I0Gb7HUOkh3h6pnmtVmu0CSlLikzy_-oYs,24190
+pycountry/locales/sk/LC_MESSAGES/iso3166-2.mo,sha256=Ha6oIfiN1HtxZBSEenVf2jCh-EWTHjvD_IcNLYE3_zQ,13180
+pycountry/locales/sk/LC_MESSAGES/iso3166-3.mo,sha256=Qlk2HG60ssgXDYEU0kKyc8LgYc2wwaQUdIzMT3XKPt0,2887
+pycountry/locales/sk/LC_MESSAGES/iso4217.mo,sha256=_fmxcCaFZiO_sPGHyP3QQpch8J-QfsQk6jFnMbEyWfM,4911
+pycountry/locales/sk/LC_MESSAGES/iso639-3.mo,sha256=7fb1U7ylNLw0RwO-2Zsg5yHLU-eCkkaSrKLlY7JiKS4,11443
+pycountry/locales/sl/LC_MESSAGES/iso15924.mo,sha256=v12SjHgRm8aD-fvGzzO1t_ly2TGq_cVRzlbaBOqdAYk,6350
+pycountry/locales/sl/LC_MESSAGES/iso3166-1.mo,sha256=Eo4U8KyzSl5YjeqZTwpcXRWtPwOn5e44zUZ6y2tsUXY,22611
+pycountry/locales/sl/LC_MESSAGES/iso3166-2.mo,sha256=qJzdttVJy_27na2WMlMnIsnNpgVBgnD1PUuQ0xB3lxY,79342
+pycountry/locales/sl/LC_MESSAGES/iso3166-3.mo,sha256=he-9cSPr8xanRF6OlaSpRSnCdDnFyQbvt6Iccevlt1I,2596
+pycountry/locales/sl/LC_MESSAGES/iso4217.mo,sha256=BR6o-Jdk-MGqAgY7HOjmjoX2bd-_cV3WMuj3yCTL05c,7114
+pycountry/locales/sl/LC_MESSAGES/iso639-3.mo,sha256=mS5lyMCtHsOtfBYCtQ_ZkVuEWk_VFKXoae_Lvl5AmHw,14346
+pycountry/locales/so/LC_MESSAGES/iso15924.mo,sha256=t7pyh8r06chYo7T4RwxG3_vRu0G9VSNRSZjXupDAc3Q,1189
+pycountry/locales/so/LC_MESSAGES/iso3166-1.mo,sha256=v6ih3uvcmqbT3vo7l_54nrcZ4ad42h-bXNOiDCz9SsA,6066
+pycountry/locales/so/LC_MESSAGES/iso3166-2.mo,sha256=mwH2Zxm3CU0xJX9HJQDj7dNiDkLpj5XR3Derog-cwXs,372
+pycountry/locales/so/LC_MESSAGES/iso3166-3.mo,sha256=QJ91kNEe1pmPM906vCXgJ0A9hfW2qVXrrgBoIVPfuoM,996
+pycountry/locales/so/LC_MESSAGES/iso4217.mo,sha256=FmVSkEXoHpW9NSR3yADXzD3DZpGlzKqMiuhevWowzjI,370
+pycountry/locales/so/LC_MESSAGES/iso639-3.mo,sha256=qfn_eoOkGZe35_J9rbUEUdykn9daS16mvZXlygVLmDY,371
+pycountry/locales/son/LC_MESSAGES/iso3166-1.mo,sha256=BJf3H3lFsXnmPxzg_MO2HjfRbtw_VMr6Rhju8KVkEGU,9275
+pycountry/locales/sq/LC_MESSAGES/iso15924.mo,sha256=uqUGKRbJuVujMX8TXq-7oaXGsqWT-vldqRjmH7S5dZU,518
+pycountry/locales/sq/LC_MESSAGES/iso3166-1.mo,sha256=qgg_HzcqjaQIB6HYynenZ7Ya1PqJt2ObXBbPVnxRl68,23866
+pycountry/locales/sq/LC_MESSAGES/iso3166-2.mo,sha256=4s5zR0XhpAuw-SnXpaoJFUkt9jV3YCvyR2phdVYI7Ao,372
+pycountry/locales/sq/LC_MESSAGES/iso3166-3.mo,sha256=TsSeS0Yq30VDTikdJ2JAl7l4qiKGcg2norY1YHuoJ2M,2664
+pycountry/locales/sq/LC_MESSAGES/iso4217.mo,sha256=Xth9DE39BemxDH03jrg88695KNirBqFajadu-fbU2_0,370
+pycountry/locales/sq/LC_MESSAGES/iso639-3.mo,sha256=3mL_7NdlD2lX4q0_ODbr11iUOut7rUDvyRfRFpz94Zk,371
+pycountry/locales/sq/LC_MESSAGES/iso639-5.mo,sha256=c_6ngFn97IVi-zbhR4oljfnAhpg_jYjJrePIVnuY18Y,3810
+pycountry/locales/sr/LC_MESSAGES/iso15924.mo,sha256=eYo1GKGjHbLQlhambmHYpRvw8XsW0cyCTYijz8h5aGE,12875
+pycountry/locales/sr/LC_MESSAGES/iso3166-1.mo,sha256=vgEgAcY81cjYqHK4tsAOY77vdSXpdk-O3gRpEwcQnXs,28915
+pycountry/locales/sr/LC_MESSAGES/iso3166-2.mo,sha256=TbKirHfaYQWszhFuH-RtFULHoCgfOhNH2IhVjsGz1I0,144341
+pycountry/locales/sr/LC_MESSAGES/iso3166-3.mo,sha256=Y9sDJ32tTzNbl3m5OOk62DIc86BQ-x64fS3ryCK4dXk,3352
+pycountry/locales/sr/LC_MESSAGES/iso4217.mo,sha256=Ygprf9YtRR3N-I-8iaO9cm2CCaprdvBoWjqYnCF6wnY,9338
+pycountry/locales/sr/LC_MESSAGES/iso639-3.mo,sha256=pXTHorjW00WRE2JMR5R0EPGz_vsTrEYIWb3oLnkApmc,17095
+pycountry/locales/sr/LC_MESSAGES/iso639-5.mo,sha256=34piuKMjb1CmXWZUcp12HZ0OQdbYTtZTPOGre96UgIM,6247
+pycountry/locales/sr@latin/LC_MESSAGES/iso15924.mo,sha256=sw6yQ4S_MFdl_i-Gy9kKLXwJisA_V4kK_5RgSSJUw88,10451
+pycountry/locales/sr@latin/LC_MESSAGES/iso3166-1.mo,sha256=mQh3QCxwNJiXB_40sJRVOE6mfFiO73KXHBFnQzZDMQE,23246
+pycountry/locales/sr@latin/LC_MESSAGES/iso3166-2.mo,sha256=joWuPaXmGktimuPSrEeJjDYWZMocTAHNBhev4HxyOk0,121630
+pycountry/locales/sr@latin/LC_MESSAGES/iso3166-3.mo,sha256=2zlS7CRGoi4QBqgQdX1VfUMYD1FMK9EQ6qbcdbFWVS0,2709
+pycountry/locales/sr@latin/LC_MESSAGES/iso4217.mo,sha256=wF9LQtk76mPxthujLL6iRDkBiPzjH5sy74Zc_7_roIU,7652
+pycountry/locales/sr@latin/LC_MESSAGES/iso639-3.mo,sha256=ERPiEnQ4UyQl9vFTw3hoAvpb4nkORa739qjtzkGFMAI,14420
+pycountry/locales/sr@latin/LC_MESSAGES/iso639-5.mo,sha256=3ZtgzQqOCZ5DqaU3W9x9YngC7PI7opZAR1EWo0o1nzg,5040
+pycountry/locales/sv/LC_MESSAGES/iso15924.mo,sha256=jiv0-ieSaizYyJmBKJnbw-4zvv9bJp2l7qc33qvWOC8,10290
+pycountry/locales/sv/LC_MESSAGES/iso3166-1.mo,sha256=hdzOp52V6XQV4x_QU2SXGmz-Z0BV9h0S-QOJvtca07Q,23553
+pycountry/locales/sv/LC_MESSAGES/iso3166-2.mo,sha256=Wc9RbAQziL3BRERy2jTGRP7TpIVRoNFC6fKcEoRFIoU,158999
+pycountry/locales/sv/LC_MESSAGES/iso3166-3.mo,sha256=btjqVszhhQZnYBe2uV652pN5pmKE4Q0A7xWtlgBK9LE,2738
+pycountry/locales/sv/LC_MESSAGES/iso4217.mo,sha256=9SFR12NZzak2ibCMtpc-odXlNWVXeReCQ8QtCv2-S4g,9466
+pycountry/locales/sv/LC_MESSAGES/iso639-3.mo,sha256=gNjeBOXjQZwuhvsYcQ0l0YKdJddP6FGcUy8f1-1_O64,398696
+pycountry/locales/sv/LC_MESSAGES/iso639-5.mo,sha256=yK2_LQZ7UpcPnGFGua3NkNr3yt7qWIs8XIsn9BSl-hU,7469
+pycountry/locales/sw/LC_MESSAGES/iso3166-1.mo,sha256=puo5AcrjhUMrPVvv4ctytx2y-hl8nLZvRM8hcfeXSIE,7984
+pycountry/locales/sw/LC_MESSAGES/iso3166-3.mo,sha256=GTz8tO8hTl6B30ZJ6hNboAvBlocq7aIOpHufsw0835o,456
+pycountry/locales/ta/LC_MESSAGES/iso15924.mo,sha256=w-AOQsewUK2prYIDoyxecb0h74K7WQ_39UuG2YWZFDc,15455
+pycountry/locales/ta/LC_MESSAGES/iso3166-1.mo,sha256=JzDcKSbmcmQk8qSEys_KOMoslUy9D4wlqD3q0sbFfH0,35476
+pycountry/locales/ta/LC_MESSAGES/iso3166-2.mo,sha256=S-PGRpwJ1Sg6rps2dXt4AmdNEPz-I_t7J7FNBZj5VEA,372
+pycountry/locales/ta/LC_MESSAGES/iso3166-3.mo,sha256=cPKoxYmPgZV9MFKxuJ6Ku2xHCzkjO9Z2LSXMxqsaNNI,4343
+pycountry/locales/ta/LC_MESSAGES/iso4217.mo,sha256=6AwG1as7eikFI0O-EJVk7pTJpWPclSi9OooVqHq3mAM,14738
+pycountry/locales/ta/LC_MESSAGES/iso639-3.mo,sha256=SKhcrQG7pA-ueZBfh9UAmvvyG40KpLhAiUtYAe6gLxo,438885
+pycountry/locales/ta/LC_MESSAGES/iso639-5.mo,sha256=ANCGgfbY4F7ou3YoEbHTpRDDPyQkz9Q1OuyJm1ZV0qU,11658
+pycountry/locales/te/LC_MESSAGES/iso3166-1.mo,sha256=mcFUynzR9m9pOA7DQhz2eiiNwJNbjWiekP3y7_R7I74,35338
+pycountry/locales/te/LC_MESSAGES/iso3166-3.mo,sha256=1J3pjyPhcOEx0r5ai_wGP-CYtmMbey3j3f_64VBOcHs,4169
+pycountry/locales/tg/LC_MESSAGES/iso3166-1.mo,sha256=Q1GsbdEj1Pyrysbq2yzBLVdMdhCr9G2YWJ2Z0NKQb_U,28527
+pycountry/locales/th/LC_MESSAGES/iso15924.mo,sha256=ImX6_DD65iAEA-A8dORr6wrqob6QxPY5ASbydbHqVHs,11584
+pycountry/locales/th/LC_MESSAGES/iso3166-1.mo,sha256=6ThLMem5BNLYZ0u6S5VqaB5IhlavWZqDYTt1hBk0gNI,33663
+pycountry/locales/th/LC_MESSAGES/iso3166-2.mo,sha256=18LfmN92xfFzmPruPXCMh1qUU_gkGpzXcpyn4TtquXE,82740
+pycountry/locales/th/LC_MESSAGES/iso3166-3.mo,sha256=IpVULSIJH4a9rErHYMd6PhXvfRZp1_OUQHZNlDdTiRA,3819
+pycountry/locales/th/LC_MESSAGES/iso4217.mo,sha256=g6uA11k1shQdjskX_P-To_m6_mja4KpeS33_ImpU6h8,10193
+pycountry/locales/th/LC_MESSAGES/iso639-3.mo,sha256=ZRCDEoiUegTcELdrKJaGiLwJj2aMhhEQiFqOs6X4KGw,53438
+pycountry/locales/ti/LC_MESSAGES/iso3166-1.mo,sha256=jLyqklwEaSPBoHEn3qM4MuQwpjt3e2lGuEE2RROJgGc,11811
+pycountry/locales/ti/LC_MESSAGES/iso3166-3.mo,sha256=Wzmda-589yuFBuxwE9NxhikP3sjgZ0GfN0AWM_S6ZHE,477
+pycountry/locales/ti/LC_MESSAGES/iso639-3.mo,sha256=rudT0161eMCs7pDBdCvsDzVCkp7Uu-3oOuRzVE0WTX0,5858
+pycountry/locales/tig/LC_MESSAGES/iso3166-1.mo,sha256=VqELNsWPC8d0GfnR-i39uhWtQlJ2DhkiDhhjDvHrx1A,5712
+pycountry/locales/tig/LC_MESSAGES/iso3166-3.mo,sha256=nNn_DuHr6UAVZZ1vgbdhiVFAIc-qbeEzGU0-_LbySKo,475
+pycountry/locales/tig/LC_MESSAGES/iso639-3.mo,sha256=WJYDBiPwZI_MTFJwAcudQwiZmcnPIFurHgk0n_U8xUY,5697
+pycountry/locales/tk/LC_MESSAGES/iso3166-1.mo,sha256=PlNOnnM6E0c0obtWOp_XHnZPZWsIy5vw9xgLl2Y3Nvg,18029
+pycountry/locales/tk/LC_MESSAGES/iso3166-3.mo,sha256=ONXoCX_y_cwOQykQVAGTHgss5Lp3gopNAGg7182SAis,416
+pycountry/locales/tl/LC_MESSAGES/iso3166-1.mo,sha256=J1GKGeMDNvkJgjiMjbSNMUwNwp8rGMiDWsHGcXGBZwU,21411
+pycountry/locales/tl/LC_MESSAGES/iso3166-3.mo,sha256=I2g0ohTAhPm_9UhASYSNX8Xw4g3iEPlUvi-Ho9l3NJM,477
+pycountry/locales/tr/LC_MESSAGES/iso15924.mo,sha256=LByG1pluXvEtX58EmSSM2C1FejG7OFF6YdlaWtlPRA0,10222
+pycountry/locales/tr/LC_MESSAGES/iso3166-1.mo,sha256=yr_-WN2CQuw21YwQehdipCiBbMsTUKRYTlriLU0Z_Nc,23676
+pycountry/locales/tr/LC_MESSAGES/iso3166-2.mo,sha256=YwAD7hziqNJFf_axlTgiZzUS7c2IdfR2g8xI4dmOco4,76675
+pycountry/locales/tr/LC_MESSAGES/iso3166-3.mo,sha256=CNAu-ntnaWEiDS8l2zWeIAS9voMHRDkX9VUO-fI8tiM,2771
+pycountry/locales/tr/LC_MESSAGES/iso4217.mo,sha256=fSUr6ax4xjMSSa_xlObeBjhUyeroWZuOsbCuwNlleUs,9693
+pycountry/locales/tr/LC_MESSAGES/iso639-3.mo,sha256=9YRTy65obg3k-BJBtaWJKgooMg0_PZ5g2Czts2mj_Co,343245
+pycountry/locales/tr/LC_MESSAGES/iso639-5.mo,sha256=6NhQ-_LVXjnOIniEleyvDJjdfPU24fux2oa1xQb0iYA,7390
+pycountry/locales/tt/LC_MESSAGES/iso3166-1.mo,sha256=gdYOQv9w4lOepwyyJbCVHYvzP5iGvrr-VC7ohKpHm2Y,21810
+pycountry/locales/tt/LC_MESSAGES/iso3166-3.mo,sha256=8h6JDzC6q2pX8g9E5KlUI69PFyMFrnrzRwntIhQKBt0,501
+pycountry/locales/tt/LC_MESSAGES/iso639-3.mo,sha256=y8d2njNTkCYRDFvdr2xptprhpzxeaOlYl8dDoyYiYPs,7206
+pycountry/locales/tt@iqtelif/LC_MESSAGES/iso3166-1.mo,sha256=0HtZ1pOcYvYiQRpawNp9pMy-lqiKjJyYI9ffXorm8f0,18209
+pycountry/locales/tt@iqtelif/LC_MESSAGES/iso3166-3.mo,sha256=HKaTaYazrRYA3cEq6I6jFhKVAcVIr1Lj0b-wDKKDQ58,492
+pycountry/locales/tt@iqtelif/LC_MESSAGES/iso639-3.mo,sha256=YxxQU4qdA0XzR3pAkuN3Uc51vgRopL1uU6SLFuC_rN8,6381
+pycountry/locales/tzm/LC_MESSAGES/iso15924.mo,sha256=VTu9P1hcNVA4i86iD-KsdR-vCY0AF0trsiBx9WPsJ6c,798
+pycountry/locales/tzm/LC_MESSAGES/iso3166-1.mo,sha256=47FJoXYiAjTnUDandgloMWAu1ta07_cBh76jgB0T2MU,608
+pycountry/locales/tzm/LC_MESSAGES/iso4217.mo,sha256=D1sFOG9x4BF1MCCFF6eQulSXi88nqUoRK679W_ZDRL0,371
+pycountry/locales/ug/LC_MESSAGES/iso3166-1.mo,sha256=XQVt-M9x-VTRB1iWsuOURL7SIwiENYt4hjLP6g5ZzJ8,29812
+pycountry/locales/ug/LC_MESSAGES/iso3166-3.mo,sha256=8zmB7JZ74Ns5Ij9bujcs0Ikdpbcp0sPRUVvzSKLHyPo,3467
+pycountry/locales/uk/LC_MESSAGES/iso15924.mo,sha256=MoqwZqWVtxzHJtZohk8WB0JRGhplE5vEatsycFhNiMg,12713
+pycountry/locales/uk/LC_MESSAGES/iso3166-1.mo,sha256=zSv-T1bAy0B0_q5qnMwitrP4CntTCQnRWcMKzVDp9_k,29887
+pycountry/locales/uk/LC_MESSAGES/iso3166-2.mo,sha256=x3BIJcVLF_mQwoFZCdMqLFGyPKOBIlIT4mLs-28VVcM,255945
+pycountry/locales/uk/LC_MESSAGES/iso3166-3.mo,sha256=NB2QqOD1clWnT2yT0ePxA8VzxdgZKdDzxbR0qrwOt4o,3668
+pycountry/locales/uk/LC_MESSAGES/iso4217.mo,sha256=Kj2Ww7jwvurvNC6dvOVvnCUItSlBYrV_ZdXpkzxtMN0,12535
+pycountry/locales/uk/LC_MESSAGES/iso639-3.mo,sha256=wkqhL4HmtRNccl5d-OdGoRbEjZsWQfgg6VyUZhSWPX4,511201
+pycountry/locales/uk/LC_MESSAGES/iso639-5.mo,sha256=12FnzPhOQn1oAZ8sBW7l5POo6QYOlA_FzpdeSlN7oP8,9363
+pycountry/locales/ur/LC_MESSAGES/iso3166-1.mo,sha256=tcC6Dkmh4a9vUhMpVoU2Nbks5oiO-ygU8wcnWE2Tbm8,11711
+pycountry/locales/uz/LC_MESSAGES/iso3166-1.mo,sha256=SQKPadwtPkruf-KXRLkSzo_j4V1DhGwq2JLwPflVQfo,8863
+pycountry/locales/ve/LC_MESSAGES/iso3166-1.mo,sha256=UPng9ItwV8-dFA4Ec6TgV3QVXUFQfsHMgrmA9C8Z2tY,7913
+pycountry/locales/ve/LC_MESSAGES/iso3166-2.mo,sha256=HOuM6pt8cvX2vj49g7-Gn01EIcgis0ffMd82WmbrlvY,924
+pycountry/locales/ve/LC_MESSAGES/iso3166-3.mo,sha256=3NgTS5O5xyhV4eGgQQQfgH1JZB1eKNDS9jpc0WjIyFM,514
+pycountry/locales/ve/LC_MESSAGES/iso639-3.mo,sha256=tzbEkeGyMcCiADL2GaoaaM66NmOcEr__mh0P5sXrvvY,1997
+pycountry/locales/vi/LC_MESSAGES/iso15924.mo,sha256=19Gv8QMvlccPkOy0keeSzz4UedM30N7rMDFy_xL_lGk,7457
+pycountry/locales/vi/LC_MESSAGES/iso3166-1.mo,sha256=ymVEYnAP_TPBhwzWXdhJpYlh6HBmsdbkgMElEZ9CdJs,24644
+pycountry/locales/vi/LC_MESSAGES/iso3166-2.mo,sha256=6HQ4_kJekZWUO-FOKyfhSyZx7himx15XqQFXFvKDwGA,135199
+pycountry/locales/vi/LC_MESSAGES/iso3166-3.mo,sha256=8KWsYZAmqADgIwh2V9CGv4otl0d-O-1fbn3kYuml7tc,2686
+pycountry/locales/vi/LC_MESSAGES/iso4217.mo,sha256=o10Kb3UE8GRTUrtovFCGP3ZHlloGUHWpPC7YYHTk86E,8278
+pycountry/locales/vi/LC_MESSAGES/iso639-3.mo,sha256=QeaUje99ocE7WSsPWQV6xEGwRW4Tr0LnogKem69b6Xg,16925
+pycountry/locales/wa/LC_MESSAGES/iso3166-1.mo,sha256=DY6d4V7EMPpQEbSbyfrmN_8yz6KRzfH9Gc1NTk0cL9Y,22427
+pycountry/locales/wa/LC_MESSAGES/iso3166-2.mo,sha256=-lSDdukzA_xt8Iqtf5d1fsWXY-UrA0muTGBvpzkJZtY,2646
+pycountry/locales/wa/LC_MESSAGES/iso3166-3.mo,sha256=BOO0onmAiuczLLyKkOyy8MasftWeGhwEEnDO3OEubwc,2663
+pycountry/locales/wa/LC_MESSAGES/iso639-3.mo,sha256=RMdySfNZzMfxGr5Wts1TD0gzOT9I7xC49VP7Vm4kS1E,12889
+pycountry/locales/wal/LC_MESSAGES/iso3166-1.mo,sha256=YKTYQvmI4WLckv6MZTnOGhWwoMi2qCeHJ86c2Wr6ja4,5713
+pycountry/locales/wal/LC_MESSAGES/iso3166-3.mo,sha256=_smA6ucdzdYF4JKooYMg0c8KBDAIE8VoLV-iO3DLQ04,476
+pycountry/locales/wo/LC_MESSAGES/iso3166-1.mo,sha256=xCAnRFH-UuZUHqmX3k0bOCC7ErAnsmuJF3UlfMUL6Yk,21638
+pycountry/locales/wo/LC_MESSAGES/iso3166-3.mo,sha256=jmlyZQmJiL1-cU-LConA_8-krM5XfkaOAyob_ED9X7U,2544
+pycountry/locales/xh/LC_MESSAGES/iso3166-1.mo,sha256=rN4Xj7i9i-Bn8jkmLMzY7Tze5ZcuMXs6soNWwI6e-Ts,2821
+pycountry/locales/xh/LC_MESSAGES/iso3166-3.mo,sha256=JQ3G-Jcvv2DlWPnVKHqVXQaBCbFm1B8-QEAxvWSOayc,422
+pycountry/locales/xh/LC_MESSAGES/iso639-3.mo,sha256=b7f1geW_5oIXnTcJdd5EzUHuaZ-oC1x0aqB6M4zc-04,2528
+pycountry/locales/yo/LC_MESSAGES/iso3166-1.mo,sha256=vXJUAuLaCWXvxbmLfdztNJmW7AEfCCoTk6BjAuIiGdo,11032
+pycountry/locales/zh_CN/LC_MESSAGES/iso15924.mo,sha256=73edCLVOwivnJWxbRcqrT0B1suCwpYDmJQw-5ESuZJY,7170
+pycountry/locales/zh_CN/LC_MESSAGES/iso3166-1.mo,sha256=cFvm2thL8VrUOBg_wgRSCNpE8kl5W50oFWU_2ouL8aU,23425
+pycountry/locales/zh_CN/LC_MESSAGES/iso3166-2.mo,sha256=5GXMVkjvIYpLRFCXD6ye7nyKvqinds-4OB5t-FOEfSk,116542
+pycountry/locales/zh_CN/LC_MESSAGES/iso3166-3.mo,sha256=jGDFtKMfZqEVephlYDTyEes8xxpKmnKBHDNWAifoT_s,2696
+pycountry/locales/zh_CN/LC_MESSAGES/iso4217.mo,sha256=K1NVIoFpGsgCLWByDVn9ThoS68my9bu-0BicPSweioI,9620
+pycountry/locales/zh_CN/LC_MESSAGES/iso639-3.mo,sha256=T_LY18QKETT27xLi9OhZEyMig0-MiaYa0V6SXoHjlCk,14527
+pycountry/locales/zh_HK/LC_MESSAGES/iso15924.mo,sha256=Sws2OMrBFpLoDq0U02l5kDyjprNVaSlbg0r-Ip4hQeY,4992
+pycountry/locales/zh_HK/LC_MESSAGES/iso3166-1.mo,sha256=04tOpotVQDSWsiIL1r92Pde5MblNEQcHRntdxhgvW7I,23388
+pycountry/locales/zh_HK/LC_MESSAGES/iso3166-3.mo,sha256=72JQpg5mwgA_5w_YmznbN2NpMGHdsCbN0I3tq30heIA,2714
+pycountry/locales/zh_HK/LC_MESSAGES/iso4217.mo,sha256=DFMqOA2PnPpXRCczQg0ipzmwTA79-815IAee1y78hY8,8815
+pycountry/locales/zh_Hans/LC_MESSAGES/iso639-5.mo,sha256=HfSKsdJZGmr9k-E4OnfWDHPP3bI9Db8dKgBxXKXuJe0,886
+pycountry/locales/zh_Hant/LC_MESSAGES/iso639-5.mo,sha256=MAmFhM-eAAF9PwLmpfJQyCMdfRpATE-eEjQ7KRF3KjA,7424
+pycountry/locales/zh_TW/LC_MESSAGES/iso15924.mo,sha256=rdTojxMvRAvyA-P2mofNpubQBeuw9mQSYA4CCecbJFc,10644
+pycountry/locales/zh_TW/LC_MESSAGES/iso3166-1.mo,sha256=jZHJGmfv_rcv6SI3xWgLLmH_iiWzR_t9eCB4BPxuVO0,23390
+pycountry/locales/zh_TW/LC_MESSAGES/iso3166-2.mo,sha256=hI-cDmSoWhYrzDVx04_sGQkqvrjA1QEzi-O60qA5V9U,18208
+pycountry/locales/zh_TW/LC_MESSAGES/iso3166-3.mo,sha256=tcw6oJie_J4xxELZd-w6rhMuxLdDTEk8kAt95lcqJwI,2685
+pycountry/locales/zh_TW/LC_MESSAGES/iso4217.mo,sha256=lx1x5_mZKbQkC__xebK2v-I55EU4yBh27HhDR9xq2Rg,9664
+pycountry/locales/zh_TW/LC_MESSAGES/iso639-3.mo,sha256=KroXcTbtcwXJubSGfIrloFYskt1cPZPzGVZGBcButNA,32698
+pycountry/locales/zu/LC_MESSAGES/iso3166-1.mo,sha256=MfXG5fBPOFvJHdiGFlSxSPPMijmuLsAAn2xbNRlpoSE,5882
+pycountry/locales/zu/LC_MESSAGES/iso3166-3.mo,sha256=U8swrNDQXoC5L2-ujZdcO68vePFKT6Wn7HQHn3Bmaq4,415
+pycountry/locales/zu/LC_MESSAGES/iso639-3.mo,sha256=Q4EhRCks8BThDf7KzLbMx788L_JsLfUmJ8ZFimyF_FE,2596
+pycountry/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pycountry/tests/__pycache__/test_general.cpython-310.pyc,,
+pycountry/tests/test_general.py,sha256=HLy1GcvTAB1YyMK81XNFdDK1I4VNLrZ6VYCAfjpJ4Wk,15209
diff --git a/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..7c881525d384f1537e81e8a783c8433a748a7089
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/pycountry-24.6.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: poetry-core 1.8.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/METADATA b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..32234a1f6c36db4aeb7511ba0b063b22c720b872
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/METADATA
@@ -0,0 +1,269 @@
+Metadata-Version: 2.4
+Name: RapidFuzz
+Version: 3.14.1
+Summary: rapid fuzzy string matching
+Author-Email: Max Bachmann
+License-Expression: MIT
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Project-URL: Homepage, https://github.com/rapidfuzz/RapidFuzz
+Project-URL: Documentation, https://rapidfuzz.github.io/RapidFuzz/
+Project-URL: Repository, https://github.com/rapidfuzz/RapidFuzz.git
+Project-URL: Issues, https://github.com/rapidfuzz/RapidFuzz/issues
+Project-URL: Changelog, https://github.com/rapidfuzz/RapidFuzz/blob/main/CHANGELOG.rst
+Requires-Python: >=3.10
+Provides-Extra: all
+Requires-Dist: numpy; extra == "all"
+Description-Content-Type: text/markdown
+
+
+
+
+Rapid fuzzy string matching in Python and C++ using the Levenshtein Distance
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Description •
+ Installation •
+ Usage •
+ License
+
+
+---
+
+## Description
+RapidFuzz is a fast string matching library for Python and C++, which is using the string similarity calculations from [FuzzyWuzzy](https://github.com/seatgeek/fuzzywuzzy). However there are a couple of aspects that set RapidFuzz apart from FuzzyWuzzy:
+1) It is MIT licensed so it can be used whichever License you might want to choose for your project, while you're forced to adopt the GPL license when using FuzzyWuzzy
+2) It provides many string_metrics like hamming or jaro_winkler, which are not included in FuzzyWuzzy
+3) It is mostly written in C++ and on top of this comes with a lot of Algorithmic improvements to make string matching even faster, while still providing the same results. For detailed benchmarks check the [documentation](https://rapidfuzz.github.io/RapidFuzz)
+4) Fixes multiple bugs in the `partial_ratio` implementation
+5) It can be largely used as a drop in replacement for `fuzzywuzzy`. However there are a couple API differences described [here](https://github.com/rapidfuzz/RapidFuzz/blob/main/api_differences.md)
+
+## Requirements
+
+- Python 3.10 or later
+- On Windows the [Visual C++ 2019 redistributable](https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads) is required
+
+## Installation
+
+There are several ways to install RapidFuzz, the recommended methods
+are to either use `pip`(the Python package manager) or
+`conda` (an open-source, cross-platform, package manager)
+
+### with pip
+
+RapidFuzz can be installed with `pip` the following way:
+
+```bash
+pip install rapidfuzz
+```
+
+There are pre-built binaries (wheels) of RapidFuzz for MacOS (10.9 and later), Linux x86_64 and Windows. Wheels for armv6l (Raspberry Pi Zero) and armv7l (Raspberry Pi) are available on [piwheels](https://www.piwheels.org/project/rapidfuzz/).
+
+> :heavy_multiplication_x: **failure "ImportError: DLL load failed"**
+>
+> If you run into this error on Windows the reason is most likely, that the [Visual C++ 2019 redistributable](https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads) is not installed, which is required to find C++ Libraries (The C++ 2019 version includes the 2015, 2017 and 2019 version).
+
+### with conda
+
+RapidFuzz can be installed with `conda`:
+
+```bash
+conda install -c conda-forge rapidfuzz
+```
+
+### from git
+RapidFuzz can be installed directly from the source distribution by cloning the repository. This requires a C++17 capable compiler.
+
+```bash
+git clone --recursive https://github.com/rapidfuzz/rapidfuzz.git
+cd rapidfuzz
+pip install .
+```
+
+## Usage
+Some simple functions are shown below. A complete documentation of all functions can be found [here](https://rapidfuzz.github.io/RapidFuzz/Usage/index.html).
+Note that from RapidFuzz 3.0.0, strings are not preprocessed(removing all non alphanumeric characters, trimming whitespaces, converting all characters to lower case) by default. Which means that when comparing two strings that have the same characters but different cases("this is a word", "THIS IS A WORD") their similarity score value might be different, so when comparing such strings you might see a difference in score value compared to previous versions. Some examples of string matching with preprocessing can be found [here](#weighted-ratio).
+
+### Scorers
+Scorers in RapidFuzz can be found in the modules `fuzz` and `distance`.
+
+#### Simple Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.ratio("this is a test", "this is a test!")
+96.55172413793103
+```
+
+#### Partial Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.partial_ratio("this is a test", "this is a test!")
+100.0
+```
+
+#### Token Sort Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
+90.9090909090909
+> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
+100.0
+```
+
+#### Token Set Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear")
+84.21052631578947
+> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear")
+100.0
+# Returns 100.0 if one string is a subset of the other, regardless of extra content in the longer string
+> fuzz.token_set_ratio("fuzzy was a bear but not a dog", "fuzzy was a bear")
+100.0
+# Score is reduced only when there is explicit disagreement in the two strings
+> fuzz.token_set_ratio("fuzzy was a bear but not a dog", "fuzzy was a bear but not a cat")
+92.3076923076923
+```
+
+#### Weighted Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.WRatio("this is a test", "this is a new test!!!")
+85.5
+
+> from rapidfuzz import fuzz, utils
+> # Removing non alpha numeric characters("!") from the string
+> fuzz.WRatio("this is a test", "this is a new test!!!", processor=utils.default_process) # here "this is a new test!!!" is converted to "this is a new test"
+95.0
+> fuzz.WRatio("this is a test", "this is a new test")
+95.0
+
+> # Converting string to lower case
+> fuzz.WRatio("this is a word", "THIS IS A WORD")
+21.42857142857143
+> fuzz.WRatio("this is a word", "THIS IS A WORD", processor=utils.default_process) # here "THIS IS A WORD" is converted to "this is a word"
+100.0
+```
+
+#### Quick Ratio
+```console
+> from rapidfuzz import fuzz
+> fuzz.QRatio("this is a test", "this is a new test!!!")
+80.0
+
+> from rapidfuzz import fuzz, utils
+> # Removing non alpha numeric characters("!") from the string
+> fuzz.QRatio("this is a test", "this is a new test!!!", processor=utils.default_process)
+87.5
+> fuzz.QRatio("this is a test", "this is a new test")
+87.5
+
+> # Converting string to lower case
+> fuzz.QRatio("this is a word", "THIS IS A WORD")
+21.42857142857143
+> fuzz.QRatio("this is a word", "THIS IS A WORD", processor=utils.default_process)
+100.0
+```
+
+### Process
+The process module makes it compare strings to lists of strings. This is generally more
+performant than using the scorers directly from Python.
+Here are some examples on the usage of processors in RapidFuzz:
+
+```console
+> from rapidfuzz import process, fuzz
+> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"]
+> process.extract("new york jets", choices, scorer=fuzz.WRatio, limit=2)
+[('New York Jets', 76.92307692307692, 1), ('New York Giants', 64.28571428571428, 2)]
+> process.extractOne("cowboys", choices, scorer=fuzz.WRatio)
+('Dallas Cowboys', 83.07692307692308, 3)
+
+> # With preprocessing
+> from rapidfuzz import process, fuzz, utils
+> process.extract("new york jets", choices, scorer=fuzz.WRatio, limit=2, processor=utils.default_process)
+[('New York Jets', 100.0, 1), ('New York Giants', 78.57142857142857, 2)]
+> process.extractOne("cowboys", choices, scorer=fuzz.WRatio, processor=utils.default_process)
+('Dallas Cowboys', 90.0, 3)
+```
+
+The full documentation of processors can be found [here](https://rapidfuzz.github.io/RapidFuzz/Usage/process.html)
+
+## Benchmark
+
+The following benchmark gives a quick performance comparison between RapidFuzz and FuzzyWuzzy.
+More detailed benchmarks for the string metrics can be found in the [documentation](https://rapidfuzz.github.io/RapidFuzz). For this simple comparison I generated a list of 10.000 strings with length 10, that is compared to a sample of 100 elements from this list:
+```python
+words = [
+ "".join(random.choice(string.ascii_letters + string.digits) for _ in range(10))
+ for _ in range(10_000)
+]
+samples = words[:: len(words) // 100]
+```
+
+The first benchmark compares the performance of the scorers in FuzzyWuzzy and RapidFuzz when they are used directly
+from Python in the following way:
+```python3
+for sample in samples:
+ for word in words:
+ scorer(sample, word)
+```
+The following graph shows how many elements are processed per second with each of the scorers. There are big performance differences between the different scorers. However each of the scorers is faster in RapidFuzz
+
+
+
+The second benchmark compares the performance when the scorers are used in combination with cdist in the following
+way:
+```python3
+cdist(samples, words, scorer=scorer)
+```
+The following graph shows how many elements are processed per second with each of the scorers. In RapidFuzz the usage of scorers through processors like `cdist` is a lot faster than directly using it. That's why they should be used whenever possible.
+
+
+
+
+## Support the project
+
+If you are using RapidFuzz for your work and feel like giving a bit of your own benefit back to support the project, consider sending us money through GitHub Sponsors or PayPal that we can use to buy us free time for the maintenance of this great library, to fix bugs in the software, review and integrate code contributions, to improve its features and documentation, or to just take a deep breath and have a cup of tea every once in a while. Thank you for your support.
+
+Support the project through [GitHub Sponsors]() or via [PayPal](https://www.paypal.com/donate/?hosted_button_id=VGWQBBD5CTWJU):
+
+[](https://www.paypal.com/donate/?hosted_button_id=VGWQBBD5CTWJU).
+
+## License
+RapidFuzz is licensed under the MIT license since I believe that everyone should be able to use it without being forced to adopt the GPL license. That's why the library is based on an older version of fuzzywuzzy that was MIT licensed as well.
+This old version of fuzzywuzzy can be found [here](https://github.com/seatgeek/fuzzywuzzy/tree/4bf28161f7005f3aa9d4d931455ac55126918df7).
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/RECORD b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..1845dd53c6c7080c4b3d9ae8c3f6d569179b3e02
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/RECORD
@@ -0,0 +1,105 @@
+rapidfuzz-3.14.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+rapidfuzz-3.14.1.dist-info/METADATA,sha256=YhyIDBd6CVw3qeJHSV72tCjuOcDw_mjT1nSZGfmY_YI,12288
+rapidfuzz-3.14.1.dist-info/RECORD,,
+rapidfuzz-3.14.1.dist-info/WHEEL,sha256=LIrydfVXIQZCYHHYt4EvMdM8Vj8KvI9goZ8ya8gIfwM,157
+rapidfuzz-3.14.1.dist-info/entry_points.txt,sha256=hmZhqJhZxrzKpas6tb_kAKUEE9952r4gqkJOV6urvt0,71
+rapidfuzz-3.14.1.dist-info/licenses/LICENSE,sha256=80zN_9_1b8QXeFkV7t8YYB1UeXVd88RyssdUwpgC1oM,1092
+rapidfuzz/__init__.py,sha256=DqpwnSg2HUzjd4XWJS5jCO3XaeuuGv_QDd5gr15ot5s,836
+rapidfuzz/__init__.pyi,sha256=6NNoCowtWGbHBRHZ-KPumXXSpk2x4trPmStDWqk9Oug,201
+rapidfuzz/__pycache__/__init__.cpython-310.pyc,,
+rapidfuzz/__pycache__/_common_py.cpython-310.pyc,,
+rapidfuzz/__pycache__/_feature_detector.cpython-310.pyc,,
+rapidfuzz/__pycache__/_utils.cpython-310.pyc,,
+rapidfuzz/__pycache__/fuzz.cpython-310.pyc,,
+rapidfuzz/__pycache__/fuzz_py.cpython-310.pyc,,
+rapidfuzz/__pycache__/process.cpython-310.pyc,,
+rapidfuzz/__pycache__/process_cpp.cpython-310.pyc,,
+rapidfuzz/__pycache__/process_py.cpython-310.pyc,,
+rapidfuzz/__pycache__/utils.cpython-310.pyc,,
+rapidfuzz/__pycache__/utils_py.cpython-310.pyc,,
+rapidfuzz/__pyinstaller/__init__.py,sha256=eNjMZIHLEdeArOmqjRgXrhkxskvxgAQJoWcqg-ceqPs,132
+rapidfuzz/__pyinstaller/__pycache__/__init__.cpython-310.pyc,,
+rapidfuzz/__pyinstaller/__pycache__/test_rapidfuzz_packaging.cpython-310.pyc,,
+rapidfuzz/__pyinstaller/test_rapidfuzz_packaging.py,sha256=iBssItCNdVZpr7JWDJt5z7dIUsydlruuPs2qeLpFg5k,1114
+rapidfuzz/_common_py.py,sha256=xbcjDP1g8-Xk8IkHwIp_Cd4ep_K3HSwFcbhzSKb5jiE,1773
+rapidfuzz/_feature_detector.py,sha256=vTnfTB-Jfljbrupxsvsa5AQcZAkGHg7FXBg0pI3_YVg,332
+rapidfuzz/_feature_detector_cpp.cpython-310-x86_64-linux-gnu.so,sha256=7Bau0JQ9_3AsYWVfgkginqpb7sunnCRMRj9VmZo5shE,41240
+rapidfuzz/_utils.py,sha256=SuK1Mrl3MFhCORFJvpcrTqzUqkiLtNiVT42J_m5SwGk,2307
+rapidfuzz/distance/DamerauLevenshtein.py,sha256=LicvoaIad4CawQuKnG7UJPgNV7yL20lNXfj1CkLtmkg,4055
+rapidfuzz/distance/DamerauLevenshtein.pyi,sha256=bMR0Hm2512jXdcBXxTfPQOZwnJonCIY8X2RJfkXsEzg,1904
+rapidfuzz/distance/DamerauLevenshtein_py.py,sha256=-zdMM4vv70Dk5VHAhbjeB5TpOd6-Y0bFS0uYbSBB9Fk,6591
+rapidfuzz/distance/Hamming.py,sha256=_dj9-1ubfqtKCA2h7JtzZa9NfhIKfbfStNerCuwvSGA,4392
+rapidfuzz/distance/Hamming.pyi,sha256=TjoXt9lysM9-ZOedijCii50xGGdjGlz239LWx0wbYeY,2769
+rapidfuzz/distance/Hamming_py.py,sha256=FAeokMCOcW3Ub8XlO6tsHWWpdJWSUKVbJCNZCnP-pmI,9081
+rapidfuzz/distance/Indel.py,sha256=C-ZCyD3dOamKIvt1ltNDroKPSqbMh4zC4FaudhdvHko,4296
+rapidfuzz/distance/Indel.pyi,sha256=xjs1sdft7AcbHOh9rp9pH0FamAf_TrN2qyWBdMXk-NE,2593
+rapidfuzz/distance/Indel_py.py,sha256=oE-hmb92o-a5xYU3bj6UQtvUljJ4Cf6VYjXAIwStzWA,9935
+rapidfuzz/distance/Jaro.py,sha256=kjB_r6CBVJfUjRiCiRkDrtdloVQ9ak2hUQB44nIlvN0,3575
+rapidfuzz/distance/Jaro.pyi,sha256=IpjLgvh73jalJiMMNqwc6TSmk7U9yE_JXLP3Q5605GM,1908
+rapidfuzz/distance/JaroWinkler.py,sha256=3RRZ4BNt9Rs4KALgQNYsp8HCBZ4BdMxMOcirnMGwxvo,3831
+rapidfuzz/distance/JaroWinkler.pyi,sha256=5XC-Y5fYFnmINM0Dw29BgRUvzFfnG07HVruCrwL4MF8,2164
+rapidfuzz/distance/JaroWinkler_py.py,sha256=CJA9ImEQPGqRToXgjejdUES93L5JRZf9gGkbVuX6AbU,6481
+rapidfuzz/distance/Jaro_py.py,sha256=1mexVsftTGRzhjctfUHuaG3D8M8T9oADuO9CqKoileU,7345
+rapidfuzz/distance/LCSseq.py,sha256=tg62FG8PzPxYGdhx428xUfcd8cgEalB_hmqxc5K-Zcw,4392
+rapidfuzz/distance/LCSseq.pyi,sha256=xjs1sdft7AcbHOh9rp9pH0FamAf_TrN2qyWBdMXk-NE,2593
+rapidfuzz/distance/LCSseq_py.py,sha256=mH3JXKvXllXX3Ts6daGfdDKGWo5V1xHkI9RyWGVVw5E,11504
+rapidfuzz/distance/Levenshtein.py,sha256=UJGLcs9dXL25kOjbi6TOCUHXf6uGMlGTWSotxRXf3JU,4584
+rapidfuzz/distance/Levenshtein.pyi,sha256=7C-nWn_yEORoj-Ioow0BsmaLnpKH7ej_5smykFtwcnM,3678
+rapidfuzz/distance/Levenshtein_py.py,sha256=f4gag2BCACSGXPVe0gnGnYf5CDLAdyqhvf5cUl9ptRU,17103
+rapidfuzz/distance/OSA.py,sha256=DzkSlRrEThCf8zc9OCI5tgNqGAzusWcn5cYE2RAVK64,3543
+rapidfuzz/distance/OSA.pyi,sha256=bMR0Hm2512jXdcBXxTfPQOZwnJonCIY8X2RJfkXsEzg,1904
+rapidfuzz/distance/OSA_py.py,sha256=BGD49wAjNbA5xqhrUID4vkA7yaeJ3jXljsE60SWbEig,6251
+rapidfuzz/distance/Postfix.py,sha256=QoTlbLgjj61CDM_rycFDoap3gARRWXOu6vwIw41Y0QE,3671
+rapidfuzz/distance/Postfix.pyi,sha256=bMR0Hm2512jXdcBXxTfPQOZwnJonCIY8X2RJfkXsEzg,1904
+rapidfuzz/distance/Postfix_py.py,sha256=ywWO0M5swCWkjZqjp2wKMEZ7_GV8Z91IRMe8_zZGeaQ,5039
+rapidfuzz/distance/Prefix.py,sha256=2Iu577WnaYCHCQd8it76gDk60QxRdlFo0cQBItCZzWw,3639
+rapidfuzz/distance/Prefix.pyi,sha256=bMR0Hm2512jXdcBXxTfPQOZwnJonCIY8X2RJfkXsEzg,1904
+rapidfuzz/distance/Prefix_py.py,sha256=mHtW3wRD0jol76NnDOgIALMvslINtGJJ9ipZ713sldQ,5015
+rapidfuzz/distance/__init__.py,sha256=gphKWTUI2CW-4OY_A9AOgz0db_sb4kxSqRr20PxsX2w,621
+rapidfuzz/distance/__init__.pyi,sha256=wX594ohPZ4gASmvKpbovDWH2BB9IcVojRqtF0yPjzvg,571
+rapidfuzz/distance/__pycache__/DamerauLevenshtein.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/DamerauLevenshtein_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Hamming.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Hamming_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Indel.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Indel_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Jaro.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/JaroWinkler.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/JaroWinkler_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Jaro_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/LCSseq.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/LCSseq_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Levenshtein.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Levenshtein_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/OSA.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/OSA_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Postfix.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Postfix_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Prefix.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/Prefix_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/__init__.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/_initialize.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/_initialize_py.cpython-310.pyc,,
+rapidfuzz/distance/__pycache__/metrics_py.cpython-310.pyc,,
+rapidfuzz/distance/_initialize.py,sha256=UKwKITEVDTvj7MiWNsmPJBDN7xgowVwlzKllEjDzpoA,3074
+rapidfuzz/distance/_initialize.pyi,sha256=N7ooznQtrQhZKNZ1UGtjUyf6LiP_vbtSCWFa49K9fJA,3998
+rapidfuzz/distance/_initialize_cpp.cpython-310-x86_64-linux-gnu.so,sha256=HoCy8LV0eSMmiEoi4s3O6HyiTPKTG93ytSPv39p7p04,310456
+rapidfuzz/distance/_initialize_py.py,sha256=I_z-54avD84EE1HA7KjT8and4GHOQI-o2tK9ZG6eYsI,26320
+rapidfuzz/distance/metrics_cpp.cpython-310-x86_64-linux-gnu.so,sha256=ayIaSl0qRf_YHS3yW5yrAYa0qV2se3sGagp0gLMR400,2984328
+rapidfuzz/distance/metrics_cpp_avx2.cpython-310-x86_64-linux-gnu.so,sha256=-iFVTAu3jCPDJCS7wqGEQ-D0snijOGZuL6M_qPiY7nA,3053928
+rapidfuzz/distance/metrics_py.py,sha256=GEfDOAgkX-vKrdNA0mx47_ji286YPYvh6zkXa2by0vw,9037
+rapidfuzz/fuzz.py,sha256=gkOM8b_kJ5yaq1er_sAqXJP6wbZJon9msV2L6EwGS24,4625
+rapidfuzz/fuzz.pyi,sha256=8I3AJtX50VlobaAgFtqiXg1-pbzaRA9dFSKezv7zgUU,4811
+rapidfuzz/fuzz_cpp.cpython-310-x86_64-linux-gnu.so,sha256=kJihD40x9S-0vpwbMfV_pQQmgl7chIlDPtyANbueu8Y,2204840
+rapidfuzz/fuzz_cpp_avx2.cpython-310-x86_64-linux-gnu.so,sha256=30bK4votcVgq_HFX75hZJHJckSvOS_XtzeDO4dIKr5E,2221224
+rapidfuzz/fuzz_py.py,sha256=pa2UsGF7CW-fOyIcGgv_lPtLB6eVbuUqGlIA4ux2YKw,25826
+rapidfuzz/process.py,sha256=JylT-tYBhwP566p0zO-O2ZT0p-0kW3cCUgbnCCOoVcQ,2672
+rapidfuzz/process.pyi,sha256=B8qM_VOu8RCvdZAA7tNhBn9W7oB2KJfT_U5qeB9BQzQ,17246
+rapidfuzz/process_cpp.py,sha256=uAXbHd_UVG0yOaFvVbZKgZzQLpDWteIJxCsY6MeURKU,2530
+rapidfuzz/process_cpp_impl.cpython-310-x86_64-linux-gnu.so,sha256=ppMWitTwTJ-dl0JcM7H9M7RG1XTWQ7DysnSXf8e477I,688008
+rapidfuzz/process_py.py,sha256=di2AS2En6VzIrpog2H-vsvauaYnMZxB4aWB59mKY7ns,26646
+rapidfuzz/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+rapidfuzz/utils.py,sha256=7rs2NCCSL2_mandvxSEkcly5WWb0RR4gxKOdYZJiavE,1910
+rapidfuzz/utils.pyi,sha256=rz2lxhxQu-Bm6gPxBDjwBbNs2oBBjArP6PEYlWcaE5Q,304
+rapidfuzz/utils_cpp.cpython-310-x86_64-linux-gnu.so,sha256=62_RA9xVx0i0tyHd1Gym9PzxN7YG7pX7f2ywt17KESs,217688
+rapidfuzz/utils_py.py,sha256=oP6xgOsopkR0NhNjf3u6x55gw03LUMJ1zh2FYIsxno4,622
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/WHEEL b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..4965c415356d551b9e18241c2d1eb8e7bb401972
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: scikit-build-core 0.11.6
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_27_x86_64
+Tag: cp310-cp310-manylinux_2_28_x86_64
+
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f18f2d377871b5d76321e2f50da8e3c3814abc88
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/entry_points.txt
@@ -0,0 +1,3 @@
+[pyinstaller40]
+tests = rapidfuzz.__pyinstaller:get_PyInstaller_tests
+
diff --git a/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..42c23b2103346d5439dd72582ed6d4a0d8d7b27b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rapidfuzz-3.14.1.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+Copyright © 2020-present Max Bachmann
+Copyright © 2011 Adam Cohen
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/rignore/__init__.py b/venv/lib/python3.10/site-packages/rignore/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3874273a9ab5c5d36df2c5f1c3521edf18089952
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rignore/__init__.py
@@ -0,0 +1,5 @@
+from .rignore import *
+
+__doc__ = rignore.__doc__
+if hasattr(rignore, "__all__"):
+ __all__ = rignore.__all__
\ No newline at end of file
diff --git a/venv/lib/python3.10/site-packages/rignore/__init__.pyi b/venv/lib/python3.10/site-packages/rignore/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..a979954fdfec3df7ad049b8094fc8135607bc55d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rignore/__init__.pyi
@@ -0,0 +1,44 @@
+from pathlib import Path
+from typing import Callable, Iterator, List, Optional
+
+class Walker:
+ def __init__(
+ self,
+ path: Path,
+ ignore_hidden: Optional[bool] = None,
+ read_ignore_files: Optional[bool] = None,
+ read_parents_ignores: Optional[bool] = None,
+ read_git_ignore: Optional[bool] = None,
+ read_global_git_ignore: Optional[bool] = None,
+ read_git_exclude: Optional[bool] = None,
+ require_git: Optional[bool] = None,
+ additional_ignores: Optional[List[str]] = None,
+ additional_ignore_paths: Optional[List[str]] = None,
+ max_depth: Optional[int] = None,
+ max_filesize: Optional[int] = None,
+ follow_links: Optional[bool] = None,
+ case_insensitive: Optional[bool] = None,
+ same_file_system: Optional[bool] = None,
+ should_exclude_entry: Optional[Callable[[Path], bool]] = None,
+ ) -> None: ...
+ def __iter__(self) -> Iterator[Path]: ...
+ def __next__(self) -> Optional[Path]: ...
+
+def walk(
+ path: Path,
+ ignore_hidden: Optional[bool] = None,
+ read_ignore_files: Optional[bool] = None,
+ read_parents_ignores: Optional[bool] = None,
+ read_git_ignore: Optional[bool] = None,
+ read_global_git_ignore: Optional[bool] = None,
+ read_git_exclude: Optional[bool] = None,
+ require_git: Optional[bool] = None,
+ additional_ignores: Optional[List[str]] = None,
+ additional_ignore_paths: Optional[List[str]] = None,
+ max_depth: Optional[int] = None,
+ max_filesize: Optional[int] = None,
+ follow_links: Optional[bool] = None,
+ case_insensitive: Optional[bool] = None,
+ same_file_system: Optional[bool] = None,
+ should_exclude_entry: Optional[Callable[[Path], bool]] = None,
+) -> Walker: ...
diff --git a/venv/lib/python3.10/site-packages/rignore/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/rignore/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5544eec2ae2bf711661bcfbc95c4ab6b077f56c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/rignore/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/rignore/py.typed b/venv/lib/python3.10/site-packages/rignore/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..3a143494b232bb8931f107ac7af7958b33960018
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/METADATA
@@ -0,0 +1,100 @@
+Metadata-Version: 2.4
+Name: rpds-py
+Version: 0.27.0
+Classifier: Development Status :: 3 - Alpha
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Rust
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+License-File: LICENSE
+Summary: Python bindings to Rust's persistent data structures (rpds)
+Keywords: data structures,rust,persistent
+Author-email: Julian Berman
+License-Expression: MIT
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst; charset=UTF-8
+Project-URL: Documentation, https://rpds.readthedocs.io/
+Project-URL: Homepage, https://github.com/crate-py/rpds
+Project-URL: Issues, https://github.com/crate-py/rpds/issues/
+Project-URL: Funding, https://github.com/sponsors/Julian
+Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-rpds-py?utm_source=pypi-rpds-py&utm_medium=referral&utm_campaign=pypi-link
+Project-URL: Source, https://github.com/crate-py/rpds
+Project-URL: Upstream, https://github.com/orium/rpds
+
+===========
+``rpds.py``
+===========
+
+|PyPI| |Pythons| |CI|
+
+.. |PyPI| image:: https://img.shields.io/pypi/v/rpds-py.svg
+ :alt: PyPI version
+ :target: https://pypi.org/project/rpds-py/
+
+.. |Pythons| image:: https://img.shields.io/pypi/pyversions/rpds-py.svg
+ :alt: Supported Python versions
+ :target: https://pypi.org/project/rpds-py/
+
+.. |CI| image:: https://github.com/crate-py/rpds/workflows/CI/badge.svg
+ :alt: Build status
+ :target: https://github.com/crate-py/rpds/actions?query=workflow%3ACI
+
+.. |ReadTheDocs| image:: https://readthedocs.org/projects/referencing/badge/?version=stable&style=flat
+ :alt: ReadTheDocs status
+ :target: https://referencing.readthedocs.io/en/stable/
+
+
+Python bindings to the `Rust rpds crate `_ for persistent data structures.
+
+What's here is quite minimal (in transparency, it was written initially to support replacing ``pyrsistent`` in the `referencing library `_).
+If you see something missing (which is very likely), a PR is definitely welcome to add it.
+
+Installation
+------------
+
+The distribution on PyPI is named ``rpds.py`` (equivalently ``rpds-py``), and thus can be installed via e.g.:
+
+.. code:: sh
+
+ $ pip install rpds-py
+
+Note that if you install ``rpds-py`` from source, you will need a Rust toolchain installed, as it is a build-time dependency.
+An example of how to do so in a ``Dockerfile`` can be found `here `_.
+
+If you believe you are on a common platform which should have wheels built (i.e. and not need to compile from source), feel free to file an issue or pull request modifying the GitHub action used here to build wheels via ``maturin``.
+
+Usage
+-----
+
+Methods in general are named similarly to their ``rpds`` counterparts (rather than ``pyrsistent``\ 's conventions, though probably a full drop-in ``pyrsistent``\ -compatible wrapper module is a good addition at some point).
+
+.. code:: python
+
+ >>> from rpds import HashTrieMap, HashTrieSet, List
+
+ >>> m = HashTrieMap({"foo": "bar", "baz": "quux"})
+ >>> m.insert("spam", 37) == HashTrieMap({"foo": "bar", "baz": "quux", "spam": 37})
+ True
+ >>> m.remove("foo") == HashTrieMap({"baz": "quux"})
+ True
+
+ >>> s = HashTrieSet({"foo", "bar", "baz", "quux"})
+ >>> s.insert("spam") == HashTrieSet({"foo", "bar", "baz", "quux", "spam"})
+ True
+ >>> s.remove("foo") == HashTrieSet({"bar", "baz", "quux"})
+ True
+
+ >>> L = List([1, 3, 5])
+ >>> L.push_front(-1) == List([-1, 1, 3, 5])
+ True
+ >>> L.rest == List([3, 5])
+ True
+
diff --git a/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..df20124877551aafc1d4205ac112d3fc5e52a638
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/RECORD
@@ -0,0 +1,10 @@
+rpds/__init__.py,sha256=w3MgXW7lpTCICw0KXbw20QX573_kbsEnWIeMsCAugvM,99
+rpds/__init__.pyi,sha256=-hd1A1d1BqGxL3XZGI9SpW1-xZe2iJcDMU6CpiejgV4,2570
+rpds/__pycache__/__init__.cpython-310.pyc,,
+rpds/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+rpds/rpds.cpython-310-x86_64-linux-gnu.so,sha256=v6omZ8x5XYXqGk0cg4fVHu0LLGuUCe6qLCwygFpKrhY,1028248
+rpds_py-0.27.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+rpds_py-0.27.0.dist-info/METADATA,sha256=20lurnkDeUz8hZ1Ho7c3qcdA7sUIw14msdGcAIggijY,4194
+rpds_py-0.27.0.dist-info/RECORD,,
+rpds_py-0.27.0.dist-info/WHEEL,sha256=eVFlkE1vBrKFbMiva8QY5dljMhlrWHHdD9pKbf8maq4,129
+rpds_py-0.27.0.dist-info/licenses/LICENSE,sha256=MU5Okb47qpPA-0vMyeTpfNZD64ObBlr5IXgsIXX-mQk,1057
diff --git a/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..b3fa2801e450c965844b53f64f731d31628f8cd0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: maturin (1.9.3)
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64
diff --git a/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..119a1f205aa85f584e0dbc04d7b34deaebe9199d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/rpds_py-0.27.0.dist-info/licenses/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2023 Julian Berman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/shellingham/__init__.py b/venv/lib/python3.10/site-packages/shellingham/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..15f7a90cbd02e5c2cc933cf6aa0374cca68035f1
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/__init__.py
@@ -0,0 +1,23 @@
+import importlib
+import os
+
+from ._core import ShellDetectionFailure
+
+__version__ = "1.5.4"
+
+
+def detect_shell(pid=None, max_depth=10):
+ name = os.name
+ try:
+ impl = importlib.import_module(".{}".format(name), __name__)
+ except ImportError:
+ message = "Shell detection not implemented for {0!r}".format(name)
+ raise RuntimeError(message)
+ try:
+ get_shell = impl.get_shell
+ except AttributeError:
+ raise RuntimeError("get_shell not implemented for {0!r}".format(name))
+ shell = get_shell(pid, max_depth=max_depth)
+ if shell:
+ return shell
+ raise ShellDetectionFailure()
diff --git a/venv/lib/python3.10/site-packages/shellingham/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0f517ba6ac62be9d09a97ad3397317dce29ef12
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/__pycache__/_core.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/__pycache__/_core.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6b67922a7a0831d2dd2171a45ab0a3a4b0b9446
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/__pycache__/_core.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/__pycache__/nt.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/__pycache__/nt.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c2ff2c452ad9ed7e5f6c274b79c1097babb6306
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/__pycache__/nt.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/_core.py b/venv/lib/python3.10/site-packages/shellingham/_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..13b65417c733b54e48b120e37f573c2baa6ef72b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/_core.py
@@ -0,0 +1,11 @@
+SHELL_NAMES = (
+ {"sh", "bash", "dash", "ash"} # Bourne.
+ | {"csh", "tcsh"} # C.
+ | {"ksh", "zsh", "fish"} # Common alternatives.
+ | {"cmd", "powershell", "pwsh"} # Microsoft.
+ | {"elvish", "xonsh", "nu"} # More exotic.
+)
+
+
+class ShellDetectionFailure(EnvironmentError):
+ pass
diff --git a/venv/lib/python3.10/site-packages/shellingham/nt.py b/venv/lib/python3.10/site-packages/shellingham/nt.py
new file mode 100644
index 0000000000000000000000000000000000000000..389551b223a761fa2f97e929b60bf3ca5baed94c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/nt.py
@@ -0,0 +1,163 @@
+import contextlib
+import ctypes
+import os
+
+from ctypes.wintypes import (
+ BOOL,
+ CHAR,
+ DWORD,
+ HANDLE,
+ LONG,
+ LPWSTR,
+ MAX_PATH,
+ PDWORD,
+ ULONG,
+)
+
+from shellingham._core import SHELL_NAMES
+
+
+INVALID_HANDLE_VALUE = HANDLE(-1).value
+ERROR_NO_MORE_FILES = 18
+ERROR_INSUFFICIENT_BUFFER = 122
+TH32CS_SNAPPROCESS = 2
+PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
+
+
+kernel32 = ctypes.windll.kernel32
+
+
+def _check_handle(error_val=0):
+ def check(ret, func, args):
+ if ret == error_val:
+ raise ctypes.WinError()
+ return ret
+
+ return check
+
+
+def _check_expected(expected):
+ def check(ret, func, args):
+ if ret:
+ return True
+ code = ctypes.GetLastError()
+ if code == expected:
+ return False
+ raise ctypes.WinError(code)
+
+ return check
+
+
+class ProcessEntry32(ctypes.Structure):
+ _fields_ = (
+ ("dwSize", DWORD),
+ ("cntUsage", DWORD),
+ ("th32ProcessID", DWORD),
+ ("th32DefaultHeapID", ctypes.POINTER(ULONG)),
+ ("th32ModuleID", DWORD),
+ ("cntThreads", DWORD),
+ ("th32ParentProcessID", DWORD),
+ ("pcPriClassBase", LONG),
+ ("dwFlags", DWORD),
+ ("szExeFile", CHAR * MAX_PATH),
+ )
+
+
+kernel32.CloseHandle.argtypes = [HANDLE]
+kernel32.CloseHandle.restype = BOOL
+
+kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
+kernel32.CreateToolhelp32Snapshot.restype = HANDLE
+kernel32.CreateToolhelp32Snapshot.errcheck = _check_handle( # type: ignore
+ INVALID_HANDLE_VALUE,
+)
+
+kernel32.Process32First.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]
+kernel32.Process32First.restype = BOOL
+kernel32.Process32First.errcheck = _check_expected( # type: ignore
+ ERROR_NO_MORE_FILES,
+)
+
+kernel32.Process32Next.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]
+kernel32.Process32Next.restype = BOOL
+kernel32.Process32Next.errcheck = _check_expected( # type: ignore
+ ERROR_NO_MORE_FILES,
+)
+
+kernel32.GetCurrentProcessId.argtypes = []
+kernel32.GetCurrentProcessId.restype = DWORD
+
+kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD]
+kernel32.OpenProcess.restype = HANDLE
+kernel32.OpenProcess.errcheck = _check_handle( # type: ignore
+ INVALID_HANDLE_VALUE,
+)
+
+kernel32.QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, PDWORD]
+kernel32.QueryFullProcessImageNameW.restype = BOOL
+kernel32.QueryFullProcessImageNameW.errcheck = _check_expected( # type: ignore
+ ERROR_INSUFFICIENT_BUFFER,
+)
+
+
+@contextlib.contextmanager
+def _handle(f, *args, **kwargs):
+ handle = f(*args, **kwargs)
+ try:
+ yield handle
+ finally:
+ kernel32.CloseHandle(handle)
+
+
+def _iter_processes():
+ f = kernel32.CreateToolhelp32Snapshot
+ with _handle(f, TH32CS_SNAPPROCESS, 0) as snap:
+ entry = ProcessEntry32()
+ entry.dwSize = ctypes.sizeof(entry)
+ ret = kernel32.Process32First(snap, entry)
+ while ret:
+ yield entry
+ ret = kernel32.Process32Next(snap, entry)
+
+
+def _get_full_path(proch):
+ size = DWORD(MAX_PATH)
+ while True:
+ path_buff = ctypes.create_unicode_buffer("", size.value)
+ if kernel32.QueryFullProcessImageNameW(proch, 0, path_buff, size):
+ return path_buff.value
+ size.value *= 2
+
+
+def get_shell(pid=None, max_depth=10):
+ proc_map = {
+ proc.th32ProcessID: (proc.th32ParentProcessID, proc.szExeFile)
+ for proc in _iter_processes()
+ }
+ pid = pid or os.getpid()
+
+ for _ in range(0, max_depth + 1):
+ try:
+ ppid, executable = proc_map[pid]
+ except KeyError: # No such process? Give up.
+ break
+
+ # The executable name would be encoded with the current code page if
+ # we're in ANSI mode (usually). Try to decode it into str/unicode,
+ # replacing invalid characters to be safe (not thoeratically necessary,
+ # I think). Note that we need to use 'mbcs' instead of encoding
+ # settings from sys because this is from the Windows API, not Python
+ # internals (which those settings reflect). (pypa/pipenv#3382)
+ if isinstance(executable, bytes):
+ executable = executable.decode("mbcs", "replace")
+
+ name = executable.rpartition(".")[0].lower()
+ if name not in SHELL_NAMES:
+ pid = ppid
+ continue
+
+ key = PROCESS_QUERY_LIMITED_INFORMATION
+ with _handle(kernel32.OpenProcess, key, 0, pid) as proch:
+ return (name, _get_full_path(proch))
+
+ return None
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/__init__.py b/venv/lib/python3.10/site-packages/shellingham/posix/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bd2070db27189e62a1867e4de49f16f8c8841ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/posix/__init__.py
@@ -0,0 +1,112 @@
+import os
+import re
+
+from .._core import SHELL_NAMES, ShellDetectionFailure
+from . import proc, ps
+
+# Based on QEMU docs: https://www.qemu.org/docs/master/user/main.html
+QEMU_BIN_REGEX = re.compile(
+ r"""qemu-
+ (alpha
+ |armeb
+ |arm
+ |m68k
+ |cris
+ |i386
+ |x86_64
+ |microblaze
+ |mips
+ |mipsel
+ |mips64
+ |mips64el
+ |mipsn32
+ |mipsn32el
+ |nios2
+ |ppc64
+ |ppc
+ |sh4eb
+ |sh4
+ |sparc
+ |sparc32plus
+ |sparc64
+ )""",
+ re.VERBOSE,
+)
+
+
+def _iter_process_parents(pid, max_depth=10):
+ """Select a way to obtain process information from the system.
+
+ * `/proc` is used if supported.
+ * The system `ps` utility is used as a fallback option.
+ """
+ for impl in (proc, ps):
+ try:
+ iterator = impl.iter_process_parents(pid, max_depth)
+ except EnvironmentError:
+ continue
+ return iterator
+ raise ShellDetectionFailure("compatible proc fs or ps utility is required")
+
+
+def _get_login_shell(proc_cmd):
+ """Form shell information from SHELL environ if possible."""
+ login_shell = os.environ.get("SHELL", "")
+ if login_shell:
+ proc_cmd = login_shell
+ else:
+ proc_cmd = proc_cmd[1:]
+ return (os.path.basename(proc_cmd).lower(), proc_cmd)
+
+
+_INTERPRETER_SHELL_NAMES = [
+ (re.compile(r"^python(\d+(\.\d+)?)?$"), {"xonsh"}),
+]
+
+
+def _get_interpreter_shell(proc_name, proc_args):
+ """Get shell invoked via an interpreter.
+
+ Some shells are implemented on, and invoked with an interpreter, e.g. xonsh
+ is commonly executed with an executable Python script. This detects what
+ script the interpreter is actually running, and check whether that looks
+ like a shell.
+
+ See sarugaku/shellingham#26 for rational.
+ """
+ for pattern, shell_names in _INTERPRETER_SHELL_NAMES:
+ if not pattern.match(proc_name):
+ continue
+ for arg in proc_args:
+ name = os.path.basename(arg).lower()
+ if os.path.isfile(arg) and name in shell_names:
+ return (name, arg)
+ return None
+
+
+def _get_shell(cmd, *args):
+ if cmd.startswith("-"): # Login shell! Let's use this.
+ return _get_login_shell(cmd)
+ name = os.path.basename(cmd).lower()
+ if name == "rosetta" or QEMU_BIN_REGEX.fullmatch(name):
+ # If the current process is Rosetta or QEMU, this likely is a
+ # containerized process. Parse out the actual command instead.
+ cmd = args[0]
+ args = args[1:]
+ name = os.path.basename(cmd).lower()
+ if name in SHELL_NAMES: # Command looks like a shell.
+ return (name, cmd)
+ shell = _get_interpreter_shell(name, args)
+ if shell:
+ return shell
+ return None
+
+
+def get_shell(pid=None, max_depth=10):
+ """Get the shell that the supplied pid or os.getpid() is running in."""
+ pid = str(pid or os.getpid())
+ for proc_args, _, _ in _iter_process_parents(pid, max_depth):
+ shell = _get_shell(*proc_args)
+ if shell:
+ return shell
+ return None
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f82fa03feebafeb4b4f53613692e7d3d2005fe0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/_core.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/_core.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..264c28a72bed8894b833b3185b9fa017fb8b2f61
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/_core.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/proc.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/proc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b1ca339bc363a20c0bf8c5343dfe21e40dec17e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/proc.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/ps.cpython-310.pyc b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/ps.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e474fa2e1ab7aeae847206a8fafa20b9d075cee
Binary files /dev/null and b/venv/lib/python3.10/site-packages/shellingham/posix/__pycache__/ps.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/_core.py b/venv/lib/python3.10/site-packages/shellingham/posix/_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..adc49e6e7a9d3edf062c55e0078136899f78d30d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/posix/_core.py
@@ -0,0 +1,3 @@
+import collections
+
+Process = collections.namedtuple("Process", "args pid ppid")
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/proc.py b/venv/lib/python3.10/site-packages/shellingham/posix/proc.py
new file mode 100644
index 0000000000000000000000000000000000000000..950f63228e5b328f82b70da8851ec60c6a2ff029
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/posix/proc.py
@@ -0,0 +1,83 @@
+import io
+import os
+import re
+import sys
+
+from ._core import Process
+
+# FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=procfs
+# NetBSD: https://man.netbsd.org/NetBSD-9.3-STABLE/mount_procfs.8
+# DragonFlyBSD: https://www.dragonflybsd.org/cgi/web-man?command=procfs
+BSD_STAT_PPID = 2
+
+# See https://docs.kernel.org/filesystems/proc.html
+LINUX_STAT_PPID = 3
+
+STAT_PATTERN = re.compile(r"\(.+\)|\S+")
+
+
+def detect_proc():
+ """Detect /proc filesystem style.
+
+ This checks the /proc/{pid} directory for possible formats. Returns one of
+ the following as str:
+
+ * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.
+ * `status`: BSD-style, i.e. ``/proc/{pid}/status``.
+ """
+ pid = os.getpid()
+ for name in ("stat", "status"):
+ if os.path.exists(os.path.join("/proc", str(pid), name)):
+ return name
+ raise ProcFormatError("unsupported proc format")
+
+
+def _use_bsd_stat_format():
+ try:
+ return os.uname().sysname.lower() in ("freebsd", "netbsd", "dragonfly")
+ except Exception:
+ return False
+
+
+def _get_ppid(pid, name):
+ path = os.path.join("/proc", str(pid), name)
+ with io.open(path, encoding="ascii", errors="replace") as f:
+ parts = STAT_PATTERN.findall(f.read())
+ # We only care about TTY and PPID -- both are numbers.
+ if _use_bsd_stat_format():
+ return parts[BSD_STAT_PPID]
+ return parts[LINUX_STAT_PPID]
+
+
+def _get_cmdline(pid):
+ path = os.path.join("/proc", str(pid), "cmdline")
+ encoding = sys.getfilesystemencoding() or "utf-8"
+ with io.open(path, encoding=encoding, errors="replace") as f:
+ # XXX: Command line arguments can be arbitrary byte sequences, not
+ # necessarily decodable. For Shellingham's purpose, however, we don't
+ # care. (pypa/pipenv#2820)
+ # cmdline appends an extra NULL at the end, hence the [:-1].
+ return tuple(f.read().split("\0")[:-1])
+
+
+class ProcFormatError(EnvironmentError):
+ pass
+
+
+def iter_process_parents(pid, max_depth=10):
+ """Try to look up the process tree via the /proc interface."""
+ stat_name = detect_proc()
+
+ # Inner generator function so we correctly throw an error eagerly if proc
+ # is not supported, rather than on the first call to the iterator. This
+ # allows the call site detects the correct implementation.
+ def _iter_process_parents(pid, max_depth):
+ for _ in range(max_depth):
+ ppid = _get_ppid(pid, stat_name)
+ args = _get_cmdline(pid)
+ yield Process(args=args, pid=pid, ppid=ppid)
+ if ppid == "0":
+ break
+ pid = ppid
+
+ return _iter_process_parents(pid, max_depth)
diff --git a/venv/lib/python3.10/site-packages/shellingham/posix/ps.py b/venv/lib/python3.10/site-packages/shellingham/posix/ps.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bc39a74a56390c263e63bfead028f6bce4df3cb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/shellingham/posix/ps.py
@@ -0,0 +1,51 @@
+import errno
+import subprocess
+import sys
+
+from ._core import Process
+
+
+class PsNotAvailable(EnvironmentError):
+ pass
+
+
+def iter_process_parents(pid, max_depth=10):
+ """Try to look up the process tree via the output of `ps`."""
+ try:
+ cmd = ["ps", "-ww", "-o", "pid=", "-o", "ppid=", "-o", "args="]
+ output = subprocess.check_output(cmd)
+ except OSError as e: # Python 2-compatible FileNotFoundError.
+ if e.errno != errno.ENOENT:
+ raise
+ raise PsNotAvailable("ps not found")
+ except subprocess.CalledProcessError as e:
+ # `ps` can return 1 if the process list is completely empty.
+ # (sarugaku/shellingham#15)
+ if not e.output.strip():
+ return
+ raise
+ if not isinstance(output, str):
+ encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
+ output = output.decode(encoding)
+
+ processes_mapping = {}
+ for line in output.split("\n"):
+ try:
+ _pid, ppid, args = line.strip().split(None, 2)
+ # XXX: This is not right, but we are really out of options.
+ # ps does not offer a sane way to decode the argument display,
+ # and this is "Good Enough" for obtaining shell names. Hopefully
+ # people don't name their shell with a space, or have something
+ # like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14)
+ args = tuple(a.strip() for a in args.split(" "))
+ except ValueError:
+ continue
+ processes_mapping[_pid] = Process(args=args, pid=_pid, ppid=ppid)
+
+ for _ in range(max_depth):
+ try:
+ process = processes_mapping[pid]
+ except KeyError:
+ return
+ yield process
+ pid = process.ppid
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..0762c8a475a6b7b0808f4f91364506c147461976
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/METADATA
@@ -0,0 +1,171 @@
+Metadata-Version: 2.4
+Name: tiktoken
+Version: 0.11.0
+Summary: tiktoken is a fast BPE tokeniser for use with OpenAI's models
+Author: Shantanu Jain
+Author-email: shantanu@openai.com
+License: MIT License
+
+ Copyright (c) 2022 OpenAI, Shantanu Jain
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
+Project-URL: homepage, https://github.com/openai/tiktoken
+Project-URL: repository, https://github.com/openai/tiktoken
+Project-URL: changelog, https://github.com/openai/tiktoken/blob/main/CHANGELOG.md
+Requires-Python: >=3.9
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: regex>=2022.1.18
+Requires-Dist: requests>=2.26.0
+Provides-Extra: blobfile
+Requires-Dist: blobfile>=2; extra == "blobfile"
+Dynamic: license-file
+
+# ⏳ tiktoken
+
+tiktoken is a fast [BPE](https://en.wikipedia.org/wiki/Byte_pair_encoding) tokeniser for use with
+OpenAI's models.
+
+```python
+import tiktoken
+enc = tiktoken.get_encoding("o200k_base")
+assert enc.decode(enc.encode("hello world")) == "hello world"
+
+# To get the tokeniser corresponding to a specific model in the OpenAI API:
+enc = tiktoken.encoding_for_model("gpt-4o")
+```
+
+The open source version of `tiktoken` can be installed from [PyPI](https://pypi.org/project/tiktoken):
+```
+pip install tiktoken
+```
+
+The tokeniser API is documented in `tiktoken/core.py`.
+
+Example code using `tiktoken` can be found in the
+[OpenAI Cookbook](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb).
+
+
+## Performance
+
+`tiktoken` is between 3-6x faster than a comparable open source tokeniser:
+
+
+
+Performance measured on 1GB of text using the GPT-2 tokeniser, using `GPT2TokenizerFast` from
+`tokenizers==0.13.2`, `transformers==4.24.0` and `tiktoken==0.2.0`.
+
+
+## Getting help
+
+Please post questions in the [issue tracker](https://github.com/openai/tiktoken/issues).
+
+If you work at OpenAI, make sure to check the internal documentation or feel free to contact
+@shantanu.
+
+## What is BPE anyway?
+
+Language models don't see text like you and I, instead they see a sequence of numbers (known as tokens).
+Byte pair encoding (BPE) is a way of converting text into tokens. It has a couple desirable
+properties:
+1) It's reversible and lossless, so you can convert tokens back into the original text
+2) It works on arbitrary text, even text that is not in the tokeniser's training data
+3) It compresses the text: the token sequence is shorter than the bytes corresponding to the
+ original text. On average, in practice, each token corresponds to about 4 bytes.
+4) It attempts to let the model see common subwords. For instance, "ing" is a common subword in
+ English, so BPE encodings will often split "encoding" into tokens like "encod" and "ing"
+ (instead of e.g. "enc" and "oding"). Because the model will then see the "ing" token again and
+ again in different contexts, it helps models generalise and better understand grammar.
+
+`tiktoken` contains an educational submodule that is friendlier if you want to learn more about
+the details of BPE, including code that helps visualise the BPE procedure:
+```python
+from tiktoken._educational import *
+
+# Train a BPE tokeniser on a small amount of text
+enc = train_simple_encoding()
+
+# Visualise how the GPT-4 encoder encodes text
+enc = SimpleBytePairEncoding.from_tiktoken("cl100k_base")
+enc.encode("hello world aaaaaaaaaaaa")
+```
+
+
+## Extending tiktoken
+
+You may wish to extend `tiktoken` to support new encodings. There are two ways to do this.
+
+
+**Create your `Encoding` object exactly the way you want and simply pass it around.**
+
+```python
+cl100k_base = tiktoken.get_encoding("cl100k_base")
+
+# In production, load the arguments directly instead of accessing private attributes
+# See openai_public.py for examples of arguments for specific encodings
+enc = tiktoken.Encoding(
+ # If you're changing the set of special tokens, make sure to use a different name
+ # It should be clear from the name what behaviour to expect.
+ name="cl100k_im",
+ pat_str=cl100k_base._pat_str,
+ mergeable_ranks=cl100k_base._mergeable_ranks,
+ special_tokens={
+ **cl100k_base._special_tokens,
+ "<|im_start|>": 100264,
+ "<|im_end|>": 100265,
+ }
+)
+```
+
+**Use the `tiktoken_ext` plugin mechanism to register your `Encoding` objects with `tiktoken`.**
+
+This is only useful if you need `tiktoken.get_encoding` to find your encoding, otherwise prefer
+option 1.
+
+To do this, you'll need to create a namespace package under `tiktoken_ext`.
+
+Layout your project like this, making sure to omit the `tiktoken_ext/__init__.py` file:
+```
+my_tiktoken_extension
+├── tiktoken_ext
+│ └── my_encodings.py
+└── setup.py
+```
+
+`my_encodings.py` should be a module that contains a variable named `ENCODING_CONSTRUCTORS`.
+This is a dictionary from an encoding name to a function that takes no arguments and returns
+arguments that can be passed to `tiktoken.Encoding` to construct that encoding. For an example, see
+`tiktoken_ext/openai_public.py`. For precise details, see `tiktoken/registry.py`.
+
+Your `setup.py` should look something like this:
+```python
+from setuptools import setup, find_namespace_packages
+
+setup(
+ name="my_tiktoken_extension",
+ packages=find_namespace_packages(include=['tiktoken_ext*']),
+ install_requires=["tiktoken"],
+ ...
+)
+```
+
+Then simply `pip install ./my_tiktoken_extension` and you should be able to use your
+custom encodings! Make sure **not** to use an editable install.
+
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..e061af2ef647a3baf561aba44ad665b7ae25881f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/RECORD
@@ -0,0 +1,22 @@
+tiktoken-0.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+tiktoken-0.11.0.dist-info/METADATA,sha256=AtRihFlqHInH6yNjacHNK7i0brhNFfAlLLB99xvYFOk,6688
+tiktoken-0.11.0.dist-info/RECORD,,
+tiktoken-0.11.0.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151
+tiktoken-0.11.0.dist-info/licenses/LICENSE,sha256=QYy0mbQ2Eo1lPXmUEzOlQ3t74uqSE9zC8E0V1dLFHYY,1078
+tiktoken-0.11.0.dist-info/top_level.txt,sha256=54G5MceQnuD7EXvp7jzGxDDapA1iOwsh77jhCN9WKkc,22
+tiktoken/__init__.py,sha256=1Z2tNVEVsP31Af_EaOnImihi7fBpz1gftl3kPU8aMWI,346
+tiktoken/__pycache__/__init__.cpython-310.pyc,,
+tiktoken/__pycache__/_educational.cpython-310.pyc,,
+tiktoken/__pycache__/core.cpython-310.pyc,,
+tiktoken/__pycache__/load.cpython-310.pyc,,
+tiktoken/__pycache__/model.cpython-310.pyc,,
+tiktoken/__pycache__/registry.cpython-310.pyc,,
+tiktoken/_educational.py,sha256=TUFOp8Q91WjrTvGKhCNEyrhtva82UlenXfhPy9zS7VQ,8229
+tiktoken/_tiktoken.cpython-310-x86_64-linux-gnu.so,sha256=pRND0umzPioN-zBP4tiUd0nGAocWX0Pt6G-MCh6jNuk,3453856
+tiktoken/core.py,sha256=JmoYCLOS1aRdcJLc0kV4mIUw5uxmSLNML3pQ5NdxKQo,17286
+tiktoken/load.py,sha256=xCKCN2CX8fO5vIRiNPfxCsJT-blIhDS3u9FwxA5OGzg,5836
+tiktoken/model.py,sha256=xDjZHcrFl4arND5B13OvqbP8zO9k2wEhhSxvsWo8njE,4034
+tiktoken/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+tiktoken/registry.py,sha256=7fktZbJ1Kcm8sVyWgEfIy-ZxfUvcXupLUNXKPfSGwQU,3256
+tiktoken_ext/__pycache__/openai_public.cpython-310.pyc,,
+tiktoken_ext/openai_public.py,sha256=lUOSc45g0Pttyh2tgIcu_EfI4nM7q-y78KI5cO1mwss,5613
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d170d6d9582d145f12244c4135d9446d597e1029
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_17_x86_64
+Tag: cp310-cp310-manylinux2014_x86_64
+
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..83ed1036f70d4f419307e8a044a35e163cc35201
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 OpenAI, Shantanu Jain
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..859880ea40d957171e49537207249fdca13946cb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/tiktoken-0.11.0.dist-info/top_level.txt
@@ -0,0 +1,2 @@
+tiktoken
+tiktoken_ext
diff --git a/venv/lib/python3.10/site-packages/typer/__init__.py b/venv/lib/python3.10/site-packages/typer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..067b36d4899927c6b2b4429634cd3458df4f0ac8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/__init__.py
@@ -0,0 +1,39 @@
+"""Typer, build great CLIs. Easy to code. Based on Python type hints."""
+
+__version__ = "0.16.0"
+
+from shutil import get_terminal_size as get_terminal_size
+
+from click.exceptions import Abort as Abort
+from click.exceptions import BadParameter as BadParameter
+from click.exceptions import Exit as Exit
+from click.termui import clear as clear
+from click.termui import confirm as confirm
+from click.termui import echo_via_pager as echo_via_pager
+from click.termui import edit as edit
+from click.termui import getchar as getchar
+from click.termui import pause as pause
+from click.termui import progressbar as progressbar
+from click.termui import prompt as prompt
+from click.termui import secho as secho
+from click.termui import style as style
+from click.termui import unstyle as unstyle
+from click.utils import echo as echo
+from click.utils import format_filename as format_filename
+from click.utils import get_app_dir as get_app_dir
+from click.utils import get_binary_stream as get_binary_stream
+from click.utils import get_text_stream as get_text_stream
+from click.utils import open_file as open_file
+
+from . import colors as colors
+from .main import Typer as Typer
+from .main import launch as launch
+from .main import run as run
+from .models import CallbackParam as CallbackParam
+from .models import Context as Context
+from .models import FileBinaryRead as FileBinaryRead
+from .models import FileBinaryWrite as FileBinaryWrite
+from .models import FileText as FileText
+from .models import FileTextWrite as FileTextWrite
+from .params import Argument as Argument
+from .params import Option as Option
diff --git a/venv/lib/python3.10/site-packages/typer/__main__.py b/venv/lib/python3.10/site-packages/typer/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/__main__.py
@@ -0,0 +1,3 @@
+from .cli import main
+
+main()
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f93f40653e5a4509bb947ac323ddec32c4d3a98
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/__main__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..959fe4d80c9de9ad0ffa2787196569fdfd5ea21e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/__main__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_classes.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_classes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e067e79cdb6b320eea8b59be58a88d0e87eb6040
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_classes.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_shared.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_shared.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb8536cc42815f94b1785562e5e44bc1d60c6a30
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/_completion_shared.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/_types.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d032942fbf28158f500956fa7ed532d6a7e68205
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/_types.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/_typing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58a09d36f520e1f087f5e05997f6e46a433ea6e6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/_typing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/cli.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35ec2e2a3b1017df2fb9609d1deaced0208097c6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/cli.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/colors.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/colors.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebec95bdb32c49505d135387229bbe126da8b502
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/colors.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/completion.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/completion.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab360da03f5ad904ca0ef70e6bdb09ed6382fe28
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/completion.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/core.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/core.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..293b2dcec392a7678ef457db8530b8189160f9c2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/core.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/main.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/main.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5efbf382b25c5191138a4c29f02e3b0206d67077
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/main.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/models.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/models.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80b2e2e46ae885175b3ba216c66d57b44b51e4e4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/models.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/params.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/params.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6b86badbc5b02bdb84c3ee4e8c40ad8b9411139
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/params.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/rich_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/rich_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3ab880a0952ad9e3962c52a05d0c947a84f2939
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/rich_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/testing.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/testing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b5fca7ee37dc4345a97a3479a6e12b41a38e514
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/testing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/typer/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc294d826741f2b22df44df27f26a1eed795bb28
Binary files /dev/null and b/venv/lib/python3.10/site-packages/typer/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/typer/_completion_classes.py b/venv/lib/python3.10/site-packages/typer/_completion_classes.py
new file mode 100644
index 0000000000000000000000000000000000000000..5980248afe4863048ecdc42e6b83281f2f870622
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/_completion_classes.py
@@ -0,0 +1,211 @@
+import importlib.util
+import os
+import re
+import sys
+from typing import Any, Dict, List, Tuple
+
+import click
+import click.parser
+import click.shell_completion
+
+from ._completion_shared import (
+ COMPLETION_SCRIPT_BASH,
+ COMPLETION_SCRIPT_FISH,
+ COMPLETION_SCRIPT_POWER_SHELL,
+ COMPLETION_SCRIPT_ZSH,
+ Shells,
+)
+
+try:
+ from click.shell_completion import split_arg_string as click_split_arg_string
+except ImportError: # pragma: no cover
+ # TODO: when removing support for Click < 8.2, remove this import
+ from click.parser import ( # type: ignore[no-redef]
+ split_arg_string as click_split_arg_string,
+ )
+
+try:
+ import shellingham
+except ImportError: # pragma: no cover
+ shellingham = None
+
+
+def _sanitize_help_text(text: str) -> str:
+ """Sanitizes the help text by removing rich tags"""
+ if not importlib.util.find_spec("rich"):
+ return text
+ from . import rich_utils
+
+ return rich_utils.rich_render_text(text)
+
+
+class BashComplete(click.shell_completion.BashComplete):
+ name = Shells.bash.value
+ source_template = COMPLETION_SCRIPT_BASH
+
+ def source_vars(self) -> Dict[str, Any]:
+ return {
+ "complete_func": self.func_name,
+ "autocomplete_var": self.complete_var,
+ "prog_name": self.prog_name,
+ }
+
+ def get_completion_args(self) -> Tuple[List[str], str]:
+ cwords = click_split_arg_string(os.environ["COMP_WORDS"])
+ cword = int(os.environ["COMP_CWORD"])
+ args = cwords[1:cword]
+
+ try:
+ incomplete = cwords[cword]
+ except IndexError:
+ incomplete = ""
+
+ return args, incomplete
+
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
+ # TODO: Explore replicating the new behavior from Click, with item types and
+ # triggering completion for files and directories
+ # return f"{item.type},{item.value}"
+ return f"{item.value}"
+
+ def complete(self) -> str:
+ args, incomplete = self.get_completion_args()
+ completions = self.get_completions(args, incomplete)
+ out = [self.format_completion(item) for item in completions]
+ return "\n".join(out)
+
+
+class ZshComplete(click.shell_completion.ZshComplete):
+ name = Shells.zsh.value
+ source_template = COMPLETION_SCRIPT_ZSH
+
+ def source_vars(self) -> Dict[str, Any]:
+ return {
+ "complete_func": self.func_name,
+ "autocomplete_var": self.complete_var,
+ "prog_name": self.prog_name,
+ }
+
+ def get_completion_args(self) -> Tuple[List[str], str]:
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
+ cwords = click_split_arg_string(completion_args)
+ args = cwords[1:]
+ if args and not completion_args.endswith(" "):
+ incomplete = args[-1]
+ args = args[:-1]
+ else:
+ incomplete = ""
+ return args, incomplete
+
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
+ def escape(s: str) -> str:
+ return (
+ s.replace('"', '""')
+ .replace("'", "''")
+ .replace("$", "\\$")
+ .replace("`", "\\`")
+ .replace(":", r"\\:")
+ )
+
+ # TODO: Explore replicating the new behavior from Click, pay attention to
+ # the difference with and without escape
+ # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
+ if item.help:
+ return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"'
+ else:
+ return f'"{escape(item.value)}"'
+
+ def complete(self) -> str:
+ args, incomplete = self.get_completion_args()
+ completions = self.get_completions(args, incomplete)
+ res = [self.format_completion(item) for item in completions]
+ if res:
+ args_str = "\n".join(res)
+ return f"_arguments '*: :(({args_str}))'"
+ else:
+ return "_files"
+
+
+class FishComplete(click.shell_completion.FishComplete):
+ name = Shells.fish.value
+ source_template = COMPLETION_SCRIPT_FISH
+
+ def source_vars(self) -> Dict[str, Any]:
+ return {
+ "complete_func": self.func_name,
+ "autocomplete_var": self.complete_var,
+ "prog_name": self.prog_name,
+ }
+
+ def get_completion_args(self) -> Tuple[List[str], str]:
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
+ cwords = click_split_arg_string(completion_args)
+ args = cwords[1:]
+ if args and not completion_args.endswith(" "):
+ incomplete = args[-1]
+ args = args[:-1]
+ else:
+ incomplete = ""
+ return args, incomplete
+
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
+ # TODO: Explore replicating the new behavior from Click, pay attention to
+ # the difference with and without formatted help
+ # if item.help:
+ # return f"{item.type},{item.value}\t{item.help}"
+
+ # return f"{item.type},{item.value}
+ if item.help:
+ formatted_help = re.sub(r"\s", " ", item.help)
+ return f"{item.value}\t{_sanitize_help_text(formatted_help)}"
+ else:
+ return f"{item.value}"
+
+ def complete(self) -> str:
+ complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")
+ args, incomplete = self.get_completion_args()
+ completions = self.get_completions(args, incomplete)
+ show_args = [self.format_completion(item) for item in completions]
+ if complete_action == "get-args":
+ if show_args:
+ return "\n".join(show_args)
+ elif complete_action == "is-args":
+ if show_args:
+ # Activate complete args (no files)
+ sys.exit(0)
+ else:
+ # Deactivate complete args (allow files)
+ sys.exit(1)
+ return "" # pragma: no cover
+
+
+class PowerShellComplete(click.shell_completion.ShellComplete):
+ name = Shells.powershell.value
+ source_template = COMPLETION_SCRIPT_POWER_SHELL
+
+ def source_vars(self) -> Dict[str, Any]:
+ return {
+ "complete_func": self.func_name,
+ "autocomplete_var": self.complete_var,
+ "prog_name": self.prog_name,
+ }
+
+ def get_completion_args(self) -> Tuple[List[str], str]:
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
+ incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")
+ cwords = click_split_arg_string(completion_args)
+ args = cwords[1:-1] if incomplete else cwords[1:]
+ return args, incomplete
+
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
+ return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"
+
+
+def completion_init() -> None:
+ click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)
+ click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value)
+ click.shell_completion.add_completion_class(FishComplete, Shells.fish.value)
+ click.shell_completion.add_completion_class(
+ PowerShellComplete, Shells.powershell.value
+ )
+ click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value)
diff --git a/venv/lib/python3.10/site-packages/typer/_completion_shared.py b/venv/lib/python3.10/site-packages/typer/_completion_shared.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc0add992c722c6044342d912f2772aedca86538
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/_completion_shared.py
@@ -0,0 +1,240 @@
+import os
+import re
+import subprocess
+from enum import Enum
+from pathlib import Path
+from typing import Optional, Tuple
+
+import click
+
+try:
+ import shellingham
+except ImportError: # pragma: no cover
+ shellingham = None
+
+
+class Shells(str, Enum):
+ bash = "bash"
+ zsh = "zsh"
+ fish = "fish"
+ powershell = "powershell"
+ pwsh = "pwsh"
+
+
+COMPLETION_SCRIPT_BASH = """
+%(complete_func)s() {
+ local IFS=$'\n'
+ COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\
+ COMP_CWORD=$COMP_CWORD \\
+ %(autocomplete_var)s=complete_bash $1 ) )
+ return 0
+}
+
+complete -o default -F %(complete_func)s %(prog_name)s
+"""
+
+COMPLETION_SCRIPT_ZSH = """
+#compdef %(prog_name)s
+
+%(complete_func)s() {
+ eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)
+}
+
+compdef %(complete_func)s %(prog_name)s
+"""
+
+COMPLETION_SCRIPT_FISH = 'complete --command %(prog_name)s --no-files --arguments "(env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=get-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s)" --condition "env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=is-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s"'
+
+COMPLETION_SCRIPT_POWER_SHELL = """
+Import-Module PSReadLine
+Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete
+$scriptblock = {
+ param($wordToComplete, $commandAst, $cursorPosition)
+ $Env:%(autocomplete_var)s = "complete_powershell"
+ $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()
+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete
+ %(prog_name)s | ForEach-Object {
+ $commandArray = $_ -Split ":::"
+ $command = $commandArray[0]
+ $helpString = $commandArray[1]
+ [System.Management.Automation.CompletionResult]::new(
+ $command, $command, 'ParameterValue', $helpString)
+ }
+ $Env:%(autocomplete_var)s = ""
+ $Env:_TYPER_COMPLETE_ARGS = ""
+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""
+}
+Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock
+"""
+
+_completion_scripts = {
+ "bash": COMPLETION_SCRIPT_BASH,
+ "zsh": COMPLETION_SCRIPT_ZSH,
+ "fish": COMPLETION_SCRIPT_FISH,
+ "powershell": COMPLETION_SCRIPT_POWER_SHELL,
+ "pwsh": COMPLETION_SCRIPT_POWER_SHELL,
+}
+
+# TODO: Probably refactor this, copied from Click 7.x
+_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")
+
+
+def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:
+ cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))
+ script = _completion_scripts.get(shell)
+ if script is None:
+ click.echo(f"Shell {shell} not supported.", err=True)
+ raise click.exceptions.Exit(1)
+ return (
+ script
+ % {
+ "complete_func": f"_{cf_name}_completion",
+ "prog_name": prog_name,
+ "autocomplete_var": complete_var,
+ }
+ ).strip()
+
+
+def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:
+ # Ref: https://github.com/scop/bash-completion#faq
+ # It seems bash-completion is the official completion system for bash:
+ # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html
+ # But installing in the locations from the docs doesn't seem to have effect
+ completion_path = Path.home() / ".bash_completions" / f"{prog_name}.sh"
+ rc_path = Path.home() / ".bashrc"
+ rc_path.parent.mkdir(parents=True, exist_ok=True)
+ rc_content = ""
+ if rc_path.is_file():
+ rc_content = rc_path.read_text()
+ completion_init_lines = [f"source '{completion_path}'"]
+ for line in completion_init_lines:
+ if line not in rc_content: # pragma: no cover
+ rc_content += f"\n{line}"
+ rc_content += "\n"
+ rc_path.write_text(rc_content)
+ # Install completion
+ completion_path.parent.mkdir(parents=True, exist_ok=True)
+ script_content = get_completion_script(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ completion_path.write_text(script_content)
+ return completion_path
+
+
+def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:
+ # Setup Zsh and load ~/.zfunc
+ zshrc_path = Path.home() / ".zshrc"
+ zshrc_path.parent.mkdir(parents=True, exist_ok=True)
+ zshrc_content = ""
+ if zshrc_path.is_file():
+ zshrc_content = zshrc_path.read_text()
+ completion_line = "fpath+=~/.zfunc; autoload -Uz compinit; compinit"
+ if completion_line not in zshrc_content:
+ zshrc_content += f"\n{completion_line}\n"
+ style_line = "zstyle ':completion:*' menu select"
+ # TODO: consider setting the style only for the current program
+ # style_line = f"zstyle ':completion:*:*:{prog_name}:*' menu select"
+ # Install zstyle completion config only if the user doesn't have a customization
+ if "zstyle" not in zshrc_content:
+ zshrc_content += f"\n{style_line}\n"
+ zshrc_content = f"{zshrc_content.strip()}\n"
+ zshrc_path.write_text(zshrc_content)
+ # Install completion under ~/.zfunc/
+ path_obj = Path.home() / f".zfunc/_{prog_name}"
+ path_obj.parent.mkdir(parents=True, exist_ok=True)
+ script_content = get_completion_script(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ path_obj.write_text(script_content)
+ return path_obj
+
+
+def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:
+ path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"
+ parent_dir: Path = path_obj.parent
+ parent_dir.mkdir(parents=True, exist_ok=True)
+ script_content = get_completion_script(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ path_obj.write_text(f"{script_content}\n")
+ return path_obj
+
+
+def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:
+ subprocess.run(
+ [
+ shell,
+ "-Command",
+ "Set-ExecutionPolicy",
+ "Unrestricted",
+ "-Scope",
+ "CurrentUser",
+ ]
+ )
+ result = subprocess.run(
+ [shell, "-NoProfile", "-Command", "echo", "$profile"],
+ check=True,
+ stdout=subprocess.PIPE,
+ )
+ if result.returncode != 0: # pragma: no cover
+ click.echo("Couldn't get PowerShell user profile", err=True)
+ raise click.exceptions.Exit(result.returncode)
+ path_str = ""
+ if isinstance(result.stdout, str): # pragma: no cover
+ path_str = result.stdout
+ if isinstance(result.stdout, bytes):
+ for encoding in ["windows-1252", "utf8", "cp850"]:
+ try:
+ path_str = result.stdout.decode(encoding)
+ break
+ except UnicodeDecodeError: # pragma: no cover
+ pass
+ if not path_str: # pragma: no cover
+ click.echo("Couldn't decode the path automatically", err=True)
+ raise click.exceptions.Exit(1)
+ path_obj = Path(path_str.strip())
+ parent_dir: Path = path_obj.parent
+ parent_dir.mkdir(parents=True, exist_ok=True)
+ script_content = get_completion_script(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ with path_obj.open(mode="a") as f:
+ f.write(f"{script_content}\n")
+ return path_obj
+
+
+def install(
+ shell: Optional[str] = None,
+ prog_name: Optional[str] = None,
+ complete_var: Optional[str] = None,
+) -> Tuple[str, Path]:
+ prog_name = prog_name or click.get_current_context().find_root().info_name
+ assert prog_name
+ if complete_var is None:
+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
+ if shell is None and shellingham is not None and not test_disable_detection:
+ shell, _ = shellingham.detect_shell()
+ if shell == "bash":
+ installed_path = install_bash(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ return shell, installed_path
+ elif shell == "zsh":
+ installed_path = install_zsh(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ return shell, installed_path
+ elif shell == "fish":
+ installed_path = install_fish(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ return shell, installed_path
+ elif shell in {"powershell", "pwsh"}:
+ installed_path = install_powershell(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ return shell, installed_path
+ else:
+ click.echo(f"Shell {shell} is not supported.")
+ raise click.exceptions.Exit(1)
diff --git a/venv/lib/python3.10/site-packages/typer/_types.py b/venv/lib/python3.10/site-packages/typer/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..045e36b815652debaeea1804b1e334218422dcb4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/_types.py
@@ -0,0 +1,27 @@
+from enum import Enum
+from typing import Generic, TypeVar, Union
+
+import click
+
+ParamTypeValue = TypeVar("ParamTypeValue")
+
+
+class TyperChoice(click.Choice, Generic[ParamTypeValue]): # type: ignore[type-arg]
+ def normalize_choice(
+ self, choice: ParamTypeValue, ctx: Union[click.Context, None]
+ ) -> str:
+ # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class
+ # to support enums, but it uses the enum names, while Typer has always used the
+ # enum values.
+ # This class overrides that method to maintain the previous behavior.
+ # In Click:
+ # normed_value = choice.name if isinstance(choice, Enum) else str(choice)
+ normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice)
+
+ if ctx is not None and ctx.token_normalize_func is not None:
+ normed_value = ctx.token_normalize_func(normed_value)
+
+ if not self.case_sensitive:
+ normed_value = normed_value.casefold()
+
+ return normed_value
diff --git a/venv/lib/python3.10/site-packages/typer/_typing.py b/venv/lib/python3.10/site-packages/typer/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b3f7c8dd6d8692f41d9d28dce3fec2627617b6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/_typing.py
@@ -0,0 +1,113 @@
+# Copied from pydantic 1.9.2 (the latest version to support python 3.6.)
+# https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py
+# Reduced drastically to only include Typer-specific 3.7+ functionality
+# mypy: ignore-errors
+
+import sys
+from typing import (
+ Any,
+ Callable,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
+
+if sys.version_info >= (3, 9):
+ from typing import Annotated, Literal, get_args, get_origin, get_type_hints
+else:
+ from typing_extensions import (
+ Annotated,
+ Literal,
+ get_args,
+ get_origin,
+ get_type_hints,
+ )
+
+if sys.version_info < (3, 10):
+
+ def is_union(tp: Optional[Type[Any]]) -> bool:
+ return tp is Union
+
+else:
+ import types
+
+ def is_union(tp: Optional[Type[Any]]) -> bool:
+ return tp is Union or tp is types.UnionType # noqa: E721
+
+
+__all__ = (
+ "NoneType",
+ "is_none_type",
+ "is_callable_type",
+ "is_literal_type",
+ "all_literal_values",
+ "is_union",
+ "Annotated",
+ "Literal",
+ "get_args",
+ "get_origin",
+ "get_type_hints",
+)
+
+
+NoneType = None.__class__
+
+
+NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None])
+
+
+if sys.version_info < (3, 8):
+ # Even though this implementation is slower, we need it for python 3.7:
+ # In python 3.7 "Literal" is not a builtin type and uses a different
+ # mechanism.
+ # for this reason `Literal[None] is Literal[None]` evaluates to `False`,
+ # breaking the faster implementation used for the other python versions.
+
+ def is_none_type(type_: Any) -> bool:
+ return type_ in NONE_TYPES
+
+elif sys.version_info[:2] == (3, 8):
+ # We can use the fast implementation for 3.8 but there is a very weird bug
+ # where it can fail for `Literal[None]`.
+ # We just need to redefine a useless `Literal[None]` inside the function body to fix this
+
+ def is_none_type(type_: Any) -> bool:
+ Literal[None] # fix edge case
+ for none_type in NONE_TYPES:
+ if type_ is none_type:
+ return True
+ return False
+
+else:
+
+ def is_none_type(type_: Any) -> bool:
+ for none_type in NONE_TYPES:
+ if type_ is none_type:
+ return True
+ return False
+
+
+def is_callable_type(type_: Type[Any]) -> bool:
+ return type_ is Callable or get_origin(type_) is Callable
+
+
+def is_literal_type(type_: Type[Any]) -> bool:
+ return Literal is not None and get_origin(type_) is Literal
+
+
+def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
+ return get_args(type_)
+
+
+def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
+ """
+ This method is used to retrieve all Literal values as
+ Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)
+ e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`
+ """
+ if not is_literal_type(type_):
+ return (type_,)
+
+ values = literal_values(type_)
+ return tuple(x for value in values for x in all_literal_values(value))
diff --git a/venv/lib/python3.10/site-packages/typer/cli.py b/venv/lib/python3.10/site-packages/typer/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fe3d3ee7fbd6fedeade47ceb22a83cf258f7945
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/cli.py
@@ -0,0 +1,315 @@
+import importlib.util
+import re
+import sys
+from pathlib import Path
+from typing import Any, List, Optional
+
+import click
+import typer
+import typer.core
+from click import Command, Group, Option
+
+from . import __version__
+
+try:
+ import rich
+
+ has_rich = True
+ from . import rich_utils
+
+except ImportError: # pragma: no cover
+ has_rich = False
+ rich = None # type: ignore
+
+default_app_names = ("app", "cli", "main")
+default_func_names = ("main", "cli", "app")
+
+app = typer.Typer()
+utils_app = typer.Typer(help="Extra utility commands for Typer apps.")
+app.add_typer(utils_app, name="utils")
+
+
+class State:
+ def __init__(self) -> None:
+ self.app: Optional[str] = None
+ self.func: Optional[str] = None
+ self.file: Optional[Path] = None
+ self.module: Optional[str] = None
+
+
+state = State()
+
+
+def maybe_update_state(ctx: click.Context) -> None:
+ path_or_module = ctx.params.get("path_or_module")
+ if path_or_module:
+ file_path = Path(path_or_module)
+ if file_path.exists() and file_path.is_file():
+ state.file = file_path
+ else:
+ if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):
+ typer.echo(
+ f"Not a valid file or Python module: {path_or_module}", err=True
+ )
+ sys.exit(1)
+ state.module = path_or_module
+ app_name = ctx.params.get("app")
+ if app_name:
+ state.app = app_name
+ func_name = ctx.params.get("func")
+ if func_name:
+ state.func = func_name
+
+
+class TyperCLIGroup(typer.core.TyperGroup):
+ def list_commands(self, ctx: click.Context) -> List[str]:
+ self.maybe_add_run(ctx)
+ return super().list_commands(ctx)
+
+ def get_command(self, ctx: click.Context, name: str) -> Optional[Command]:
+ self.maybe_add_run(ctx)
+ return super().get_command(ctx, name)
+
+ def invoke(self, ctx: click.Context) -> Any:
+ self.maybe_add_run(ctx)
+ return super().invoke(ctx)
+
+ def maybe_add_run(self, ctx: click.Context) -> None:
+ maybe_update_state(ctx)
+ maybe_add_run_to_cli(self)
+
+
+def get_typer_from_module(module: Any) -> Optional[typer.Typer]:
+ # Try to get defined app
+ if state.app:
+ obj = getattr(module, state.app, None)
+ if not isinstance(obj, typer.Typer):
+ typer.echo(f"Not a Typer object: --app {state.app}", err=True)
+ sys.exit(1)
+ return obj
+ # Try to get defined function
+ if state.func:
+ func_obj = getattr(module, state.func, None)
+ if not callable(func_obj):
+ typer.echo(f"Not a function: --func {state.func}", err=True)
+ sys.exit(1)
+ sub_app = typer.Typer()
+ sub_app.command()(func_obj)
+ return sub_app
+ # Iterate and get a default object to use as CLI
+ local_names = dir(module)
+ local_names_set = set(local_names)
+ # Try to get a default Typer app
+ for name in default_app_names:
+ if name in local_names_set:
+ obj = getattr(module, name, None)
+ if isinstance(obj, typer.Typer):
+ return obj
+ # Try to get any Typer app
+ for name in local_names_set - set(default_app_names):
+ obj = getattr(module, name)
+ if isinstance(obj, typer.Typer):
+ return obj
+ # Try to get a default function
+ for func_name in default_func_names:
+ func_obj = getattr(module, func_name, None)
+ if callable(func_obj):
+ sub_app = typer.Typer()
+ sub_app.command()(func_obj)
+ return sub_app
+ # Try to get any func app
+ for func_name in local_names_set - set(default_func_names):
+ func_obj = getattr(module, func_name)
+ if callable(func_obj):
+ sub_app = typer.Typer()
+ sub_app.command()(func_obj)
+ return sub_app
+ return None
+
+
+def get_typer_from_state() -> Optional[typer.Typer]:
+ spec = None
+ if state.file:
+ module_name = state.file.name
+ spec = importlib.util.spec_from_file_location(module_name, str(state.file))
+ elif state.module:
+ spec = importlib.util.find_spec(state.module)
+ if spec is None:
+ if state.file:
+ typer.echo(f"Could not import as Python file: {state.file}", err=True)
+ else:
+ typer.echo(f"Could not import as Python module: {state.module}", err=True)
+ sys.exit(1)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module) # type: ignore
+ obj = get_typer_from_module(module)
+ return obj
+
+
+def maybe_add_run_to_cli(cli: click.Group) -> None:
+ if "run" not in cli.commands:
+ if state.file or state.module:
+ obj = get_typer_from_state()
+ if obj:
+ obj._add_completion = False
+ click_obj = typer.main.get_command(obj)
+ click_obj.name = "run"
+ if not click_obj.help:
+ click_obj.help = "Run the provided Typer app."
+ cli.add_command(click_obj)
+
+
+def print_version(ctx: click.Context, param: Option, value: bool) -> None:
+ if not value or ctx.resilient_parsing:
+ return
+ typer.echo(f"Typer version: {__version__}")
+ raise typer.Exit()
+
+
+@app.callback(cls=TyperCLIGroup, no_args_is_help=True)
+def callback(
+ ctx: typer.Context,
+ *,
+ path_or_module: str = typer.Argument(None),
+ app: str = typer.Option(None, help="The typer app object/variable to use."),
+ func: str = typer.Option(None, help="The function to convert to Typer."),
+ version: bool = typer.Option(
+ False,
+ "--version",
+ help="Print version and exit.",
+ callback=print_version,
+ ),
+) -> None:
+ """
+ Run Typer scripts with completion, without having to create a package.
+
+ You probably want to install completion for the typer command:
+
+ $ typer --install-completion
+
+ https://typer.tiangolo.com/
+ """
+ maybe_update_state(ctx)
+
+
+def get_docs_for_click(
+ *,
+ obj: Command,
+ ctx: typer.Context,
+ indent: int = 0,
+ name: str = "",
+ call_prefix: str = "",
+ title: Optional[str] = None,
+) -> str:
+ docs = "#" * (1 + indent)
+ command_name = name or obj.name
+ if call_prefix:
+ command_name = f"{call_prefix} {command_name}"
+ if not title:
+ title = f"`{command_name}`" if command_name else "CLI"
+ docs += f" {title}\n\n"
+ if obj.help:
+ docs += f"{_parse_html(obj.help)}\n\n"
+ usage_pieces = obj.collect_usage_pieces(ctx)
+ if usage_pieces:
+ docs += "**Usage**:\n\n"
+ docs += "```console\n"
+ docs += "$ "
+ if command_name:
+ docs += f"{command_name} "
+ docs += f"{' '.join(usage_pieces)}\n"
+ docs += "```\n\n"
+ args = []
+ opts = []
+ for param in obj.get_params(ctx):
+ rv = param.get_help_record(ctx)
+ if rv is not None:
+ if param.param_type_name == "argument":
+ args.append(rv)
+ elif param.param_type_name == "option":
+ opts.append(rv)
+ if args:
+ docs += "**Arguments**:\n\n"
+ for arg_name, arg_help in args:
+ docs += f"* `{arg_name}`"
+ if arg_help:
+ docs += f": {_parse_html(arg_help)}"
+ docs += "\n"
+ docs += "\n"
+ if opts:
+ docs += "**Options**:\n\n"
+ for opt_name, opt_help in opts:
+ docs += f"* `{opt_name}`"
+ if opt_help:
+ docs += f": {_parse_html(opt_help)}"
+ docs += "\n"
+ docs += "\n"
+ if obj.epilog:
+ docs += f"{obj.epilog}\n\n"
+ if isinstance(obj, Group):
+ group = obj
+ commands = group.list_commands(ctx)
+ if commands:
+ docs += "**Commands**:\n\n"
+ for command in commands:
+ command_obj = group.get_command(ctx, command)
+ assert command_obj
+ docs += f"* `{command_obj.name}`"
+ command_help = command_obj.get_short_help_str()
+ if command_help:
+ docs += f": {_parse_html(command_help)}"
+ docs += "\n"
+ docs += "\n"
+ for command in commands:
+ command_obj = group.get_command(ctx, command)
+ assert command_obj
+ use_prefix = ""
+ if command_name:
+ use_prefix += f"{command_name}"
+ docs += get_docs_for_click(
+ obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix
+ )
+ return docs
+
+
+def _parse_html(input_text: str) -> str:
+ if not has_rich: # pragma: no cover
+ return input_text
+ return rich_utils.rich_to_html(input_text)
+
+
+@utils_app.command()
+def docs(
+ ctx: typer.Context,
+ name: str = typer.Option("", help="The name of the CLI program to use in docs."),
+ output: Optional[Path] = typer.Option(
+ None,
+ help="An output file to write docs to, like README.md.",
+ file_okay=True,
+ dir_okay=False,
+ ),
+ title: Optional[str] = typer.Option(
+ None,
+ help="The title for the documentation page. If not provided, the name of "
+ "the program is used.",
+ ),
+) -> None:
+ """
+ Generate Markdown docs for a Typer app.
+ """
+ typer_obj = get_typer_from_state()
+ if not typer_obj:
+ typer.echo("No Typer app found", err=True)
+ raise typer.Abort()
+ click_obj = typer.main.get_command(typer_obj)
+ docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)
+ clean_docs = f"{docs.strip()}\n"
+ if output:
+ output.write_text(clean_docs)
+ typer.echo(f"Docs saved to: {output}")
+ else:
+ typer.echo(clean_docs)
+
+
+def main() -> Any:
+ return app()
diff --git a/venv/lib/python3.10/site-packages/typer/colors.py b/venv/lib/python3.10/site-packages/typer/colors.py
new file mode 100644
index 0000000000000000000000000000000000000000..54e7b166cb1de83321a4965cc4915824b47a7f4f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/colors.py
@@ -0,0 +1,20 @@
+# Variable names to colors, just for completion
+BLACK = "black"
+RED = "red"
+GREEN = "green"
+YELLOW = "yellow"
+BLUE = "blue"
+MAGENTA = "magenta"
+CYAN = "cyan"
+WHITE = "white"
+
+RESET = "reset"
+
+BRIGHT_BLACK = "bright_black"
+BRIGHT_RED = "bright_red"
+BRIGHT_GREEN = "bright_green"
+BRIGHT_YELLOW = "bright_yellow"
+BRIGHT_BLUE = "bright_blue"
+BRIGHT_MAGENTA = "bright_magenta"
+BRIGHT_CYAN = "bright_cyan"
+BRIGHT_WHITE = "bright_white"
diff --git a/venv/lib/python3.10/site-packages/typer/completion.py b/venv/lib/python3.10/site-packages/typer/completion.py
new file mode 100644
index 0000000000000000000000000000000000000000..c355baa78182a6e7a6ba692db660fca162ef79f9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/completion.py
@@ -0,0 +1,149 @@
+import os
+import sys
+from typing import Any, MutableMapping, Tuple
+
+import click
+
+from ._completion_classes import completion_init
+from ._completion_shared import Shells, get_completion_script, install
+from .models import ParamMeta
+from .params import Option
+from .utils import get_params_from_function
+
+try:
+ import shellingham
+except ImportError: # pragma: no cover
+ shellingham = None
+
+
+_click_patched = False
+
+
+def get_completion_inspect_parameters() -> Tuple[ParamMeta, ParamMeta]:
+ completion_init()
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
+ if shellingham and not test_disable_detection:
+ parameters = get_params_from_function(_install_completion_placeholder_function)
+ else:
+ parameters = get_params_from_function(
+ _install_completion_no_auto_placeholder_function
+ )
+ install_param, show_param = parameters.values()
+ return install_param, show_param
+
+
+def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
+ if not value or ctx.resilient_parsing:
+ return value # pragma: no cover
+ if isinstance(value, str):
+ shell, path = install(shell=value)
+ else:
+ shell, path = install()
+ click.secho(f"{shell} completion installed in {path}", fg="green")
+ click.echo("Completion will take effect once you restart the terminal")
+ sys.exit(0)
+
+
+def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
+ if not value or ctx.resilient_parsing:
+ return value # pragma: no cover
+ prog_name = ctx.find_root().info_name
+ assert prog_name
+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
+ shell = ""
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
+ if isinstance(value, str):
+ shell = value
+ elif shellingham and not test_disable_detection:
+ shell, _ = shellingham.detect_shell()
+ script_content = get_completion_script(
+ prog_name=prog_name, complete_var=complete_var, shell=shell
+ )
+ click.echo(script_content)
+ sys.exit(0)
+
+
+# Create a fake command function to extract the completion parameters
+def _install_completion_placeholder_function(
+ install_completion: bool = Option(
+ None,
+ "--install-completion",
+ callback=install_callback,
+ expose_value=False,
+ help="Install completion for the current shell.",
+ ),
+ show_completion: bool = Option(
+ None,
+ "--show-completion",
+ callback=show_callback,
+ expose_value=False,
+ help="Show completion for the current shell, to copy it or customize the installation.",
+ ),
+) -> Any:
+ pass # pragma: no cover
+
+
+def _install_completion_no_auto_placeholder_function(
+ install_completion: Shells = Option(
+ None,
+ callback=install_callback,
+ expose_value=False,
+ help="Install completion for the specified shell.",
+ ),
+ show_completion: Shells = Option(
+ None,
+ callback=show_callback,
+ expose_value=False,
+ help="Show completion for the specified shell, to copy it or customize the installation.",
+ ),
+) -> Any:
+ pass # pragma: no cover
+
+
+# Re-implement Click's shell_complete to add error message with:
+# Invalid completion instruction
+# To use 7.x instruction style for compatibility
+# And to add extra error messages, for compatibility with Typer in previous versions
+# This is only called in new Command method, only used by Click 8.x+
+def shell_complete(
+ cli: click.Command,
+ ctx_args: MutableMapping[str, Any],
+ prog_name: str,
+ complete_var: str,
+ instruction: str,
+) -> int:
+ import click
+ import click.shell_completion
+
+ if "_" not in instruction:
+ click.echo("Invalid completion instruction.", err=True)
+ return 1
+
+ # Click 8 changed the order/style of shell instructions from e.g.
+ # source_bash to bash_source
+ # Typer override to preserve the old style for compatibility
+ # Original in Click 8.x commented:
+ # shell, _, instruction = instruction.partition("_")
+ instruction, _, shell = instruction.partition("_")
+ # Typer override end
+
+ comp_cls = click.shell_completion.get_completion_class(shell)
+
+ if comp_cls is None:
+ click.echo(f"Shell {shell} not supported.", err=True)
+ return 1
+
+ comp = comp_cls(cli, ctx_args, prog_name, complete_var)
+
+ if instruction == "source":
+ click.echo(comp.source())
+ return 0
+
+ # Typer override to print the completion help msg with Rich
+ if instruction == "complete":
+ click.echo(comp.complete())
+ return 0
+ # Typer override end
+
+ click.echo(f'Completion instruction "{instruction}" not supported.', err=True)
+ return 1
diff --git a/venv/lib/python3.10/site-packages/typer/core.py b/venv/lib/python3.10/site-packages/typer/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6c4f72e8a5bd2ab8d117f87895b9d1200cb6e9a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/core.py
@@ -0,0 +1,781 @@
+import errno
+import inspect
+import os
+import sys
+from enum import Enum
+from gettext import gettext as _
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ MutableMapping,
+ Optional,
+ Sequence,
+ TextIO,
+ Tuple,
+ Union,
+ cast,
+)
+
+import click
+import click.core
+import click.formatting
+import click.parser
+import click.shell_completion
+import click.types
+import click.utils
+
+from ._typing import Literal
+
+MarkupMode = Literal["markdown", "rich", None]
+
+try:
+ import rich
+
+ from . import rich_utils
+
+ DEFAULT_MARKUP_MODE: MarkupMode = "rich"
+
+except ImportError: # pragma: no cover
+ rich = None # type: ignore
+ DEFAULT_MARKUP_MODE = None
+
+
+# Copy from click.parser._split_opt
+def _split_opt(opt: str) -> Tuple[str, str]:
+ first = opt[:1]
+ if first.isalnum():
+ return "", opt
+ if opt[1:2] == first:
+ return opt[:2], opt[2:]
+ return first, opt[1:]
+
+
+def _typer_param_setup_autocompletion_compat(
+ self: click.Parameter,
+ *,
+ autocompletion: Optional[
+ Callable[[click.Context, List[str], str], List[Union[Tuple[str, str], str]]]
+ ] = None,
+) -> None:
+ if self._custom_shell_complete is not None:
+ import warnings
+
+ warnings.warn(
+ "In Typer, only the parameter 'autocompletion' is supported. "
+ "The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ if autocompletion is not None:
+
+ def compat_autocompletion(
+ ctx: click.Context, param: click.core.Parameter, incomplete: str
+ ) -> List["click.shell_completion.CompletionItem"]:
+ from click.shell_completion import CompletionItem
+
+ out = []
+
+ for c in autocompletion(ctx, [], incomplete):
+ if isinstance(c, tuple):
+ use_completion = CompletionItem(c[0], help=c[1])
+ else:
+ assert isinstance(c, str)
+ use_completion = CompletionItem(c)
+
+ if use_completion.value.startswith(incomplete):
+ out.append(use_completion)
+
+ return out
+
+ self._custom_shell_complete = compat_autocompletion
+
+
+def _get_default_string(
+ obj: Union["TyperArgument", "TyperOption"],
+ *,
+ ctx: click.Context,
+ show_default_is_str: bool,
+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],
+) -> str:
+ # Extracted from click.core.Option.get_help_record() to be reused by
+ # rich_utils avoiding RegEx hacks
+ if show_default_is_str:
+ default_string = f"({obj.show_default})"
+ elif isinstance(default_value, (list, tuple)):
+ default_string = ", ".join(
+ _get_default_string(
+ obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d
+ )
+ for d in default_value
+ )
+ elif isinstance(default_value, Enum):
+ default_string = str(default_value.value)
+ elif inspect.isfunction(default_value):
+ default_string = _("(dynamic)")
+ elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:
+ # For boolean flags that have distinct True/False opts,
+ # use the opt without prefix instead of the value.
+ # Typer override, original commented
+ # default_string = click.parser.split_opt(
+ # (self.opts if self.default else self.secondary_opts)[0]
+ # )[1]
+ if obj.default:
+ if obj.opts:
+ default_string = _split_opt(obj.opts[0])[1]
+ else:
+ default_string = str(default_value)
+ else:
+ default_string = _split_opt(obj.secondary_opts[0])[1]
+ # Typer override end
+ elif (
+ isinstance(obj, TyperOption)
+ and obj.is_bool_flag
+ and not obj.secondary_opts
+ and not default_value
+ ):
+ default_string = ""
+ else:
+ default_string = str(default_value)
+ return default_string
+
+
+def _extract_default_help_str(
+ obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context
+) -> Optional[Union[Any, Callable[[], Any]]]:
+ # Extracted from click.core.Option.get_help_record() to be reused by
+ # rich_utils avoiding RegEx hacks
+ # Temporarily enable resilient parsing to avoid type casting
+ # failing for the default. Might be possible to extend this to
+ # help formatting in general.
+ resilient = ctx.resilient_parsing
+ ctx.resilient_parsing = True
+
+ try:
+ default_value = obj.get_default(ctx, call=False)
+ finally:
+ ctx.resilient_parsing = resilient
+ return default_value
+
+
+def _main(
+ self: click.Command,
+ *,
+ args: Optional[Sequence[str]] = None,
+ prog_name: Optional[str] = None,
+ complete_var: Optional[str] = None,
+ standalone_mode: bool = True,
+ windows_expand_args: bool = True,
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
+ **extra: Any,
+) -> Any:
+ # Typer override, duplicated from click.main() to handle custom rich exceptions
+ # Verify that the environment is configured correctly, or reject
+ # further execution to avoid a broken script.
+ if args is None:
+ args = sys.argv[1:]
+
+ # Covered in Click tests
+ if os.name == "nt" and windows_expand_args: # pragma: no cover
+ args = click.utils._expand_args(args)
+ else:
+ args = list(args)
+
+ if prog_name is None:
+ prog_name = click.utils._detect_program_name()
+
+ # Process shell completion requests and exit early.
+ self._main_shell_completion(extra, prog_name, complete_var)
+
+ try:
+ try:
+ with self.make_context(prog_name, args, **extra) as ctx:
+ rv = self.invoke(ctx)
+ if not standalone_mode:
+ return rv
+ # it's not safe to `ctx.exit(rv)` here!
+ # note that `rv` may actually contain data like "1" which
+ # has obvious effects
+ # more subtle case: `rv=[None, None]` can come out of
+ # chained commands which all returned `None` -- so it's not
+ # even always obvious that `rv` indicates success/failure
+ # by its truthiness/falsiness
+ ctx.exit()
+ except EOFError as e:
+ click.echo(file=sys.stderr)
+ raise click.Abort() from e
+ except KeyboardInterrupt as e:
+ raise click.exceptions.Exit(130) from e
+ except click.ClickException as e:
+ if not standalone_mode:
+ raise
+ # Typer override
+ if rich and rich_markup_mode is not None:
+ rich_utils.rich_format_error(e)
+ else:
+ e.show()
+ # Typer override end
+ sys.exit(e.exit_code)
+ except OSError as e:
+ if e.errno == errno.EPIPE:
+ sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))
+ sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))
+ sys.exit(1)
+ else:
+ raise
+ except click.exceptions.Exit as e:
+ if standalone_mode:
+ sys.exit(e.exit_code)
+ else:
+ # in non-standalone mode, return the exit code
+ # note that this is only reached if `self.invoke` above raises
+ # an Exit explicitly -- thus bypassing the check there which
+ # would return its result
+ # the results of non-standalone execution may therefore be
+ # somewhat ambiguous: if there are codepaths which lead to
+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to
+ # tell the difference between the two
+ return e.exit_code
+ except click.Abort:
+ if not standalone_mode:
+ raise
+ # Typer override
+ if rich and rich_markup_mode is not None:
+ rich_utils.rich_abort_error()
+ else:
+ click.echo(_("Aborted!"), file=sys.stderr)
+ # Typer override end
+ sys.exit(1)
+
+
+class TyperArgument(click.core.Argument):
+ def __init__(
+ self,
+ *,
+ # Parameter
+ param_decls: List[str],
+ type: Optional[Any] = None,
+ required: Optional[bool] = None,
+ default: Optional[Any] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ nargs: Optional[int] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ self.help = help
+ self.show_default = show_default
+ self.show_choices = show_choices
+ self.show_envvar = show_envvar
+ self.hidden = hidden
+ self.rich_help_panel = rich_help_panel
+
+ super().__init__(
+ param_decls=param_decls,
+ type=type,
+ required=required,
+ default=default,
+ callback=callback,
+ nargs=nargs,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ shell_complete=shell_complete,
+ )
+ _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
+
+ def _get_default_string(
+ self,
+ *,
+ ctx: click.Context,
+ show_default_is_str: bool,
+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],
+ ) -> str:
+ return _get_default_string(
+ self,
+ ctx=ctx,
+ show_default_is_str=show_default_is_str,
+ default_value=default_value,
+ )
+
+ def _extract_default_help_str(
+ self, *, ctx: click.Context
+ ) -> Optional[Union[Any, Callable[[], Any]]]:
+ return _extract_default_help_str(self, ctx=ctx)
+
+ def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
+ # Modified version of click.core.Option.get_help_record()
+ # to support Arguments
+ if self.hidden:
+ return None
+ name = self.make_metavar(ctx=ctx)
+ help = self.help or ""
+ extra = []
+ if self.show_envvar:
+ envvar = self.envvar
+ # allow_from_autoenv is currently not supported in Typer for CLI Arguments
+ if envvar is not None:
+ var_str = (
+ ", ".join(str(d) for d in envvar)
+ if isinstance(envvar, (list, tuple))
+ else envvar
+ )
+ extra.append(f"env var: {var_str}")
+
+ # Typer override:
+ # Extracted to _extract_default_help_str() to allow re-using it in rich_utils
+ default_value = self._extract_default_help_str(ctx=ctx)
+ # Typer override end
+
+ show_default_is_str = isinstance(self.show_default, str)
+
+ if show_default_is_str or (
+ default_value is not None and (self.show_default or ctx.show_default)
+ ):
+ # Typer override:
+ # Extracted to _get_default_string() to allow re-using it in rich_utils
+ default_string = self._get_default_string(
+ ctx=ctx,
+ show_default_is_str=show_default_is_str,
+ default_value=default_value,
+ )
+ # Typer override end
+ if default_string:
+ extra.append(_("default: {default}").format(default=default_string))
+ if self.required:
+ extra.append(_("required"))
+ if extra:
+ extra_str = "; ".join(extra)
+ extra_str = f"[{extra_str}]"
+ if rich is not None:
+ # This is needed for when we want to export to HTML
+ extra_str = rich.markup.escape(extra_str).strip()
+
+ help = f"{help} {extra_str}" if help else f"{extra_str}"
+ return name, help
+
+ def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:
+ # Modified version of click.core.Argument.make_metavar()
+ # to include Argument name
+ if self.metavar is not None:
+ return self.metavar
+ var = (self.name or "").upper()
+ if not self.required:
+ var = f"[{var}]"
+ # TODO: When deprecating Click < 8.2, remove this
+ signature = inspect.signature(self.type.get_metavar)
+ if "ctx" in signature.parameters:
+ # Click >= 8.2
+ type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type]
+ else:
+ # Click < 8.2
+ type_var = self.type.get_metavar(self) # type: ignore[call-arg]
+ # TODO: /When deprecating Click < 8.2, remove this, uncomment the line below
+ # type_var = self.type.get_metavar(self, ctx=ctx)
+ if type_var:
+ var += f":{type_var}"
+ if self.nargs != 1:
+ var += "..."
+ return var
+
+
+class TyperOption(click.core.Option):
+ def __init__(
+ self,
+ *,
+ # Parameter
+ param_decls: List[str],
+ type: Optional[Union[click.types.ParamType, Any]] = None,
+ required: Optional[bool] = None,
+ default: Optional[Any] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ nargs: Optional[int] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ # Option
+ show_default: Union[bool, str] = False,
+ prompt: Union[bool, str] = False,
+ confirmation_prompt: Union[bool, str] = False,
+ prompt_required: bool = True,
+ hide_input: bool = False,
+ is_flag: Optional[bool] = None,
+ multiple: bool = False,
+ count: bool = False,
+ allow_from_autoenv: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ show_choices: bool = True,
+ show_envvar: bool = False,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ super().__init__(
+ param_decls=param_decls,
+ type=type,
+ required=required,
+ default=default,
+ callback=callback,
+ nargs=nargs,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ show_default=show_default,
+ prompt=prompt,
+ confirmation_prompt=confirmation_prompt,
+ hide_input=hide_input,
+ is_flag=is_flag,
+ multiple=multiple,
+ count=count,
+ allow_from_autoenv=allow_from_autoenv,
+ help=help,
+ hidden=hidden,
+ show_choices=show_choices,
+ show_envvar=show_envvar,
+ prompt_required=prompt_required,
+ shell_complete=shell_complete,
+ )
+ _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
+ self.rich_help_panel = rich_help_panel
+
+ def _get_default_string(
+ self,
+ *,
+ ctx: click.Context,
+ show_default_is_str: bool,
+ default_value: Union[List[Any], Tuple[Any, ...], str, Callable[..., Any], Any],
+ ) -> str:
+ return _get_default_string(
+ self,
+ ctx=ctx,
+ show_default_is_str=show_default_is_str,
+ default_value=default_value,
+ )
+
+ def _extract_default_help_str(
+ self, *, ctx: click.Context
+ ) -> Optional[Union[Any, Callable[[], Any]]]:
+ return _extract_default_help_str(self, ctx=ctx)
+
+ def make_metavar(self, ctx: Union[click.Context, None] = None) -> str:
+ signature = inspect.signature(super().make_metavar)
+ if "ctx" in signature.parameters:
+ # Click >= 8.2
+ return super().make_metavar(ctx=ctx) # type: ignore[arg-type]
+ # Click < 8.2
+ return super().make_metavar() # type: ignore[call-arg]
+
+ def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:
+ # Duplicate all of Click's logic only to modify a single line, to allow boolean
+ # flags with only names for False values as it's currently supported by Typer
+ # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false
+ if self.hidden:
+ return None
+
+ any_prefix_is_slash = False
+
+ def _write_opts(opts: Sequence[str]) -> str:
+ nonlocal any_prefix_is_slash
+
+ rv, any_slashes = click.formatting.join_options(opts)
+
+ if any_slashes:
+ any_prefix_is_slash = True
+
+ if not self.is_flag and not self.count:
+ rv += f" {self.make_metavar(ctx=ctx)}"
+
+ return rv
+
+ rv = [_write_opts(self.opts)]
+
+ if self.secondary_opts:
+ rv.append(_write_opts(self.secondary_opts))
+
+ help = self.help or ""
+ extra = []
+
+ if self.show_envvar:
+ envvar = self.envvar
+
+ if envvar is None:
+ if (
+ self.allow_from_autoenv
+ and ctx.auto_envvar_prefix is not None
+ and self.name is not None
+ ):
+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
+
+ if envvar is not None:
+ var_str = (
+ envvar
+ if isinstance(envvar, str)
+ else ", ".join(str(d) for d in envvar)
+ )
+ extra.append(_("env var: {var}").format(var=var_str))
+
+ # Typer override:
+ # Extracted to _extract_default() to allow re-using it in rich_utils
+ default_value = self._extract_default_help_str(ctx=ctx)
+ # Typer override end
+
+ show_default_is_str = isinstance(self.show_default, str)
+
+ if show_default_is_str or (
+ default_value is not None and (self.show_default or ctx.show_default)
+ ):
+ # Typer override:
+ # Extracted to _get_default_string() to allow re-using it in rich_utils
+ default_string = self._get_default_string(
+ ctx=ctx,
+ show_default_is_str=show_default_is_str,
+ default_value=default_value,
+ )
+ # Typer override end
+ if default_string:
+ extra.append(_("default: {default}").format(default=default_string))
+
+ if isinstance(self.type, click.types._NumberRangeBase):
+ range_str = self.type._describe_range()
+
+ if range_str:
+ extra.append(range_str)
+
+ if self.required:
+ extra.append(_("required"))
+
+ if extra:
+ extra_str = "; ".join(extra)
+ extra_str = f"[{extra_str}]"
+ if rich is not None:
+ # This is needed for when we want to export to HTML
+ extra_str = rich.markup.escape(extra_str).strip()
+
+ help = f"{help} {extra_str}" if help else f"{extra_str}"
+
+ return ("; " if any_prefix_is_slash else " / ").join(rv), help
+
+
+def _typer_format_options(
+ self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter
+) -> None:
+ args = []
+ opts = []
+ for param in self.get_params(ctx):
+ rv = param.get_help_record(ctx)
+ if rv is not None:
+ if param.param_type_name == "argument":
+ args.append(rv)
+ elif param.param_type_name == "option":
+ opts.append(rv)
+
+ if args:
+ with formatter.section(_("Arguments")):
+ formatter.write_dl(args)
+ if opts:
+ with formatter.section(_("Options")):
+ formatter.write_dl(opts)
+
+
+def _typer_main_shell_completion(
+ self: click.core.Command,
+ *,
+ ctx_args: MutableMapping[str, Any],
+ prog_name: str,
+ complete_var: Optional[str] = None,
+) -> None:
+ if complete_var is None:
+ complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
+
+ instruction = os.environ.get(complete_var)
+
+ if not instruction:
+ return
+
+ from .completion import shell_complete
+
+ rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
+ sys.exit(rv)
+
+
+class TyperCommand(click.core.Command):
+ def __init__(
+ self,
+ name: Optional[str],
+ *,
+ context_settings: Optional[Dict[str, Any]] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ params: Optional[List[click.Parameter]] = None,
+ help: Optional[str] = None,
+ epilog: Optional[str] = None,
+ short_help: Optional[str] = None,
+ options_metavar: Optional[str] = "[OPTIONS]",
+ add_help_option: bool = True,
+ no_args_is_help: bool = False,
+ hidden: bool = False,
+ deprecated: bool = False,
+ # Rich settings
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
+ rich_help_panel: Union[str, None] = None,
+ ) -> None:
+ super().__init__(
+ name=name,
+ context_settings=context_settings,
+ callback=callback,
+ params=params,
+ help=help,
+ epilog=epilog,
+ short_help=short_help,
+ options_metavar=options_metavar,
+ add_help_option=add_help_option,
+ no_args_is_help=no_args_is_help,
+ hidden=hidden,
+ deprecated=deprecated,
+ )
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
+ self.rich_help_panel = rich_help_panel
+
+ def format_options(
+ self, ctx: click.Context, formatter: click.HelpFormatter
+ ) -> None:
+ _typer_format_options(self, ctx=ctx, formatter=formatter)
+
+ def _main_shell_completion(
+ self,
+ ctx_args: MutableMapping[str, Any],
+ prog_name: str,
+ complete_var: Optional[str] = None,
+ ) -> None:
+ _typer_main_shell_completion(
+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
+ )
+
+ def main(
+ self,
+ args: Optional[Sequence[str]] = None,
+ prog_name: Optional[str] = None,
+ complete_var: Optional[str] = None,
+ standalone_mode: bool = True,
+ windows_expand_args: bool = True,
+ **extra: Any,
+ ) -> Any:
+ return _main(
+ self,
+ args=args,
+ prog_name=prog_name,
+ complete_var=complete_var,
+ standalone_mode=standalone_mode,
+ windows_expand_args=windows_expand_args,
+ rich_markup_mode=self.rich_markup_mode,
+ **extra,
+ )
+
+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
+ if not rich or self.rich_markup_mode is None:
+ return super().format_help(ctx, formatter)
+ return rich_utils.rich_format_help(
+ obj=self,
+ ctx=ctx,
+ markup_mode=self.rich_markup_mode,
+ )
+
+
+class TyperGroup(click.core.Group):
+ def __init__(
+ self,
+ *,
+ name: Optional[str] = None,
+ commands: Optional[
+ Union[Dict[str, click.Command], Sequence[click.Command]]
+ ] = None,
+ # Rich settings
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
+ rich_help_panel: Union[str, None] = None,
+ **attrs: Any,
+ ) -> None:
+ super().__init__(name=name, commands=commands, **attrs)
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
+ self.rich_help_panel = rich_help_panel
+
+ def format_options(
+ self, ctx: click.Context, formatter: click.HelpFormatter
+ ) -> None:
+ _typer_format_options(self, ctx=ctx, formatter=formatter)
+ self.format_commands(ctx, formatter)
+
+ def _main_shell_completion(
+ self,
+ ctx_args: MutableMapping[str, Any],
+ prog_name: str,
+ complete_var: Optional[str] = None,
+ ) -> None:
+ _typer_main_shell_completion(
+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
+ )
+
+ def main(
+ self,
+ args: Optional[Sequence[str]] = None,
+ prog_name: Optional[str] = None,
+ complete_var: Optional[str] = None,
+ standalone_mode: bool = True,
+ windows_expand_args: bool = True,
+ **extra: Any,
+ ) -> Any:
+ return _main(
+ self,
+ args=args,
+ prog_name=prog_name,
+ complete_var=complete_var,
+ standalone_mode=standalone_mode,
+ windows_expand_args=windows_expand_args,
+ rich_markup_mode=self.rich_markup_mode,
+ **extra,
+ )
+
+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
+ if not rich or self.rich_markup_mode is None:
+ return super().format_help(ctx, formatter)
+ return rich_utils.rich_format_help(
+ obj=self,
+ ctx=ctx,
+ markup_mode=self.rich_markup_mode,
+ )
+
+ def list_commands(self, ctx: click.Context) -> List[str]:
+ """Returns a list of subcommand names.
+ Note that in Click's Group class, these are sorted.
+ In Typer, we wish to maintain the original order of creation (cf Issue #933)"""
+ return [n for n, c in self.commands.items()]
diff --git a/venv/lib/python3.10/site-packages/typer/main.py b/venv/lib/python3.10/site-packages/typer/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..59e22c77aaac18f3f4194201e2a118dfa136b8a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/main.py
@@ -0,0 +1,1145 @@
+import inspect
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import traceback
+from datetime import datetime
+from enum import Enum
+from functools import update_wrapper
+from pathlib import Path
+from traceback import FrameSummary, StackSummary
+from types import TracebackType
+from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
+from uuid import UUID
+
+import click
+from typer._types import TyperChoice
+
+from ._typing import get_args, get_origin, is_union
+from .completion import get_completion_inspect_parameters
+from .core import (
+ DEFAULT_MARKUP_MODE,
+ MarkupMode,
+ TyperArgument,
+ TyperCommand,
+ TyperGroup,
+ TyperOption,
+)
+from .models import (
+ AnyType,
+ ArgumentInfo,
+ CommandFunctionType,
+ CommandInfo,
+ Default,
+ DefaultPlaceholder,
+ DeveloperExceptionConfig,
+ FileBinaryRead,
+ FileBinaryWrite,
+ FileText,
+ FileTextWrite,
+ NoneType,
+ OptionInfo,
+ ParameterInfo,
+ ParamMeta,
+ Required,
+ TyperInfo,
+ TyperPath,
+)
+from .utils import get_params_from_function
+
+try:
+ import rich
+ from rich.traceback import Traceback
+
+ from . import rich_utils
+
+ console_stderr = rich_utils._get_rich_console(stderr=True)
+
+except ImportError: # pragma: no cover
+ rich = None # type: ignore
+
+_original_except_hook = sys.excepthook
+_typer_developer_exception_attr_name = "__typer_developer_exception__"
+
+
+def except_hook(
+ exc_type: Type[BaseException], exc_value: BaseException, tb: Optional[TracebackType]
+) -> None:
+ exception_config: Union[DeveloperExceptionConfig, None] = getattr(
+ exc_value, _typer_developer_exception_attr_name, None
+ )
+ standard_traceback = os.getenv("_TYPER_STANDARD_TRACEBACK")
+ if (
+ standard_traceback
+ or not exception_config
+ or not exception_config.pretty_exceptions_enable
+ ):
+ _original_except_hook(exc_type, exc_value, tb)
+ return
+ typer_path = os.path.dirname(__file__)
+ click_path = os.path.dirname(click.__file__)
+ supress_internal_dir_names = [typer_path, click_path]
+ exc = exc_value
+ if rich:
+ from .rich_utils import MAX_WIDTH
+
+ rich_tb = Traceback.from_exception(
+ type(exc),
+ exc,
+ exc.__traceback__,
+ show_locals=exception_config.pretty_exceptions_show_locals,
+ suppress=supress_internal_dir_names,
+ width=MAX_WIDTH,
+ )
+ console_stderr.print(rich_tb)
+ return
+ tb_exc = traceback.TracebackException.from_exception(exc)
+ stack: List[FrameSummary] = []
+ for frame in tb_exc.stack:
+ if any(frame.filename.startswith(path) for path in supress_internal_dir_names):
+ if not exception_config.pretty_exceptions_short:
+ # Hide the line for internal libraries, Typer and Click
+ stack.append(
+ traceback.FrameSummary(
+ filename=frame.filename,
+ lineno=frame.lineno,
+ name=frame.name,
+ line="",
+ )
+ )
+ else:
+ stack.append(frame)
+ # Type ignore ref: https://github.com/python/typeshed/pull/8244
+ final_stack_summary = StackSummary.from_list(stack)
+ tb_exc.stack = final_stack_summary
+ for line in tb_exc.format():
+ print(line, file=sys.stderr)
+ return
+
+
+def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:
+ install_param, show_param = get_completion_inspect_parameters()
+ click_install_param, _ = get_click_param(install_param)
+ click_show_param, _ = get_click_param(show_param)
+ return click_install_param, click_show_param
+
+
+class Typer:
+ def __init__(
+ self,
+ *,
+ name: Optional[str] = Default(None),
+ cls: Optional[Type[TyperGroup]] = Default(None),
+ invoke_without_command: bool = Default(False),
+ no_args_is_help: bool = Default(False),
+ subcommand_metavar: Optional[str] = Default(None),
+ chain: bool = Default(False),
+ result_callback: Optional[Callable[..., Any]] = Default(None),
+ # Command
+ context_settings: Optional[Dict[Any, Any]] = Default(None),
+ callback: Optional[Callable[..., Any]] = Default(None),
+ help: Optional[str] = Default(None),
+ epilog: Optional[str] = Default(None),
+ short_help: Optional[str] = Default(None),
+ options_metavar: str = Default("[OPTIONS]"),
+ add_help_option: bool = Default(True),
+ hidden: bool = Default(False),
+ deprecated: bool = Default(False),
+ add_completion: bool = True,
+ # Rich settings
+ rich_markup_mode: MarkupMode = Default(DEFAULT_MARKUP_MODE),
+ rich_help_panel: Union[str, None] = Default(None),
+ pretty_exceptions_enable: bool = True,
+ pretty_exceptions_show_locals: bool = True,
+ pretty_exceptions_short: bool = True,
+ ):
+ self._add_completion = add_completion
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
+ self.rich_help_panel = rich_help_panel
+ self.pretty_exceptions_enable = pretty_exceptions_enable
+ self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
+ self.pretty_exceptions_short = pretty_exceptions_short
+ self.info = TyperInfo(
+ name=name,
+ cls=cls,
+ invoke_without_command=invoke_without_command,
+ no_args_is_help=no_args_is_help,
+ subcommand_metavar=subcommand_metavar,
+ chain=chain,
+ result_callback=result_callback,
+ context_settings=context_settings,
+ callback=callback,
+ help=help,
+ epilog=epilog,
+ short_help=short_help,
+ options_metavar=options_metavar,
+ add_help_option=add_help_option,
+ hidden=hidden,
+ deprecated=deprecated,
+ )
+ self.registered_groups: List[TyperInfo] = []
+ self.registered_commands: List[CommandInfo] = []
+ self.registered_callback: Optional[TyperInfo] = None
+
+ def callback(
+ self,
+ *,
+ cls: Optional[Type[TyperGroup]] = Default(None),
+ invoke_without_command: bool = Default(False),
+ no_args_is_help: bool = Default(False),
+ subcommand_metavar: Optional[str] = Default(None),
+ chain: bool = Default(False),
+ result_callback: Optional[Callable[..., Any]] = Default(None),
+ # Command
+ context_settings: Optional[Dict[Any, Any]] = Default(None),
+ help: Optional[str] = Default(None),
+ epilog: Optional[str] = Default(None),
+ short_help: Optional[str] = Default(None),
+ options_metavar: str = Default("[OPTIONS]"),
+ add_help_option: bool = Default(True),
+ hidden: bool = Default(False),
+ deprecated: bool = Default(False),
+ # Rich settings
+ rich_help_panel: Union[str, None] = Default(None),
+ ) -> Callable[[CommandFunctionType], CommandFunctionType]:
+ def decorator(f: CommandFunctionType) -> CommandFunctionType:
+ self.registered_callback = TyperInfo(
+ cls=cls,
+ invoke_without_command=invoke_without_command,
+ no_args_is_help=no_args_is_help,
+ subcommand_metavar=subcommand_metavar,
+ chain=chain,
+ result_callback=result_callback,
+ context_settings=context_settings,
+ callback=f,
+ help=help,
+ epilog=epilog,
+ short_help=short_help,
+ options_metavar=options_metavar,
+ add_help_option=add_help_option,
+ hidden=hidden,
+ deprecated=deprecated,
+ rich_help_panel=rich_help_panel,
+ )
+ return f
+
+ return decorator
+
+ def command(
+ self,
+ name: Optional[str] = None,
+ *,
+ cls: Optional[Type[TyperCommand]] = None,
+ context_settings: Optional[Dict[Any, Any]] = None,
+ help: Optional[str] = None,
+ epilog: Optional[str] = None,
+ short_help: Optional[str] = None,
+ options_metavar: str = "[OPTIONS]",
+ add_help_option: bool = True,
+ no_args_is_help: bool = False,
+ hidden: bool = False,
+ deprecated: bool = False,
+ # Rich settings
+ rich_help_panel: Union[str, None] = Default(None),
+ ) -> Callable[[CommandFunctionType], CommandFunctionType]:
+ if cls is None:
+ cls = TyperCommand
+
+ def decorator(f: CommandFunctionType) -> CommandFunctionType:
+ self.registered_commands.append(
+ CommandInfo(
+ name=name,
+ cls=cls,
+ context_settings=context_settings,
+ callback=f,
+ help=help,
+ epilog=epilog,
+ short_help=short_help,
+ options_metavar=options_metavar,
+ add_help_option=add_help_option,
+ no_args_is_help=no_args_is_help,
+ hidden=hidden,
+ deprecated=deprecated,
+ # Rich settings
+ rich_help_panel=rich_help_panel,
+ )
+ )
+ return f
+
+ return decorator
+
+ def add_typer(
+ self,
+ typer_instance: "Typer",
+ *,
+ name: Optional[str] = Default(None),
+ cls: Optional[Type[TyperGroup]] = Default(None),
+ invoke_without_command: bool = Default(False),
+ no_args_is_help: bool = Default(False),
+ subcommand_metavar: Optional[str] = Default(None),
+ chain: bool = Default(False),
+ result_callback: Optional[Callable[..., Any]] = Default(None),
+ # Command
+ context_settings: Optional[Dict[Any, Any]] = Default(None),
+ callback: Optional[Callable[..., Any]] = Default(None),
+ help: Optional[str] = Default(None),
+ epilog: Optional[str] = Default(None),
+ short_help: Optional[str] = Default(None),
+ options_metavar: str = Default("[OPTIONS]"),
+ add_help_option: bool = Default(True),
+ hidden: bool = Default(False),
+ deprecated: bool = Default(False),
+ # Rich settings
+ rich_help_panel: Union[str, None] = Default(None),
+ ) -> None:
+ self.registered_groups.append(
+ TyperInfo(
+ typer_instance,
+ name=name,
+ cls=cls,
+ invoke_without_command=invoke_without_command,
+ no_args_is_help=no_args_is_help,
+ subcommand_metavar=subcommand_metavar,
+ chain=chain,
+ result_callback=result_callback,
+ context_settings=context_settings,
+ callback=callback,
+ help=help,
+ epilog=epilog,
+ short_help=short_help,
+ options_metavar=options_metavar,
+ add_help_option=add_help_option,
+ hidden=hidden,
+ deprecated=deprecated,
+ rich_help_panel=rich_help_panel,
+ )
+ )
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ if sys.excepthook != except_hook:
+ sys.excepthook = except_hook
+ try:
+ return get_command(self)(*args, **kwargs)
+ except Exception as e:
+ # Set a custom attribute to tell the hook to show nice exceptions for user
+ # code. An alternative/first implementation was a custom exception with
+ # raise custom_exc from e
+ # but that means the last error shown is the custom exception, not the
+ # actual error. This trick improves developer experience by showing the
+ # actual error last.
+ setattr(
+ e,
+ _typer_developer_exception_attr_name,
+ DeveloperExceptionConfig(
+ pretty_exceptions_enable=self.pretty_exceptions_enable,
+ pretty_exceptions_show_locals=self.pretty_exceptions_show_locals,
+ pretty_exceptions_short=self.pretty_exceptions_short,
+ ),
+ )
+ raise e
+
+
+def get_group(typer_instance: Typer) -> TyperGroup:
+ group = get_group_from_info(
+ TyperInfo(typer_instance),
+ pretty_exceptions_short=typer_instance.pretty_exceptions_short,
+ rich_markup_mode=typer_instance.rich_markup_mode,
+ )
+ return group
+
+
+def get_command(typer_instance: Typer) -> click.Command:
+ if typer_instance._add_completion:
+ click_install_param, click_show_param = get_install_completion_arguments()
+ if (
+ typer_instance.registered_callback
+ or typer_instance.info.callback
+ or typer_instance.registered_groups
+ or len(typer_instance.registered_commands) > 1
+ ):
+ # Create a Group
+ click_command: click.Command = get_group(typer_instance)
+ if typer_instance._add_completion:
+ click_command.params.append(click_install_param)
+ click_command.params.append(click_show_param)
+ return click_command
+ elif len(typer_instance.registered_commands) == 1:
+ # Create a single Command
+ single_command = typer_instance.registered_commands[0]
+
+ if not single_command.context_settings and not isinstance(
+ typer_instance.info.context_settings, DefaultPlaceholder
+ ):
+ single_command.context_settings = typer_instance.info.context_settings
+
+ click_command = get_command_from_info(
+ single_command,
+ pretty_exceptions_short=typer_instance.pretty_exceptions_short,
+ rich_markup_mode=typer_instance.rich_markup_mode,
+ )
+ if typer_instance._add_completion:
+ click_command.params.append(click_install_param)
+ click_command.params.append(click_show_param)
+ return click_command
+ raise RuntimeError(
+ "Could not get a command for this Typer instance"
+ ) # pragma: no cover
+
+
+def solve_typer_info_help(typer_info: TyperInfo) -> str:
+ # Priority 1: Explicit value was set in app.add_typer()
+ if not isinstance(typer_info.help, DefaultPlaceholder):
+ return inspect.cleandoc(typer_info.help or "")
+ # Priority 2: Explicit value was set in sub_app.callback()
+ try:
+ callback_help = typer_info.typer_instance.registered_callback.help
+ if not isinstance(callback_help, DefaultPlaceholder):
+ return inspect.cleandoc(callback_help or "")
+ except AttributeError:
+ pass
+ # Priority 3: Explicit value was set in sub_app = typer.Typer()
+ try:
+ instance_help = typer_info.typer_instance.info.help
+ if not isinstance(instance_help, DefaultPlaceholder):
+ return inspect.cleandoc(instance_help or "")
+ except AttributeError:
+ pass
+ # Priority 4: Implicit inference from callback docstring in app.add_typer()
+ if typer_info.callback:
+ doc = inspect.getdoc(typer_info.callback)
+ if doc:
+ return doc
+ # Priority 5: Implicit inference from callback docstring in @app.callback()
+ try:
+ callback = typer_info.typer_instance.registered_callback.callback
+ if not isinstance(callback, DefaultPlaceholder):
+ doc = inspect.getdoc(callback or "")
+ if doc:
+ return doc
+ except AttributeError:
+ pass
+ # Priority 6: Implicit inference from callback docstring in typer.Typer()
+ try:
+ instance_callback = typer_info.typer_instance.info.callback
+ if not isinstance(instance_callback, DefaultPlaceholder):
+ doc = inspect.getdoc(instance_callback)
+ if doc:
+ return doc
+ except AttributeError:
+ pass
+ # Value not set, use the default
+ return typer_info.help.value
+
+
+def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:
+ values: Dict[str, Any] = {}
+ for name, value in typer_info.__dict__.items():
+ # Priority 1: Value was set in app.add_typer()
+ if not isinstance(value, DefaultPlaceholder):
+ values[name] = value
+ continue
+ # Priority 2: Value was set in @subapp.callback()
+ try:
+ callback_value = getattr(
+ typer_info.typer_instance.registered_callback, # type: ignore
+ name,
+ )
+ if not isinstance(callback_value, DefaultPlaceholder):
+ values[name] = callback_value
+ continue
+ except AttributeError:
+ pass
+ # Priority 3: Value set in subapp = typer.Typer()
+ try:
+ instance_value = getattr(
+ typer_info.typer_instance.info, # type: ignore
+ name,
+ )
+ if not isinstance(instance_value, DefaultPlaceholder):
+ values[name] = instance_value
+ continue
+ except AttributeError:
+ pass
+ # Value not set, use the default
+ values[name] = value.value
+ values["help"] = solve_typer_info_help(typer_info)
+ return TyperInfo(**values)
+
+
+def get_group_from_info(
+ group_info: TyperInfo,
+ *,
+ pretty_exceptions_short: bool,
+ rich_markup_mode: MarkupMode,
+) -> TyperGroup:
+ assert group_info.typer_instance, (
+ "A Typer instance is needed to generate a Click Group"
+ )
+ commands: Dict[str, click.Command] = {}
+ for command_info in group_info.typer_instance.registered_commands:
+ command = get_command_from_info(
+ command_info=command_info,
+ pretty_exceptions_short=pretty_exceptions_short,
+ rich_markup_mode=rich_markup_mode,
+ )
+ if command.name:
+ commands[command.name] = command
+ for sub_group_info in group_info.typer_instance.registered_groups:
+ sub_group = get_group_from_info(
+ sub_group_info,
+ pretty_exceptions_short=pretty_exceptions_short,
+ rich_markup_mode=rich_markup_mode,
+ )
+ if sub_group.name:
+ commands[sub_group.name] = sub_group
+ else:
+ if sub_group.callback:
+ import warnings
+
+ warnings.warn(
+ "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",
+ stacklevel=5,
+ )
+ for sub_command_name, sub_command in sub_group.commands.items():
+ commands[sub_command_name] = sub_command
+ solved_info = solve_typer_info_defaults(group_info)
+ (
+ params,
+ convertors,
+ context_param_name,
+ ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback)
+ cls = solved_info.cls or TyperGroup
+ assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}"
+ group = cls(
+ name=solved_info.name or "",
+ commands=commands,
+ invoke_without_command=solved_info.invoke_without_command,
+ no_args_is_help=solved_info.no_args_is_help,
+ subcommand_metavar=solved_info.subcommand_metavar,
+ chain=solved_info.chain,
+ result_callback=solved_info.result_callback,
+ context_settings=solved_info.context_settings,
+ callback=get_callback(
+ callback=solved_info.callback,
+ params=params,
+ convertors=convertors,
+ context_param_name=context_param_name,
+ pretty_exceptions_short=pretty_exceptions_short,
+ ),
+ params=params,
+ help=solved_info.help,
+ epilog=solved_info.epilog,
+ short_help=solved_info.short_help,
+ options_metavar=solved_info.options_metavar,
+ add_help_option=solved_info.add_help_option,
+ hidden=solved_info.hidden,
+ deprecated=solved_info.deprecated,
+ rich_markup_mode=rich_markup_mode,
+ # Rich settings
+ rich_help_panel=solved_info.rich_help_panel,
+ )
+ return group
+
+
+def get_command_name(name: str) -> str:
+ return name.lower().replace("_", "-")
+
+
+def get_params_convertors_ctx_param_name_from_function(
+ callback: Optional[Callable[..., Any]],
+) -> Tuple[List[Union[click.Argument, click.Option]], Dict[str, Any], Optional[str]]:
+ params = []
+ convertors = {}
+ context_param_name = None
+ if callback:
+ parameters = get_params_from_function(callback)
+ for param_name, param in parameters.items():
+ if lenient_issubclass(param.annotation, click.Context):
+ context_param_name = param_name
+ continue
+ click_param, convertor = get_click_param(param)
+ if convertor:
+ convertors[param_name] = convertor
+ params.append(click_param)
+ return params, convertors, context_param_name
+
+
+def get_command_from_info(
+ command_info: CommandInfo,
+ *,
+ pretty_exceptions_short: bool,
+ rich_markup_mode: MarkupMode,
+) -> click.Command:
+ assert command_info.callback, "A command must have a callback function"
+ name = command_info.name or get_command_name(command_info.callback.__name__)
+ use_help = command_info.help
+ if use_help is None:
+ use_help = inspect.getdoc(command_info.callback)
+ else:
+ use_help = inspect.cleandoc(use_help)
+ (
+ params,
+ convertors,
+ context_param_name,
+ ) = get_params_convertors_ctx_param_name_from_function(command_info.callback)
+ cls = command_info.cls or TyperCommand
+ command = cls(
+ name=name,
+ context_settings=command_info.context_settings,
+ callback=get_callback(
+ callback=command_info.callback,
+ params=params,
+ convertors=convertors,
+ context_param_name=context_param_name,
+ pretty_exceptions_short=pretty_exceptions_short,
+ ),
+ params=params, # type: ignore
+ help=use_help,
+ epilog=command_info.epilog,
+ short_help=command_info.short_help,
+ options_metavar=command_info.options_metavar,
+ add_help_option=command_info.add_help_option,
+ no_args_is_help=command_info.no_args_is_help,
+ hidden=command_info.hidden,
+ deprecated=command_info.deprecated,
+ rich_markup_mode=rich_markup_mode,
+ # Rich settings
+ rich_help_panel=command_info.rich_help_panel,
+ )
+ return command
+
+
+def determine_type_convertor(type_: Any) -> Optional[Callable[[Any], Any]]:
+ convertor: Optional[Callable[[Any], Any]] = None
+ if lenient_issubclass(type_, Path):
+ convertor = param_path_convertor
+ if lenient_issubclass(type_, Enum):
+ convertor = generate_enum_convertor(type_)
+ return convertor
+
+
+def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:
+ if value is not None:
+ return Path(value)
+ return None
+
+
+def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:
+ val_map = {str(val.value): val for val in enum}
+
+ def convertor(value: Any) -> Any:
+ if value is not None:
+ val = str(value)
+ if val in val_map:
+ key = val_map[val]
+ return enum(key)
+
+ return convertor
+
+
+def generate_list_convertor(
+ convertor: Optional[Callable[[Any], Any]], default_value: Optional[Any]
+) -> Callable[[Sequence[Any]], Optional[List[Any]]]:
+ def internal_convertor(value: Sequence[Any]) -> Optional[List[Any]]:
+ if default_value is None and len(value) == 0:
+ return None
+ return [convertor(v) if convertor else v for v in value]
+
+ return internal_convertor
+
+
+def generate_tuple_convertor(
+ types: Sequence[Any],
+) -> Callable[[Optional[Tuple[Any, ...]]], Optional[Tuple[Any, ...]]]:
+ convertors = [determine_type_convertor(type_) for type_ in types]
+
+ def internal_convertor(
+ param_args: Optional[Tuple[Any, ...]],
+ ) -> Optional[Tuple[Any, ...]]:
+ if param_args is None:
+ return None
+ return tuple(
+ convertor(arg) if convertor else arg
+ for (convertor, arg) in zip(convertors, param_args)
+ )
+
+ return internal_convertor
+
+
+def get_callback(
+ *,
+ callback: Optional[Callable[..., Any]] = None,
+ params: Sequence[click.Parameter] = [],
+ convertors: Optional[Dict[str, Callable[[str], Any]]] = None,
+ context_param_name: Optional[str] = None,
+ pretty_exceptions_short: bool,
+) -> Optional[Callable[..., Any]]:
+ use_convertors = convertors or {}
+ if not callback:
+ return None
+ parameters = get_params_from_function(callback)
+ use_params: Dict[str, Any] = {}
+ for param_name in parameters:
+ use_params[param_name] = None
+ for param in params:
+ if param.name:
+ use_params[param.name] = param.default
+
+ def wrapper(**kwargs: Any) -> Any:
+ _rich_traceback_guard = pretty_exceptions_short # noqa: F841
+ for k, v in kwargs.items():
+ if k in use_convertors:
+ use_params[k] = use_convertors[k](v)
+ else:
+ use_params[k] = v
+ if context_param_name:
+ use_params[context_param_name] = click.get_current_context()
+ return callback(**use_params)
+
+ update_wrapper(wrapper, callback)
+ return wrapper
+
+
+def get_click_type(
+ *, annotation: Any, parameter_info: ParameterInfo
+) -> click.ParamType:
+ if parameter_info.click_type is not None:
+ return parameter_info.click_type
+
+ elif parameter_info.parser is not None:
+ return click.types.FuncParamType(parameter_info.parser)
+
+ elif annotation is str:
+ return click.STRING
+ elif annotation is int:
+ if parameter_info.min is not None or parameter_info.max is not None:
+ min_ = None
+ max_ = None
+ if parameter_info.min is not None:
+ min_ = int(parameter_info.min)
+ if parameter_info.max is not None:
+ max_ = int(parameter_info.max)
+ return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp)
+ else:
+ return click.INT
+ elif annotation is float:
+ if parameter_info.min is not None or parameter_info.max is not None:
+ return click.FloatRange(
+ min=parameter_info.min,
+ max=parameter_info.max,
+ clamp=parameter_info.clamp,
+ )
+ else:
+ return click.FLOAT
+ elif annotation is bool:
+ return click.BOOL
+ elif annotation == UUID:
+ return click.UUID
+ elif annotation == datetime:
+ return click.DateTime(formats=parameter_info.formats)
+ elif (
+ annotation == Path
+ or parameter_info.allow_dash
+ or parameter_info.path_type
+ or parameter_info.resolve_path
+ ):
+ return TyperPath(
+ exists=parameter_info.exists,
+ file_okay=parameter_info.file_okay,
+ dir_okay=parameter_info.dir_okay,
+ writable=parameter_info.writable,
+ readable=parameter_info.readable,
+ resolve_path=parameter_info.resolve_path,
+ allow_dash=parameter_info.allow_dash,
+ path_type=parameter_info.path_type,
+ )
+ elif lenient_issubclass(annotation, FileTextWrite):
+ return click.File(
+ mode=parameter_info.mode or "w",
+ encoding=parameter_info.encoding,
+ errors=parameter_info.errors,
+ lazy=parameter_info.lazy,
+ atomic=parameter_info.atomic,
+ )
+ elif lenient_issubclass(annotation, FileText):
+ return click.File(
+ mode=parameter_info.mode or "r",
+ encoding=parameter_info.encoding,
+ errors=parameter_info.errors,
+ lazy=parameter_info.lazy,
+ atomic=parameter_info.atomic,
+ )
+ elif lenient_issubclass(annotation, FileBinaryRead):
+ return click.File(
+ mode=parameter_info.mode or "rb",
+ encoding=parameter_info.encoding,
+ errors=parameter_info.errors,
+ lazy=parameter_info.lazy,
+ atomic=parameter_info.atomic,
+ )
+ elif lenient_issubclass(annotation, FileBinaryWrite):
+ return click.File(
+ mode=parameter_info.mode or "wb",
+ encoding=parameter_info.encoding,
+ errors=parameter_info.errors,
+ lazy=parameter_info.lazy,
+ atomic=parameter_info.atomic,
+ )
+ elif lenient_issubclass(annotation, Enum):
+ # The custom TyperChoice is only needed for Click < 8.2.0, to parse the
+ # command line values matching them to the enum values. Click 8.2.0 added
+ # support for enum values but reading enum names.
+ # Passing here the list of enum values (instead of just the enum) accounts for
+ # Click < 8.2.0.
+ return TyperChoice(
+ [item.value for item in annotation],
+ case_sensitive=parameter_info.case_sensitive,
+ )
+ raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover
+
+
+def lenient_issubclass(
+ cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]
+) -> bool:
+ return isinstance(cls, type) and issubclass(cls, class_or_tuple)
+
+
+def get_click_param(
+ param: ParamMeta,
+) -> Tuple[Union[click.Argument, click.Option], Any]:
+ # First, find out what will be:
+ # * ParamInfo (ArgumentInfo or OptionInfo)
+ # * default_value
+ # * required
+ default_value = None
+ required = False
+ if isinstance(param.default, ParameterInfo):
+ parameter_info = param.default
+ if parameter_info.default == Required:
+ required = True
+ else:
+ default_value = parameter_info.default
+ elif param.default == Required or param.default is param.empty:
+ required = True
+ parameter_info = ArgumentInfo()
+ else:
+ default_value = param.default
+ parameter_info = OptionInfo()
+ annotation: Any
+ if param.annotation is not param.empty:
+ annotation = param.annotation
+ else:
+ annotation = str
+ main_type = annotation
+ is_list = False
+ is_tuple = False
+ parameter_type: Any = None
+ is_flag = None
+ origin = get_origin(main_type)
+
+ if origin is not None:
+ # Handle SomeType | None and Optional[SomeType]
+ if is_union(origin):
+ types = []
+ for type_ in get_args(main_type):
+ if type_ is NoneType:
+ continue
+ types.append(type_)
+ assert len(types) == 1, "Typer Currently doesn't support Union types"
+ main_type = types[0]
+ origin = get_origin(main_type)
+ # Handle Tuples and Lists
+ if lenient_issubclass(origin, List):
+ main_type = get_args(main_type)[0]
+ assert not get_origin(main_type), (
+ "List types with complex sub-types are not currently supported"
+ )
+ is_list = True
+ elif lenient_issubclass(origin, Tuple): # type: ignore
+ types = []
+ for type_ in get_args(main_type):
+ assert not get_origin(type_), (
+ "Tuple types with complex sub-types are not currently supported"
+ )
+ types.append(
+ get_click_type(annotation=type_, parameter_info=parameter_info)
+ )
+ parameter_type = tuple(types)
+ is_tuple = True
+ if parameter_type is None:
+ parameter_type = get_click_type(
+ annotation=main_type, parameter_info=parameter_info
+ )
+ convertor = determine_type_convertor(main_type)
+ if is_list:
+ convertor = generate_list_convertor(
+ convertor=convertor, default_value=default_value
+ )
+ if is_tuple:
+ convertor = generate_tuple_convertor(get_args(main_type))
+ if isinstance(parameter_info, OptionInfo):
+ if main_type is bool:
+ is_flag = True
+ # Click doesn't accept a flag of type bool, only None, and then it sets it
+ # to bool internally
+ parameter_type = None
+ default_option_name = get_command_name(param.name)
+ if is_flag:
+ default_option_declaration = (
+ f"--{default_option_name}/--no-{default_option_name}"
+ )
+ else:
+ default_option_declaration = f"--{default_option_name}"
+ param_decls = [param.name]
+ if parameter_info.param_decls:
+ param_decls.extend(parameter_info.param_decls)
+ else:
+ param_decls.append(default_option_declaration)
+ return (
+ TyperOption(
+ # Option
+ param_decls=param_decls,
+ show_default=parameter_info.show_default,
+ prompt=parameter_info.prompt,
+ confirmation_prompt=parameter_info.confirmation_prompt,
+ prompt_required=parameter_info.prompt_required,
+ hide_input=parameter_info.hide_input,
+ is_flag=is_flag,
+ multiple=is_list,
+ count=parameter_info.count,
+ allow_from_autoenv=parameter_info.allow_from_autoenv,
+ type=parameter_type,
+ help=parameter_info.help,
+ hidden=parameter_info.hidden,
+ show_choices=parameter_info.show_choices,
+ show_envvar=parameter_info.show_envvar,
+ # Parameter
+ required=required,
+ default=default_value,
+ callback=get_param_callback(
+ callback=parameter_info.callback, convertor=convertor
+ ),
+ metavar=parameter_info.metavar,
+ expose_value=parameter_info.expose_value,
+ is_eager=parameter_info.is_eager,
+ envvar=parameter_info.envvar,
+ shell_complete=parameter_info.shell_complete,
+ autocompletion=get_param_completion(parameter_info.autocompletion),
+ # Rich settings
+ rich_help_panel=parameter_info.rich_help_panel,
+ ),
+ convertor,
+ )
+ elif isinstance(parameter_info, ArgumentInfo):
+ param_decls = [param.name]
+ nargs = None
+ if is_list:
+ nargs = -1
+ return (
+ TyperArgument(
+ # Argument
+ param_decls=param_decls,
+ type=parameter_type,
+ required=required,
+ nargs=nargs,
+ # TyperArgument
+ show_default=parameter_info.show_default,
+ show_choices=parameter_info.show_choices,
+ show_envvar=parameter_info.show_envvar,
+ help=parameter_info.help,
+ hidden=parameter_info.hidden,
+ # Parameter
+ default=default_value,
+ callback=get_param_callback(
+ callback=parameter_info.callback, convertor=convertor
+ ),
+ metavar=parameter_info.metavar,
+ expose_value=parameter_info.expose_value,
+ is_eager=parameter_info.is_eager,
+ envvar=parameter_info.envvar,
+ shell_complete=parameter_info.shell_complete,
+ autocompletion=get_param_completion(parameter_info.autocompletion),
+ # Rich settings
+ rich_help_panel=parameter_info.rich_help_panel,
+ ),
+ convertor,
+ )
+ raise AssertionError("A click.Parameter should be returned") # pragma: no cover
+
+
+def get_param_callback(
+ *,
+ callback: Optional[Callable[..., Any]] = None,
+ convertor: Optional[Callable[..., Any]] = None,
+) -> Optional[Callable[..., Any]]:
+ if not callback:
+ return None
+ parameters = get_params_from_function(callback)
+ ctx_name = None
+ click_param_name = None
+ value_name = None
+ untyped_names: List[str] = []
+ for param_name, param_sig in parameters.items():
+ if lenient_issubclass(param_sig.annotation, click.Context):
+ ctx_name = param_name
+ elif lenient_issubclass(param_sig.annotation, click.Parameter):
+ click_param_name = param_name
+ else:
+ untyped_names.append(param_name)
+ # Extract value param name first
+ if untyped_names:
+ value_name = untyped_names.pop()
+ # If context and Click param were not typed (old/Click callback style) extract them
+ if untyped_names:
+ if ctx_name is None:
+ ctx_name = untyped_names.pop(0)
+ if click_param_name is None:
+ if untyped_names:
+ click_param_name = untyped_names.pop(0)
+ if untyped_names:
+ raise click.ClickException(
+ "Too many CLI parameter callback function parameters"
+ )
+
+ def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
+ use_params: Dict[str, Any] = {}
+ if ctx_name:
+ use_params[ctx_name] = ctx
+ if click_param_name:
+ use_params[click_param_name] = param
+ if value_name:
+ if convertor:
+ use_value = convertor(value)
+ else:
+ use_value = value
+ use_params[value_name] = use_value
+ return callback(**use_params)
+
+ update_wrapper(wrapper, callback)
+ return wrapper
+
+
+def get_param_completion(
+ callback: Optional[Callable[..., Any]] = None,
+) -> Optional[Callable[..., Any]]:
+ if not callback:
+ return None
+ parameters = get_params_from_function(callback)
+ ctx_name = None
+ args_name = None
+ incomplete_name = None
+ unassigned_params = list(parameters.values())
+ for param_sig in unassigned_params[:]:
+ origin = get_origin(param_sig.annotation)
+ if lenient_issubclass(param_sig.annotation, click.Context):
+ ctx_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ elif lenient_issubclass(origin, List):
+ args_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ elif lenient_issubclass(param_sig.annotation, str):
+ incomplete_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ # If there are still unassigned parameters (not typed), extract by name
+ for param_sig in unassigned_params[:]:
+ if ctx_name is None and param_sig.name == "ctx":
+ ctx_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ elif args_name is None and param_sig.name == "args":
+ args_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ elif incomplete_name is None and param_sig.name == "incomplete":
+ incomplete_name = param_sig.name
+ unassigned_params.remove(param_sig)
+ # Extract value param name first
+ if unassigned_params:
+ show_params = " ".join([param.name for param in unassigned_params])
+ raise click.ClickException(
+ f"Invalid autocompletion callback parameters: {show_params}"
+ )
+
+ def wrapper(ctx: click.Context, args: List[str], incomplete: Optional[str]) -> Any:
+ use_params: Dict[str, Any] = {}
+ if ctx_name:
+ use_params[ctx_name] = ctx
+ if args_name:
+ use_params[args_name] = args
+ if incomplete_name:
+ use_params[incomplete_name] = incomplete
+ return callback(**use_params)
+
+ update_wrapper(wrapper, callback)
+ return wrapper
+
+
+def run(function: Callable[..., Any]) -> None:
+ app = Typer(add_completion=False)
+ app.command()(function)
+ app()
+
+
+def _is_macos() -> bool:
+ return platform.system() == "Darwin"
+
+
+def _is_linux_or_bsd() -> bool:
+ if platform.system() == "Linux":
+ return True
+
+ return "BSD" in platform.system()
+
+
+def launch(url: str, wait: bool = False, locate: bool = False) -> int:
+ """This function launches the given URL (or filename) in the default
+ viewer application for this file type. If this is an executable, it
+ might launch the executable in a new session. The return value is
+ the exit code of the launched application. Usually, ``0`` indicates
+ success.
+
+ This function handles url in different operating systems separately:
+ - On macOS (Darwin), it uses the 'open' command.
+ - On Linux and BSD, it uses 'xdg-open' if available.
+ - On Windows (and other OSes), it uses the standard webbrowser module.
+
+ The function avoids, when possible, using the webbrowser module on Linux and macOS
+ to prevent spammy terminal messages from some browsers (e.g., Chrome).
+
+ Examples::
+
+ typer.launch("https://typer.tiangolo.com/")
+ typer.launch("/my/downloaded/file", locate=True)
+
+ :param url: URL or filename of the thing to launch.
+ :param wait: Wait for the program to exit before returning. This
+ only works if the launched program blocks. In particular,
+ ``xdg-open`` on Linux does not block.
+ :param locate: if this is set to `True` then instead of launching the
+ application associated with the URL it will attempt to
+ launch a file manager with the file located. This
+ might have weird effects if the URL does not point to
+ the filesystem.
+ """
+
+ if url.startswith("http://") or url.startswith("https://"):
+ if _is_macos():
+ return subprocess.Popen(
+ ["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
+ ).wait()
+
+ has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None
+
+ if has_xdg_open:
+ return subprocess.Popen(
+ ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
+ ).wait()
+
+ import webbrowser
+
+ webbrowser.open(url)
+
+ return 0
+
+ else:
+ return click.launch(url)
diff --git a/venv/lib/python3.10/site-packages/typer/models.py b/venv/lib/python3.10/site-packages/typer/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0bddb965be67ec2e8fd7c045a9e53baa887a915
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/models.py
@@ -0,0 +1,544 @@
+import inspect
+import io
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Sequence,
+ Type,
+ TypeVar,
+ Union,
+)
+
+import click
+import click.shell_completion
+
+if TYPE_CHECKING: # pragma: no cover
+ from .core import TyperCommand, TyperGroup
+ from .main import Typer
+
+
+NoneType = type(None)
+
+AnyType = Type[Any]
+
+Required = ...
+
+
+class Context(click.Context):
+ pass
+
+
+class FileText(io.TextIOWrapper):
+ pass
+
+
+class FileTextWrite(FileText):
+ pass
+
+
+class FileBinaryRead(io.BufferedReader):
+ pass
+
+
+class FileBinaryWrite(io.BufferedWriter):
+ pass
+
+
+class CallbackParam(click.Parameter):
+ pass
+
+
+class DefaultPlaceholder:
+ """
+ You shouldn't use this class directly.
+
+ It's used internally to recognize when a default value has been overwritten, even
+ if the new value is `None`.
+ """
+
+ def __init__(self, value: Any):
+ self.value = value
+
+ def __bool__(self) -> bool:
+ return bool(self.value)
+
+
+DefaultType = TypeVar("DefaultType")
+
+CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any])
+
+
+def Default(value: DefaultType) -> DefaultType:
+ """
+ You shouldn't use this function directly.
+
+ It's used internally to recognize when a default value has been overwritten, even
+ if the new value is `None`.
+ """
+ return DefaultPlaceholder(value) # type: ignore
+
+
+class CommandInfo:
+ def __init__(
+ self,
+ name: Optional[str] = None,
+ *,
+ cls: Optional[Type["TyperCommand"]] = None,
+ context_settings: Optional[Dict[Any, Any]] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ help: Optional[str] = None,
+ epilog: Optional[str] = None,
+ short_help: Optional[str] = None,
+ options_metavar: str = "[OPTIONS]",
+ add_help_option: bool = True,
+ no_args_is_help: bool = False,
+ hidden: bool = False,
+ deprecated: bool = False,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ self.name = name
+ self.cls = cls
+ self.context_settings = context_settings
+ self.callback = callback
+ self.help = help
+ self.epilog = epilog
+ self.short_help = short_help
+ self.options_metavar = options_metavar
+ self.add_help_option = add_help_option
+ self.no_args_is_help = no_args_is_help
+ self.hidden = hidden
+ self.deprecated = deprecated
+ # Rich settings
+ self.rich_help_panel = rich_help_panel
+
+
+class TyperInfo:
+ def __init__(
+ self,
+ typer_instance: Optional["Typer"] = Default(None),
+ *,
+ name: Optional[str] = Default(None),
+ cls: Optional[Type["TyperGroup"]] = Default(None),
+ invoke_without_command: bool = Default(False),
+ no_args_is_help: bool = Default(False),
+ subcommand_metavar: Optional[str] = Default(None),
+ chain: bool = Default(False),
+ result_callback: Optional[Callable[..., Any]] = Default(None),
+ # Command
+ context_settings: Optional[Dict[Any, Any]] = Default(None),
+ callback: Optional[Callable[..., Any]] = Default(None),
+ help: Optional[str] = Default(None),
+ epilog: Optional[str] = Default(None),
+ short_help: Optional[str] = Default(None),
+ options_metavar: str = Default("[OPTIONS]"),
+ add_help_option: bool = Default(True),
+ hidden: bool = Default(False),
+ deprecated: bool = Default(False),
+ # Rich settings
+ rich_help_panel: Union[str, None] = Default(None),
+ ):
+ self.typer_instance = typer_instance
+ self.name = name
+ self.cls = cls
+ self.invoke_without_command = invoke_without_command
+ self.no_args_is_help = no_args_is_help
+ self.subcommand_metavar = subcommand_metavar
+ self.chain = chain
+ self.result_callback = result_callback
+ self.context_settings = context_settings
+ self.callback = callback
+ self.help = help
+ self.epilog = epilog
+ self.short_help = short_help
+ self.options_metavar = options_metavar
+ self.add_help_option = add_help_option
+ self.hidden = hidden
+ self.deprecated = deprecated
+ self.rich_help_panel = rich_help_panel
+
+
+class ParameterInfo:
+ def __init__(
+ self,
+ *,
+ default: Optional[Any] = None,
+ param_decls: Optional[Sequence[str]] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ click_type: Optional[click.ParamType] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ # Check if user has provided multiple custom parsers
+ if parser and click_type:
+ raise ValueError(
+ "Multiple custom type parsers provided. "
+ "`parser` and `click_type` may not both be provided."
+ )
+
+ self.default = default
+ self.param_decls = param_decls
+ self.callback = callback
+ self.metavar = metavar
+ self.expose_value = expose_value
+ self.is_eager = is_eager
+ self.envvar = envvar
+ self.shell_complete = shell_complete
+ self.autocompletion = autocompletion
+ self.default_factory = default_factory
+ # Custom type
+ self.parser = parser
+ self.click_type = click_type
+ # TyperArgument
+ self.show_default = show_default
+ self.show_choices = show_choices
+ self.show_envvar = show_envvar
+ self.help = help
+ self.hidden = hidden
+ # Choice
+ self.case_sensitive = case_sensitive
+ # Numbers
+ self.min = min
+ self.max = max
+ self.clamp = clamp
+ # DateTime
+ self.formats = formats
+ # File
+ self.mode = mode
+ self.encoding = encoding
+ self.errors = errors
+ self.lazy = lazy
+ self.atomic = atomic
+ # Path
+ self.exists = exists
+ self.file_okay = file_okay
+ self.dir_okay = dir_okay
+ self.writable = writable
+ self.readable = readable
+ self.resolve_path = resolve_path
+ self.allow_dash = allow_dash
+ self.path_type = path_type
+ # Rich settings
+ self.rich_help_panel = rich_help_panel
+
+
+class OptionInfo(ParameterInfo):
+ def __init__(
+ self,
+ *,
+ # ParameterInfo
+ default: Optional[Any] = None,
+ param_decls: Optional[Sequence[str]] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ click_type: Optional[click.ParamType] = None,
+ # Option
+ show_default: Union[bool, str] = True,
+ prompt: Union[bool, str] = False,
+ confirmation_prompt: bool = False,
+ prompt_required: bool = True,
+ hide_input: bool = False,
+ # TODO: remove is_flag and flag_value in a future release
+ is_flag: Optional[bool] = None,
+ flag_value: Optional[Any] = None,
+ count: bool = False,
+ allow_from_autoenv: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ super().__init__(
+ default=default,
+ param_decls=param_decls,
+ callback=callback,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ shell_complete=shell_complete,
+ autocompletion=autocompletion,
+ default_factory=default_factory,
+ # Custom type
+ parser=parser,
+ click_type=click_type,
+ # TyperArgument
+ show_default=show_default,
+ show_choices=show_choices,
+ show_envvar=show_envvar,
+ help=help,
+ hidden=hidden,
+ # Choice
+ case_sensitive=case_sensitive,
+ # Numbers
+ min=min,
+ max=max,
+ clamp=clamp,
+ # DateTime
+ formats=formats,
+ # File
+ mode=mode,
+ encoding=encoding,
+ errors=errors,
+ lazy=lazy,
+ atomic=atomic,
+ # Path
+ exists=exists,
+ file_okay=file_okay,
+ dir_okay=dir_okay,
+ writable=writable,
+ readable=readable,
+ resolve_path=resolve_path,
+ allow_dash=allow_dash,
+ path_type=path_type,
+ # Rich settings
+ rich_help_panel=rich_help_panel,
+ )
+ if is_flag is not None or flag_value is not None:
+ import warnings
+
+ warnings.warn(
+ "The 'is_flag' and 'flag_value' parameters are not supported by Typer "
+ "and will be removed entirely in a future release.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self.prompt = prompt
+ self.confirmation_prompt = confirmation_prompt
+ self.prompt_required = prompt_required
+ self.hide_input = hide_input
+ self.count = count
+ self.allow_from_autoenv = allow_from_autoenv
+
+
+class ArgumentInfo(ParameterInfo):
+ def __init__(
+ self,
+ *,
+ # ParameterInfo
+ default: Optional[Any] = None,
+ param_decls: Optional[Sequence[str]] = None,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ click_type: Optional[click.ParamType] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+ ):
+ super().__init__(
+ default=default,
+ param_decls=param_decls,
+ callback=callback,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ shell_complete=shell_complete,
+ autocompletion=autocompletion,
+ default_factory=default_factory,
+ # Custom type
+ parser=parser,
+ click_type=click_type,
+ # TyperArgument
+ show_default=show_default,
+ show_choices=show_choices,
+ show_envvar=show_envvar,
+ help=help,
+ hidden=hidden,
+ # Choice
+ case_sensitive=case_sensitive,
+ # Numbers
+ min=min,
+ max=max,
+ clamp=clamp,
+ # DateTime
+ formats=formats,
+ # File
+ mode=mode,
+ encoding=encoding,
+ errors=errors,
+ lazy=lazy,
+ atomic=atomic,
+ # Path
+ exists=exists,
+ file_okay=file_okay,
+ dir_okay=dir_okay,
+ writable=writable,
+ readable=readable,
+ resolve_path=resolve_path,
+ allow_dash=allow_dash,
+ path_type=path_type,
+ # Rich settings
+ rich_help_panel=rich_help_panel,
+ )
+
+
+class ParamMeta:
+ empty = inspect.Parameter.empty
+
+ def __init__(
+ self,
+ *,
+ name: str,
+ default: Any = inspect.Parameter.empty,
+ annotation: Any = inspect.Parameter.empty,
+ ) -> None:
+ self.name = name
+ self.default = default
+ self.annotation = annotation
+
+
+class DeveloperExceptionConfig:
+ def __init__(
+ self,
+ *,
+ pretty_exceptions_enable: bool = True,
+ pretty_exceptions_show_locals: bool = True,
+ pretty_exceptions_short: bool = True,
+ ) -> None:
+ self.pretty_exceptions_enable = pretty_exceptions_enable
+ self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
+ self.pretty_exceptions_short = pretty_exceptions_short
+
+
+class TyperPath(click.Path):
+ # Overwrite Click's behaviour to be compatible with Typer's autocompletion system
+ def shell_complete(
+ self, ctx: click.Context, param: click.Parameter, incomplete: str
+ ) -> List[click.shell_completion.CompletionItem]:
+ """Return an empty list so that the autocompletion functionality
+ will work properly from the commandline.
+ """
+ return []
diff --git a/venv/lib/python3.10/site-packages/typer/params.py b/venv/lib/python3.10/site-packages/typer/params.py
new file mode 100644
index 0000000000000000000000000000000000000000..66c2b32d3e35e313454ed3dcbaac8ac9bf71d14d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/params.py
@@ -0,0 +1,479 @@
+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, overload
+
+import click
+
+from .models import ArgumentInfo, OptionInfo
+
+if TYPE_CHECKING: # pragma: no cover
+ import click.shell_completion
+
+
+# Overload for Option created with custom type 'parser'
+@overload
+def Option(
+ # Parameter
+ default: Optional[Any] = ...,
+ *param_decls: str,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ # Option
+ show_default: Union[bool, str] = True,
+ prompt: Union[bool, str] = False,
+ confirmation_prompt: bool = False,
+ prompt_required: bool = True,
+ hide_input: bool = False,
+ # TODO: remove is_flag and flag_value in a future release
+ is_flag: Optional[bool] = None,
+ flag_value: Optional[Any] = None,
+ count: bool = False,
+ allow_from_autoenv: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any: ...
+
+
+# Overload for Option created with custom type 'click_type'
+@overload
+def Option(
+ # Parameter
+ default: Optional[Any] = ...,
+ *param_decls: str,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ click_type: Optional[click.ParamType] = None,
+ # Option
+ show_default: Union[bool, str] = True,
+ prompt: Union[bool, str] = False,
+ confirmation_prompt: bool = False,
+ prompt_required: bool = True,
+ hide_input: bool = False,
+ # TODO: remove is_flag and flag_value in a future release
+ is_flag: Optional[bool] = None,
+ flag_value: Optional[Any] = None,
+ count: bool = False,
+ allow_from_autoenv: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any: ...
+
+
+def Option(
+ # Parameter
+ default: Optional[Any] = ...,
+ *param_decls: str,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ click_type: Optional[click.ParamType] = None,
+ # Option
+ show_default: Union[bool, str] = True,
+ prompt: Union[bool, str] = False,
+ confirmation_prompt: bool = False,
+ prompt_required: bool = True,
+ hide_input: bool = False,
+ # TODO: remove is_flag and flag_value in a future release
+ is_flag: Optional[bool] = None,
+ flag_value: Optional[Any] = None,
+ count: bool = False,
+ allow_from_autoenv: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any:
+ return OptionInfo(
+ # Parameter
+ default=default,
+ param_decls=param_decls,
+ callback=callback,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ shell_complete=shell_complete,
+ autocompletion=autocompletion,
+ default_factory=default_factory,
+ # Custom type
+ parser=parser,
+ click_type=click_type,
+ # Option
+ show_default=show_default,
+ prompt=prompt,
+ confirmation_prompt=confirmation_prompt,
+ prompt_required=prompt_required,
+ hide_input=hide_input,
+ is_flag=is_flag,
+ flag_value=flag_value,
+ count=count,
+ allow_from_autoenv=allow_from_autoenv,
+ help=help,
+ hidden=hidden,
+ show_choices=show_choices,
+ show_envvar=show_envvar,
+ # Choice
+ case_sensitive=case_sensitive,
+ # Numbers
+ min=min,
+ max=max,
+ clamp=clamp,
+ # DateTime
+ formats=formats,
+ # File
+ mode=mode,
+ encoding=encoding,
+ errors=errors,
+ lazy=lazy,
+ atomic=atomic,
+ # Path
+ exists=exists,
+ file_okay=file_okay,
+ dir_okay=dir_okay,
+ writable=writable,
+ readable=readable,
+ resolve_path=resolve_path,
+ allow_dash=allow_dash,
+ path_type=path_type,
+ # Rich settings
+ rich_help_panel=rich_help_panel,
+ )
+
+
+# Overload for Argument created with custom type 'parser'
+@overload
+def Argument(
+ # Parameter
+ default: Optional[Any] = ...,
+ *,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any: ...
+
+
+# Overload for Argument created with custom type 'click_type'
+@overload
+def Argument(
+ # Parameter
+ default: Optional[Any] = ...,
+ *,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ click_type: Optional[click.ParamType] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any: ...
+
+
+def Argument(
+ # Parameter
+ default: Optional[Any] = ...,
+ *,
+ callback: Optional[Callable[..., Any]] = None,
+ metavar: Optional[str] = None,
+ expose_value: bool = True,
+ is_eager: bool = False,
+ envvar: Optional[Union[str, List[str]]] = None,
+ # Note that shell_complete is not fully supported and will be removed in future versions
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
+ shell_complete: Optional[
+ Callable[
+ [click.Context, click.Parameter, str],
+ Union[List["click.shell_completion.CompletionItem"], List[str]],
+ ]
+ ] = None,
+ autocompletion: Optional[Callable[..., Any]] = None,
+ default_factory: Optional[Callable[[], Any]] = None,
+ # Custom type
+ parser: Optional[Callable[[str], Any]] = None,
+ click_type: Optional[click.ParamType] = None,
+ # TyperArgument
+ show_default: Union[bool, str] = True,
+ show_choices: bool = True,
+ show_envvar: bool = True,
+ help: Optional[str] = None,
+ hidden: bool = False,
+ # Choice
+ case_sensitive: bool = True,
+ # Numbers
+ min: Optional[Union[int, float]] = None,
+ max: Optional[Union[int, float]] = None,
+ clamp: bool = False,
+ # DateTime
+ formats: Optional[List[str]] = None,
+ # File
+ mode: Optional[str] = None,
+ encoding: Optional[str] = None,
+ errors: Optional[str] = "strict",
+ lazy: Optional[bool] = None,
+ atomic: bool = False,
+ # Path
+ exists: bool = False,
+ file_okay: bool = True,
+ dir_okay: bool = True,
+ writable: bool = False,
+ readable: bool = True,
+ resolve_path: bool = False,
+ allow_dash: bool = False,
+ path_type: Union[None, Type[str], Type[bytes]] = None,
+ # Rich settings
+ rich_help_panel: Union[str, None] = None,
+) -> Any:
+ return ArgumentInfo(
+ # Parameter
+ default=default,
+ # Arguments can only have one param declaration
+ # it will be generated from the param name
+ param_decls=None,
+ callback=callback,
+ metavar=metavar,
+ expose_value=expose_value,
+ is_eager=is_eager,
+ envvar=envvar,
+ shell_complete=shell_complete,
+ autocompletion=autocompletion,
+ default_factory=default_factory,
+ # Custom type
+ parser=parser,
+ click_type=click_type,
+ # TyperArgument
+ show_default=show_default,
+ show_choices=show_choices,
+ show_envvar=show_envvar,
+ help=help,
+ hidden=hidden,
+ # Choice
+ case_sensitive=case_sensitive,
+ # Numbers
+ min=min,
+ max=max,
+ clamp=clamp,
+ # DateTime
+ formats=formats,
+ # File
+ mode=mode,
+ encoding=encoding,
+ errors=errors,
+ lazy=lazy,
+ atomic=atomic,
+ # Path
+ exists=exists,
+ file_okay=file_okay,
+ dir_okay=dir_okay,
+ writable=writable,
+ readable=readable,
+ resolve_path=resolve_path,
+ allow_dash=allow_dash,
+ path_type=path_type,
+ # Rich settings
+ rich_help_panel=rich_help_panel,
+ )
diff --git a/venv/lib/python3.10/site-packages/typer/py.typed b/venv/lib/python3.10/site-packages/typer/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/typer/rich_utils.py b/venv/lib/python3.10/site-packages/typer/rich_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b6c5a840f2aa9b52c788ea998d906e196c4224a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/rich_utils.py
@@ -0,0 +1,741 @@
+# Extracted and modified from https://github.com/ewels/rich-click
+
+import inspect
+import io
+import sys
+from collections import defaultdict
+from gettext import gettext as _
+from os import getenv
+from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Union
+
+import click
+from rich import box
+from rich.align import Align
+from rich.columns import Columns
+from rich.console import Console, RenderableType, group
+from rich.emoji import Emoji
+from rich.highlighter import RegexHighlighter
+from rich.markdown import Markdown
+from rich.padding import Padding
+from rich.panel import Panel
+from rich.table import Table
+from rich.text import Text
+from rich.theme import Theme
+
+if sys.version_info >= (3, 9):
+ from typing import Literal
+else:
+ from typing_extensions import Literal
+
+# Default styles
+STYLE_OPTION = "bold cyan"
+STYLE_SWITCH = "bold green"
+STYLE_NEGATIVE_OPTION = "bold magenta"
+STYLE_NEGATIVE_SWITCH = "bold red"
+STYLE_METAVAR = "bold yellow"
+STYLE_METAVAR_SEPARATOR = "dim"
+STYLE_USAGE = "yellow"
+STYLE_USAGE_COMMAND = "bold"
+STYLE_DEPRECATED = "red"
+STYLE_DEPRECATED_COMMAND = "dim"
+STYLE_HELPTEXT_FIRST_LINE = ""
+STYLE_HELPTEXT = "dim"
+STYLE_OPTION_HELP = ""
+STYLE_OPTION_DEFAULT = "dim"
+STYLE_OPTION_ENVVAR = "dim yellow"
+STYLE_REQUIRED_SHORT = "red"
+STYLE_REQUIRED_LONG = "dim red"
+STYLE_OPTIONS_PANEL_BORDER = "dim"
+ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left"
+STYLE_OPTIONS_TABLE_SHOW_LINES = False
+STYLE_OPTIONS_TABLE_LEADING = 0
+STYLE_OPTIONS_TABLE_PAD_EDGE = False
+STYLE_OPTIONS_TABLE_PADDING = (0, 1)
+STYLE_OPTIONS_TABLE_BOX = ""
+STYLE_OPTIONS_TABLE_ROW_STYLES = None
+STYLE_OPTIONS_TABLE_BORDER_STYLE = None
+STYLE_COMMANDS_PANEL_BORDER = "dim"
+ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"
+STYLE_COMMANDS_TABLE_SHOW_LINES = False
+STYLE_COMMANDS_TABLE_LEADING = 0
+STYLE_COMMANDS_TABLE_PAD_EDGE = False
+STYLE_COMMANDS_TABLE_PADDING = (0, 1)
+STYLE_COMMANDS_TABLE_BOX = ""
+STYLE_COMMANDS_TABLE_ROW_STYLES = None
+STYLE_COMMANDS_TABLE_BORDER_STYLE = None
+STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan"
+STYLE_ERRORS_PANEL_BORDER = "red"
+ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left"
+STYLE_ERRORS_SUGGESTION = "dim"
+STYLE_ABORTED = "red"
+_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH")
+MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None
+COLOR_SYSTEM: Optional[Literal["auto", "standard", "256", "truecolor", "windows"]] = (
+ "auto" # Set to None to disable colors
+)
+_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL")
+FORCE_TERMINAL = (
+ True
+ if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS")
+ else None
+)
+if _TYPER_FORCE_DISABLE_TERMINAL:
+ FORCE_TERMINAL = False
+
+# Fixed strings
+DEPRECATED_STRING = _("(deprecated) ")
+DEFAULT_STRING = _("[default: {}]")
+ENVVAR_STRING = _("[env var: {}]")
+REQUIRED_SHORT_STRING = "*"
+REQUIRED_LONG_STRING = _("[required]")
+RANGE_STRING = " [{}]"
+ARGUMENTS_PANEL_TITLE = _("Arguments")
+OPTIONS_PANEL_TITLE = _("Options")
+COMMANDS_PANEL_TITLE = _("Commands")
+ERRORS_PANEL_TITLE = _("Error")
+ABORTED_TEXT = _("Aborted.")
+RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.")
+
+MARKUP_MODE_MARKDOWN = "markdown"
+MARKUP_MODE_RICH = "rich"
+_RICH_HELP_PANEL_NAME = "rich_help_panel"
+
+MarkupMode = Literal["markdown", "rich", None]
+
+
+# Rich regex highlighter
+class OptionHighlighter(RegexHighlighter):
+ """Highlights our special options."""
+
+ highlights = [
+ r"(^|\W)(?P\-\w+)(?![a-zA-Z0-9])",
+ r"(^|\W)(?P\-\-[\w\-]+)(?![a-zA-Z0-9])",
+ r"(?P\<[^\>]+\>)",
+ r"(?PUsage: )",
+ ]
+
+
+class NegativeOptionHighlighter(RegexHighlighter):
+ highlights = [
+ r"(^|\W)(?P\-\w+)(?![a-zA-Z0-9])",
+ r"(^|\W)(?P\-\-[\w\-]+)(?![a-zA-Z0-9])",
+ ]
+
+
+highlighter = OptionHighlighter()
+negative_highlighter = NegativeOptionHighlighter()
+
+
+def _get_rich_console(stderr: bool = False) -> Console:
+ return Console(
+ theme=Theme(
+ {
+ "option": STYLE_OPTION,
+ "switch": STYLE_SWITCH,
+ "negative_option": STYLE_NEGATIVE_OPTION,
+ "negative_switch": STYLE_NEGATIVE_SWITCH,
+ "metavar": STYLE_METAVAR,
+ "metavar_sep": STYLE_METAVAR_SEPARATOR,
+ "usage": STYLE_USAGE,
+ },
+ ),
+ highlighter=highlighter,
+ color_system=COLOR_SYSTEM,
+ force_terminal=FORCE_TERMINAL,
+ width=MAX_WIDTH,
+ stderr=stderr,
+ )
+
+
+def _make_rich_text(
+ *, text: str, style: str = "", markup_mode: MarkupMode
+) -> Union[Markdown, Text]:
+ """Take a string, remove indentations, and return styled text.
+
+ By default, the text is not parsed for any special formatting.
+ If `markup_mode` is `"rich"`, the text is parsed for Rich markup strings.
+ If `markup_mode` is `"markdown"`, parse as Markdown.
+ """
+ # Remove indentations from input text
+ text = inspect.cleandoc(text)
+ if markup_mode == MARKUP_MODE_MARKDOWN:
+ text = Emoji.replace(text)
+ return Markdown(text, style=style)
+ if markup_mode == MARKUP_MODE_RICH:
+ return highlighter(Text.from_markup(text, style=style))
+ else:
+ return highlighter(Text(text, style=style))
+
+
+@group()
+def _get_help_text(
+ *,
+ obj: Union[click.Command, click.Group],
+ markup_mode: MarkupMode,
+) -> Iterable[Union[Markdown, Text]]:
+ """Build primary help text for a click command or group.
+
+ Returns the prose help text for a command or group, rendered either as a
+ Rich Text object or as Markdown.
+ If the command is marked as deprecated, the deprecated string will be prepended.
+ """
+ # Prepend deprecated status
+ if obj.deprecated:
+ yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)
+
+ # Fetch and dedent the help text
+ help_text = inspect.cleandoc(obj.help or "")
+
+ # Trim off anything that comes after \f on its own line
+ help_text = help_text.partition("\f")[0]
+
+ # Get the first paragraph
+ first_line = help_text.split("\n\n")[0]
+ # Remove single linebreaks
+ if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"):
+ first_line = first_line.replace("\n", " ")
+ yield _make_rich_text(
+ text=first_line.strip(),
+ style=STYLE_HELPTEXT_FIRST_LINE,
+ markup_mode=markup_mode,
+ )
+
+ # Add a newline inbetween the header and the remaining paragraphs
+ yield Text("")
+
+ # Get remaining lines, remove single line breaks and format as dim
+ remaining_paragraphs = help_text.split("\n\n")[1:]
+ if remaining_paragraphs:
+ if markup_mode != MARKUP_MODE_RICH:
+ # Remove single linebreaks
+ remaining_paragraphs = [
+ x.replace("\n", " ").strip()
+ if not x.startswith("\b")
+ else "{}\n".format(x.strip("\b\n"))
+ for x in remaining_paragraphs
+ ]
+ # Join back together
+ remaining_lines = "\n".join(remaining_paragraphs)
+ else:
+ # Join with double linebreaks if markdown
+ remaining_lines = "\n\n".join(remaining_paragraphs)
+
+ yield _make_rich_text(
+ text=remaining_lines,
+ style=STYLE_HELPTEXT,
+ markup_mode=markup_mode,
+ )
+
+
+def _get_parameter_help(
+ *,
+ param: Union[click.Option, click.Argument, click.Parameter],
+ ctx: click.Context,
+ markup_mode: MarkupMode,
+) -> Columns:
+ """Build primary help text for a click option or argument.
+
+ Returns the prose help text for an option or argument, rendered either
+ as a Rich Text object or as Markdown.
+ Additional elements are appended to show the default and required status if
+ applicable.
+ """
+ # import here to avoid cyclic imports
+ from .core import TyperArgument, TyperOption
+
+ items: List[Union[Text, Markdown]] = []
+
+ # Get the environment variable first
+
+ envvar = getattr(param, "envvar", None)
+ var_str = ""
+ # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726
+ if envvar is None:
+ if (
+ getattr(param, "allow_from_autoenv", None)
+ and getattr(ctx, "auto_envvar_prefix", None) is not None
+ and param.name is not None
+ ):
+ envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}"
+ if envvar is not None:
+ var_str = (
+ envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar)
+ )
+
+ # Main help text
+ help_value: Union[str, None] = getattr(param, "help", None)
+ if help_value:
+ paragraphs = help_value.split("\n\n")
+ # Remove single linebreaks
+ if markup_mode != MARKUP_MODE_MARKDOWN:
+ paragraphs = [
+ x.replace("\n", " ").strip()
+ if not x.startswith("\b")
+ else "{}\n".format(x.strip("\b\n"))
+ for x in paragraphs
+ ]
+ items.append(
+ _make_rich_text(
+ text="\n".join(paragraphs).strip(),
+ style=STYLE_OPTION_HELP,
+ markup_mode=markup_mode,
+ )
+ )
+
+ # Environment variable AFTER help text
+ if envvar and getattr(param, "show_envvar", None):
+ items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR))
+
+ # Default value
+ # This uses Typer's specific param._get_default_string
+ if isinstance(param, (TyperOption, TyperArgument)):
+ if param.show_default:
+ show_default_is_str = isinstance(param.show_default, str)
+ default_value = param._extract_default_help_str(ctx=ctx)
+ default_str = param._get_default_string(
+ ctx=ctx,
+ show_default_is_str=show_default_is_str,
+ default_value=default_value,
+ )
+ if default_str:
+ items.append(
+ Text(
+ DEFAULT_STRING.format(default_str),
+ style=STYLE_OPTION_DEFAULT,
+ )
+ )
+
+ # Required?
+ if param.required:
+ items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))
+
+ # Use Columns - this allows us to group different renderable types
+ # (Text, Markdown) onto a single line.
+ return Columns(items)
+
+
+def _make_command_help(
+ *,
+ help_text: str,
+ markup_mode: MarkupMode,
+) -> Union[Text, Markdown]:
+ """Build cli help text for a click group command.
+
+ That is, when calling help on groups with multiple subcommands
+ (not the main help text when calling the subcommand help).
+
+ Returns the first paragraph of help text for a command, rendered either as a
+ Rich Text object or as Markdown.
+ Ignores single newlines as paragraph markers, looks for double only.
+ """
+ paragraphs = inspect.cleandoc(help_text).split("\n\n")
+ # Remove single linebreaks
+ if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"):
+ paragraphs[0] = paragraphs[0].replace("\n", " ")
+ elif paragraphs[0].startswith("\b"):
+ paragraphs[0] = paragraphs[0].replace("\b\n", "")
+ return _make_rich_text(
+ text=paragraphs[0].strip(),
+ style=STYLE_OPTION_HELP,
+ markup_mode=markup_mode,
+ )
+
+
+def _print_options_panel(
+ *,
+ name: str,
+ params: Union[List[click.Option], List[click.Argument]],
+ ctx: click.Context,
+ markup_mode: MarkupMode,
+ console: Console,
+) -> None:
+ options_rows: List[List[RenderableType]] = []
+ required_rows: List[Union[str, Text]] = []
+ for param in params:
+ # Short and long form
+ opt_long_strs = []
+ opt_short_strs = []
+ secondary_opt_long_strs = []
+ secondary_opt_short_strs = []
+ for opt_str in param.opts:
+ if "--" in opt_str:
+ opt_long_strs.append(opt_str)
+ else:
+ opt_short_strs.append(opt_str)
+ for opt_str in param.secondary_opts:
+ if "--" in opt_str:
+ secondary_opt_long_strs.append(opt_str)
+ else:
+ secondary_opt_short_strs.append(opt_str)
+
+ # Column for a metavar, if we have one
+ metavar = Text(style=STYLE_METAVAR, overflow="fold")
+ # TODO: when deprecating Click < 8.2, make ctx required
+ signature = inspect.signature(param.make_metavar)
+ if "ctx" in signature.parameters:
+ metavar_str = param.make_metavar(ctx=ctx)
+ else:
+ # Click < 8.2
+ metavar_str = param.make_metavar() # type: ignore[call-arg]
+
+ # Do it ourselves if this is a positional argument
+ if (
+ isinstance(param, click.Argument)
+ and param.name
+ and metavar_str == param.name.upper()
+ ):
+ metavar_str = param.type.name.upper()
+
+ # Skip booleans and choices (handled above)
+ if metavar_str != "BOOLEAN":
+ metavar.append(metavar_str)
+
+ # Range - from
+ # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501
+ # skip count with default range type
+ if (
+ isinstance(param.type, click.types._NumberRangeBase)
+ and isinstance(param, click.Option)
+ and not (param.count and param.type.min == 0 and param.type.max is None)
+ ):
+ range_str = param.type._describe_range()
+ if range_str:
+ metavar.append(RANGE_STRING.format(range_str))
+
+ # Required asterisk
+ required: Union[str, Text] = ""
+ if param.required:
+ required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)
+
+ # Highlighter to make [ | ] and <> dim
+ class MetavarHighlighter(RegexHighlighter):
+ highlights = [
+ r"^(?P(\[|<))",
+ r"(?P\|)",
+ r"(?P(\]|>)$)",
+ ]
+
+ metavar_highlighter = MetavarHighlighter()
+
+ required_rows.append(required)
+ options_rows.append(
+ [
+ highlighter(",".join(opt_long_strs)),
+ highlighter(",".join(opt_short_strs)),
+ negative_highlighter(",".join(secondary_opt_long_strs)),
+ negative_highlighter(",".join(secondary_opt_short_strs)),
+ metavar_highlighter(metavar),
+ _get_parameter_help(
+ param=param,
+ ctx=ctx,
+ markup_mode=markup_mode,
+ ),
+ ]
+ )
+ rows_with_required: List[List[RenderableType]] = []
+ if any(required_rows):
+ for required, row in zip(required_rows, options_rows):
+ rows_with_required.append([required, *row])
+ else:
+ rows_with_required = options_rows
+ if options_rows:
+ t_styles: Dict[str, Any] = {
+ "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,
+ "leading": STYLE_OPTIONS_TABLE_LEADING,
+ "box": STYLE_OPTIONS_TABLE_BOX,
+ "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,
+ "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,
+ "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,
+ "padding": STYLE_OPTIONS_TABLE_PADDING,
+ }
+ box_style = getattr(box, t_styles.pop("box"), None)
+
+ options_table = Table(
+ highlight=True,
+ show_header=False,
+ expand=True,
+ box=box_style,
+ **t_styles,
+ )
+ for row in rows_with_required:
+ options_table.add_row(*row)
+ console.print(
+ Panel(
+ options_table,
+ border_style=STYLE_OPTIONS_PANEL_BORDER,
+ title=name,
+ title_align=ALIGN_OPTIONS_PANEL,
+ )
+ )
+
+
+def _print_commands_panel(
+ *,
+ name: str,
+ commands: List[click.Command],
+ markup_mode: MarkupMode,
+ console: Console,
+ cmd_len: int,
+) -> None:
+ t_styles: Dict[str, Any] = {
+ "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,
+ "leading": STYLE_COMMANDS_TABLE_LEADING,
+ "box": STYLE_COMMANDS_TABLE_BOX,
+ "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,
+ "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,
+ "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,
+ "padding": STYLE_COMMANDS_TABLE_PADDING,
+ }
+ box_style = getattr(box, t_styles.pop("box"), None)
+
+ commands_table = Table(
+ highlight=False,
+ show_header=False,
+ expand=True,
+ box=box_style,
+ **t_styles,
+ )
+ # Define formatting in first column, as commands don't match highlighter
+ # regex
+ commands_table.add_column(
+ style=STYLE_COMMANDS_TABLE_FIRST_COLUMN,
+ no_wrap=True,
+ width=cmd_len,
+ )
+
+ # A big ratio makes the description column be greedy and take all the space
+ # available instead of allowing the command column to grow and misalign with
+ # other panels.
+ commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10)
+ rows: List[List[Union[RenderableType, None]]] = []
+ deprecated_rows: List[Union[RenderableType, None]] = []
+ for command in commands:
+ helptext = command.short_help or command.help or ""
+ command_name = command.name or ""
+ if command.deprecated:
+ command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND)
+ deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED))
+ else:
+ command_name_text = Text(command_name)
+ deprecated_rows.append(None)
+ rows.append(
+ [
+ command_name_text,
+ _make_command_help(
+ help_text=helptext,
+ markup_mode=markup_mode,
+ ),
+ ]
+ )
+ rows_with_deprecated = rows
+ if any(deprecated_rows):
+ rows_with_deprecated = []
+ for row, deprecated_text in zip(rows, deprecated_rows):
+ rows_with_deprecated.append([*row, deprecated_text])
+ for row in rows_with_deprecated:
+ commands_table.add_row(*row)
+ if commands_table.row_count:
+ console.print(
+ Panel(
+ commands_table,
+ border_style=STYLE_COMMANDS_PANEL_BORDER,
+ title=name,
+ title_align=ALIGN_COMMANDS_PANEL,
+ )
+ )
+
+
+def rich_format_help(
+ *,
+ obj: Union[click.Command, click.Group],
+ ctx: click.Context,
+ markup_mode: MarkupMode,
+) -> None:
+ """Print nicely formatted help text using rich.
+
+ Based on original code from rich-cli, by @willmcgugan.
+ https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
+
+ Replacement for the click function format_help().
+ Takes a command or group and builds the help text output.
+ """
+ console = _get_rich_console()
+
+ # Print usage
+ console.print(
+ Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND
+ )
+
+ # Print command / group help if we have some
+ if obj.help:
+ # Print with some padding
+ console.print(
+ Padding(
+ Align(
+ _get_help_text(
+ obj=obj,
+ markup_mode=markup_mode,
+ ),
+ pad=False,
+ ),
+ (0, 1, 1, 1),
+ )
+ )
+ panel_to_arguments: DefaultDict[str, List[click.Argument]] = defaultdict(list)
+ panel_to_options: DefaultDict[str, List[click.Option]] = defaultdict(list)
+ for param in obj.get_params(ctx):
+ # Skip if option is hidden
+ if getattr(param, "hidden", False):
+ continue
+ if isinstance(param, click.Argument):
+ panel_name = (
+ getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE
+ )
+ panel_to_arguments[panel_name].append(param)
+ elif isinstance(param, click.Option):
+ panel_name = (
+ getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE
+ )
+ panel_to_options[panel_name].append(param)
+ default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, [])
+ _print_options_panel(
+ name=ARGUMENTS_PANEL_TITLE,
+ params=default_arguments,
+ ctx=ctx,
+ markup_mode=markup_mode,
+ console=console,
+ )
+ for panel_name, arguments in panel_to_arguments.items():
+ if panel_name == ARGUMENTS_PANEL_TITLE:
+ # Already printed above
+ continue
+ _print_options_panel(
+ name=panel_name,
+ params=arguments,
+ ctx=ctx,
+ markup_mode=markup_mode,
+ console=console,
+ )
+ default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, [])
+ _print_options_panel(
+ name=OPTIONS_PANEL_TITLE,
+ params=default_options,
+ ctx=ctx,
+ markup_mode=markup_mode,
+ console=console,
+ )
+ for panel_name, options in panel_to_options.items():
+ if panel_name == OPTIONS_PANEL_TITLE:
+ # Already printed above
+ continue
+ _print_options_panel(
+ name=panel_name,
+ params=options,
+ ctx=ctx,
+ markup_mode=markup_mode,
+ console=console,
+ )
+
+ if isinstance(obj, click.Group):
+ panel_to_commands: DefaultDict[str, List[click.Command]] = defaultdict(list)
+ for command_name in obj.list_commands(ctx):
+ command = obj.get_command(ctx, command_name)
+ if command and not command.hidden:
+ panel_name = (
+ getattr(command, _RICH_HELP_PANEL_NAME, None)
+ or COMMANDS_PANEL_TITLE
+ )
+ panel_to_commands[panel_name].append(command)
+
+ # Identify the longest command name in all panels
+ max_cmd_len = max(
+ [
+ len(command.name or "")
+ for commands in panel_to_commands.values()
+ for command in commands
+ ],
+ default=0,
+ )
+
+ # Print each command group panel
+ default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, [])
+ _print_commands_panel(
+ name=COMMANDS_PANEL_TITLE,
+ commands=default_commands,
+ markup_mode=markup_mode,
+ console=console,
+ cmd_len=max_cmd_len,
+ )
+ for panel_name, commands in panel_to_commands.items():
+ if panel_name == COMMANDS_PANEL_TITLE:
+ # Already printed above
+ continue
+ _print_commands_panel(
+ name=panel_name,
+ commands=commands,
+ markup_mode=markup_mode,
+ console=console,
+ cmd_len=max_cmd_len,
+ )
+
+ # Epilogue if we have it
+ if obj.epilog:
+ # Remove single linebreaks, replace double with single
+ lines = obj.epilog.split("\n\n")
+ epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])
+ epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)
+ console.print(Padding(Align(epilogue_text, pad=False), 1))
+
+
+def rich_format_error(self: click.ClickException) -> None:
+ """Print richly formatted click errors.
+
+ Called by custom exception handler to print richly formatted click errors.
+ Mimics original click.ClickException.echo() function but with rich formatting.
+ """
+ console = _get_rich_console(stderr=True)
+ ctx: Union[click.Context, None] = getattr(self, "ctx", None)
+ if ctx is not None:
+ console.print(ctx.get_usage())
+
+ if ctx is not None and ctx.command.get_help_option(ctx) is not None:
+ console.print(
+ RICH_HELP.format(
+ command_path=ctx.command_path, help_option=ctx.help_option_names[0]
+ ),
+ style=STYLE_ERRORS_SUGGESTION,
+ )
+
+ console.print(
+ Panel(
+ highlighter(self.format_message()),
+ border_style=STYLE_ERRORS_PANEL_BORDER,
+ title=ERRORS_PANEL_TITLE,
+ title_align=ALIGN_ERRORS_PANEL,
+ )
+ )
+
+
+def rich_abort_error() -> None:
+ """Print richly formatted abort error."""
+ console = _get_rich_console(stderr=True)
+ console.print(ABORTED_TEXT, style=STYLE_ABORTED)
+
+
+def rich_to_html(input_text: str) -> str:
+ """Print the HTML version of a rich-formatted input string.
+
+ This function does not provide a full HTML page, but can be used to insert
+ HTML-formatted text spans into a markdown file.
+ """
+ console = Console(record=True, highlight=False, file=io.StringIO())
+
+ console.print(input_text, overflow="ignore", crop=False)
+
+ return console.export_html(inline_styles=True, code_format="{code}").strip()
+
+
+def rich_render_text(text: str) -> str:
+ """Remove rich tags and render a pure text representation"""
+ console = _get_rich_console()
+ return "".join(segment.text for segment in console.render(text)).rstrip("\n")
diff --git a/venv/lib/python3.10/site-packages/typer/testing.py b/venv/lib/python3.10/site-packages/typer/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..720cd81db6f47175609b527beff5bcf4bacd869c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/testing.py
@@ -0,0 +1,29 @@
+from typing import IO, Any, Mapping, Optional, Sequence, Union
+
+from click.testing import CliRunner as ClickCliRunner # noqa
+from click.testing import Result
+from typer.main import Typer
+from typer.main import get_command as _get_command
+
+
+class CliRunner(ClickCliRunner):
+ def invoke( # type: ignore
+ self,
+ app: Typer,
+ args: Optional[Union[str, Sequence[str]]] = None,
+ input: Optional[Union[bytes, str, IO[Any]]] = None,
+ env: Optional[Mapping[str, str]] = None,
+ catch_exceptions: bool = True,
+ color: bool = False,
+ **extra: Any,
+ ) -> Result:
+ use_cli = _get_command(app)
+ return super().invoke(
+ use_cli,
+ args=args,
+ input=input,
+ env=env,
+ catch_exceptions=catch_exceptions,
+ color=color,
+ **extra,
+ )
diff --git a/venv/lib/python3.10/site-packages/typer/utils.py b/venv/lib/python3.10/site-packages/typer/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..81dc4dd61deeb1d2782edc41e1502164ec72e52c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/typer/utils.py
@@ -0,0 +1,190 @@
+import inspect
+import sys
+from copy import copy
+from typing import Any, Callable, Dict, List, Tuple, Type, cast
+
+from ._typing import Annotated, get_args, get_origin, get_type_hints
+from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta
+
+
+def _param_type_to_user_string(param_type: Type[ParameterInfo]) -> str:
+ # Render a `ParameterInfo` subclass for use in error messages.
+ # User code doesn't call `*Info` directly, so errors should present the classes how
+ # they were (probably) defined in the user code.
+ if param_type is OptionInfo:
+ return "`Option`"
+ elif param_type is ArgumentInfo:
+ return "`Argument`"
+ # This line shouldn't be reachable during normal use.
+ return f"`{param_type.__name__}`" # pragma: no cover
+
+
+class AnnotatedParamWithDefaultValueError(Exception):
+ argument_name: str
+ param_type: Type[ParameterInfo]
+
+ def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):
+ self.argument_name = argument_name
+ self.param_type = param_type
+
+ def __str__(self) -> str:
+ param_type_str = _param_type_to_user_string(self.param_type)
+ return (
+ f"{param_type_str} default value cannot be set in `Annotated`"
+ f" for {self.argument_name!r}. Set the default value with `=` instead."
+ )
+
+
+class MixedAnnotatedAndDefaultStyleError(Exception):
+ argument_name: str
+ annotated_param_type: Type[ParameterInfo]
+ default_param_type: Type[ParameterInfo]
+
+ def __init__(
+ self,
+ argument_name: str,
+ annotated_param_type: Type[ParameterInfo],
+ default_param_type: Type[ParameterInfo],
+ ):
+ self.argument_name = argument_name
+ self.annotated_param_type = annotated_param_type
+ self.default_param_type = default_param_type
+
+ def __str__(self) -> str:
+ annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)
+ default_param_type_str = _param_type_to_user_string(self.default_param_type)
+ msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"
+ if self.annotated_param_type is self.default_param_type:
+ msg += " default value"
+ else:
+ msg += f" {default_param_type_str} as a default value"
+ msg += f" together for {self.argument_name!r}"
+ return msg
+
+
+class MultipleTyperAnnotationsError(Exception):
+ argument_name: str
+
+ def __init__(self, argument_name: str):
+ self.argument_name = argument_name
+
+ def __str__(self) -> str:
+ return (
+ "Cannot specify multiple `Annotated` Typer arguments"
+ f" for {self.argument_name!r}"
+ )
+
+
+class DefaultFactoryAndDefaultValueError(Exception):
+ argument_name: str
+ param_type: Type[ParameterInfo]
+
+ def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):
+ self.argument_name = argument_name
+ self.param_type = param_type
+
+ def __str__(self) -> str:
+ param_type_str = _param_type_to_user_string(self.param_type)
+ return (
+ "Cannot specify `default_factory` and a default value together"
+ f" for {param_type_str}"
+ )
+
+
+def _split_annotation_from_typer_annotations(
+ base_annotation: Type[Any],
+) -> Tuple[Type[Any], List[ParameterInfo]]:
+ if get_origin(base_annotation) is not Annotated:
+ return base_annotation, []
+ base_annotation, *maybe_typer_annotations = get_args(base_annotation)
+ return base_annotation, [
+ annotation
+ for annotation in maybe_typer_annotations
+ if isinstance(annotation, ParameterInfo)
+ ]
+
+
+def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:
+ if sys.version_info >= (3, 10):
+ signature = inspect.signature(func, eval_str=True)
+ else:
+ signature = inspect.signature(func)
+
+ type_hints = get_type_hints(func)
+ params = {}
+ for param in signature.parameters.values():
+ annotation, typer_annotations = _split_annotation_from_typer_annotations(
+ param.annotation,
+ )
+ if len(typer_annotations) > 1:
+ raise MultipleTyperAnnotationsError(param.name)
+
+ default = param.default
+ if typer_annotations:
+ # It's something like `my_param: Annotated[str, Argument()]`
+ [parameter_info] = typer_annotations
+
+ # Forbid `my_param: Annotated[str, Argument()] = Argument("...")`
+ if isinstance(param.default, ParameterInfo):
+ raise MixedAnnotatedAndDefaultStyleError(
+ argument_name=param.name,
+ annotated_param_type=type(parameter_info),
+ default_param_type=type(param.default),
+ )
+
+ parameter_info = copy(parameter_info)
+
+ # When used as a default, `Option` takes a default value and option names
+ # as positional arguments:
+ # `Option(some_value, "--some-argument", "-s")`
+ # When used in `Annotated` (ie, what this is handling), `Option` just takes
+ # option names as positional arguments:
+ # `Option("--some-argument", "-s")`
+ # In this case, the `default` attribute of `parameter_info` is actually
+ # meant to be the first item of `param_decls`.
+ if (
+ isinstance(parameter_info, OptionInfo)
+ and parameter_info.default is not ...
+ ):
+ parameter_info.param_decls = (
+ cast(str, parameter_info.default),
+ *(parameter_info.param_decls or ()),
+ )
+ parameter_info.default = ...
+
+ # Forbid `my_param: Annotated[str, Argument('some-default')]`
+ if parameter_info.default is not ...:
+ raise AnnotatedParamWithDefaultValueError(
+ param_type=type(parameter_info),
+ argument_name=param.name,
+ )
+ if param.default is not param.empty:
+ # Put the parameter's default (set by `=`) into `parameter_info`, where
+ # typer can find it.
+ parameter_info.default = param.default
+
+ default = parameter_info
+ elif param.name in type_hints:
+ # Resolve forward references.
+ annotation = type_hints[param.name]
+
+ if isinstance(default, ParameterInfo):
+ parameter_info = copy(default)
+ # Click supports `default` as either
+ # - an actual value; or
+ # - a factory function (returning a default value.)
+ # The two are not interchangeable for static typing, so typer allows
+ # specifying `default_factory`. Move the `default_factory` into `default`
+ # so click can find it.
+ if parameter_info.default is ... and parameter_info.default_factory:
+ parameter_info.default = parameter_info.default_factory
+ elif parameter_info.default_factory:
+ raise DefaultFactoryAndDefaultValueError(
+ argument_name=param.name, param_type=type(parameter_info)
+ )
+ default = parameter_info
+
+ params[param.name] = ParamMeta(
+ name=param.name, default=default, annotation=annotation
+ )
+ return params
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17dc11bd5a5b802fde95459b8b6219e540b4aba4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..945d270114493522b5f6a4667645b3d7f3aa9774
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/__main__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1779b2b7c90f6e9c3038741cf7c202594b1befd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/_iterutils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..564add2b56d13284d934ed79619fd09cd98b5bfd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/data_types.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61adc20c0e762b22cedb7c75864be263e3505df3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/env.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36ca80fe1bd3e5474175d4cbb0e47998a834f618
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/jupyter.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d8e0e79c27e7bbf9f8f1f5f84c0fa19f595d470
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/sklearn.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ebf841b34d756b18a79b1b62beb524dcc439269
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/trigger.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ac1cf38c4e3502448a75b438f5d074ca3661aeb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b889f516951fb58c308a73290548f67d4cb60be
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_agent.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..992c3eff2007d066038171b1d70c7b707239c41d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_controller.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a63dad604c6b8a80b1b2f7e0245d32bd837cc9ca
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/__pycache__/wandb_run.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5d3cb1ab88fd25a878f9ec18a544375c108068d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96d0910b2c501cb5173354d6b458ad5b0483fc66
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/base.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32852ca45724abe0dce30ffb1f3094c3bdaeb28f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/_pydantic/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/_pydantic/base.py b/venv/lib/python3.10/site-packages/wandb/_pydantic/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c80e1a92d208955af0d5566bc1461cdc0f041cc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/_pydantic/base.py
@@ -0,0 +1,128 @@
+"""Base classes and other customizations for generated pydantic types."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar
+
+from pydantic import BaseModel, ConfigDict, Field, Json, StrictStr
+from typing_extensions import Annotated, TypedDict, Unpack, override
+
+from .utils import IS_PYDANTIC_V2, to_json
+from .v1_compat import PydanticCompatMixin
+
+if TYPE_CHECKING:
+ from pydantic.main import IncEx
+
+
+class ModelDumpKwargs(TypedDict, total=False):
+ """Shared keyword arguments for `BaseModel.model_{dump,dump_json}`."""
+
+ include: IncEx | None
+ exclude: IncEx | None
+ context: dict[str, Any] | None
+ by_alias: bool | None
+ exclude_unset: bool
+ exclude_defaults: bool
+ exclude_none: bool
+ round_trip: bool
+ warnings: bool | Literal["none", "warn", "error"]
+ fallback: Callable[[Any], Any] | None
+ serialize_as_any: bool
+
+
+#: Custom overrides of default kwargs for `BaseModel.model_{dump,dump_json}`.
+MODEL_DUMP_DEFAULTS = ModelDumpKwargs(
+ by_alias=True, # Always serialize with aliases (e.g. camelCase names)
+ round_trip=True, # Ensure serialized values remain valid inputs for deserialization
+)
+
+
+# v1-compatible base class for pydantic types.
+class CompatBaseModel(PydanticCompatMixin, BaseModel):
+ __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring
+
+
+# Base class for all GraphQL-generated types.
+# Omitted from docstring to avoid inclusion in generated docs.
+class GQLBase(CompatBaseModel):
+ model_config = ConfigDict(
+ populate_by_name=True, # Discouraged in pydantic v2.11+, will be deprecated in v3
+ validate_by_name=True, # Introduced in pydantic v2.11
+ validate_by_alias=True, # Introduced in pydantic v2.11
+ serialize_by_alias=True, # Introduced in pydantic v2.11
+ validate_assignment=True,
+ validate_default=True,
+ use_attribute_docstrings=True,
+ from_attributes=True,
+ revalidate_instances="always",
+ protected_namespaces=(), # Some GraphQL fields may begin with "model_"
+ )
+
+ @override
+ def model_dump(
+ self,
+ *,
+ mode: Literal["json", "python"] | str = "json", # NOTE: changed default
+ **kwargs: Unpack[ModelDumpKwargs],
+ ) -> dict[str, Any]:
+ kwargs = {**MODEL_DUMP_DEFAULTS, **kwargs}
+ return super().model_dump(mode=mode, **kwargs)
+
+ @override
+ def model_dump_json(
+ self,
+ *,
+ indent: int | None = None,
+ **kwargs: Unpack[ModelDumpKwargs],
+ ) -> str:
+ kwargs = {**MODEL_DUMP_DEFAULTS, **kwargs}
+ return super().model_dump_json(indent=indent, **kwargs)
+
+
+# ------------------------------------------------------------------------------
+# Reusable annotations for field types
+T = TypeVar("T")
+
+if IS_PYDANTIC_V2 or TYPE_CHECKING:
+ GQLId = Annotated[
+ StrictStr,
+ Field(repr=False, frozen=True),
+ ]
+else:
+ # FIXME: Find a way to fix this for pydantic v1, which doesn't like when
+ # `Field(...)` used in the field assignment AND `Annotated[...]`.
+ # This is a problem for codegen, which can currently outputs e.g.
+ #
+ # class MyModel(GQLBase):
+ # my_id: GQLId = Field(alias="myID")
+ #
+ GQLId = StrictStr # type: ignore[misc]
+
+Typename = Annotated[
+ T,
+ Field(repr=False, frozen=True, alias="__typename"),
+]
+
+
+def ensure_json(v: Any) -> Any:
+ """In case the incoming value isn't serialized JSON, reserialize it.
+
+ This lets us use `Json[...]` fields with values that are already deserialized.
+ """
+ # NOTE: Assumes that the deserialized type is not itself a string.
+ # Revisit this if we need to support deserialized types that are str/bytes.
+ return v if isinstance(v, (str, bytes)) else to_json(v)
+
+
+if IS_PYDANTIC_V2 or TYPE_CHECKING:
+ from pydantic import BeforeValidator, PlainSerializer
+
+ SerializedToJson = Annotated[
+ Json[T],
+ # Allow lenient instantiation/validation: incoming data may already be deserialized.
+ BeforeValidator(ensure_json),
+ PlainSerializer(to_json),
+ ]
+else:
+ # FIXME: Restore, modify, or replace this later after ensuring pydantic v1 compatibility.
+ SerializedToJson = Json[T] # type: ignore[misc]
diff --git a/venv/lib/python3.10/site-packages/wandb/agents/__init__.py b/venv/lib/python3.10/site-packages/wandb/agents/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a311063898f21387545814a6bca22a5f7af9e34
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/pyagent.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/pyagent.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ca1c25712224a05b99c30c46a2f27c0cd07e3c7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/agents/__pycache__/pyagent.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/agents/pyagent.py b/venv/lib/python3.10/site-packages/wandb/agents/pyagent.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9483f6a0b20c2dd4703a3fa7df45fc5eeb6310d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/agents/pyagent.py
@@ -0,0 +1,386 @@
+"""Agent - Agent object.
+
+Manage wandb agent.
+
+"""
+
+import ctypes
+import logging
+import os
+import queue
+import socket
+import sys
+import threading
+import time
+import traceback
+
+import wandb
+from wandb.apis import InternalApi
+from wandb.sdk.launch.sweeps import utils as sweep_utils
+
+logger = logging.getLogger(__name__)
+
+
+def _terminate_thread(thread):
+ if not thread.is_alive():
+ return
+ if hasattr(thread, "_terminated"):
+ return
+ thread._terminated = True
+ tid = getattr(thread, "_thread_id", None)
+ if tid is None:
+ for k, v in threading._active.items():
+ if v is thread:
+ tid = k
+ if tid is None:
+ # This should never happen
+ return
+ logger.debug(f"Terminating thread: {tid}")
+ res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
+ ctypes.c_long(tid), ctypes.py_object(Exception)
+ )
+ if res == 0:
+ # This should never happen
+ return
+ elif res != 1:
+ # Revert
+ logger.debug(f"Termination failed for thread {tid}")
+ ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
+
+
+class Job:
+ def __init__(self, command):
+ self.command = command
+ job_type = command.get("type")
+ self.type = job_type
+ self.run_id = command.get("run_id")
+ self.config = command.get("args")
+
+ def __repr__(self):
+ if self.type == "run":
+ return f"Job({self.run_id},{self.config})"
+ elif self.type == "stop":
+ return f"stop({self.run_id})"
+ else:
+ return "exit"
+
+
+class RunStatus:
+ QUEUED = "QUEUED"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ ERRORED = "ERRORED"
+ DONE = "DONE"
+
+
+class Agent:
+ FLAPPING_MAX_SECONDS = 60
+ FLAPPING_MAX_FAILURES = 3
+ MAX_INITIAL_FAILURES = 5
+
+ def __init__(
+ self, sweep_id=None, project=None, entity=None, function=None, count=None
+ ):
+ self._sweep_path = sweep_id
+ self._sweep_id = None
+ self._project = project
+ self._entity = entity
+ self._function = function
+ self._count = count
+ # glob_config = os.path.expanduser('~/.config/wandb/settings')
+ # loc_config = 'wandb/settings'
+ # files = (glob_config, loc_config)
+ self._api = InternalApi()
+ self._agent_id = None
+ self._max_initial_failures = wandb.env.get_agent_max_initial_failures(
+ self.MAX_INITIAL_FAILURES
+ )
+ # if the directory to log to is not set, set it
+ if os.environ.get(wandb.env.DIR) is None:
+ os.environ[wandb.env.DIR] = os.path.abspath(os.getcwd())
+
+ def _init(self):
+ # These are not in constructor so that Agent instance can be rerun
+ self._run_threads = {}
+ self._run_status = {}
+ self._queue = queue.Queue()
+ self._exit_flag = False
+ self._exceptions = {}
+ self._start_time = time.time()
+
+ def _register(self):
+ logger.debug("Agent._register()")
+ agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id)
+ self._agent_id = agent["id"]
+ logger.debug(f"agent_id = {self._agent_id}")
+
+ def _setup(self):
+ logger.debug("Agent._setup()")
+ self._init()
+ parts = dict(entity=self._entity, project=self._project, name=self._sweep_path)
+ err = sweep_utils.parse_sweep_id(parts)
+ if err:
+ wandb.termerror(err)
+ return
+ entity = parts.get("entity") or self._entity
+ project = parts.get("project") or self._project
+ sweep_id = parts.get("name") or self._sweep_id
+ if sweep_id:
+ os.environ[wandb.env.SWEEP_ID] = sweep_id
+ if entity:
+ wandb.env.set_entity(entity)
+ if project:
+ wandb.env.set_project(project)
+ if sweep_id:
+ self._sweep_id = sweep_id
+ self._register()
+
+ def _stop_run(self, run_id):
+ logger.debug(f"Stopping run {run_id}.")
+ self._run_status[run_id] = RunStatus.STOPPED
+ thread = self._run_threads.get(run_id)
+ if thread:
+ _terminate_thread(thread)
+
+ def _stop_all_runs(self):
+ logger.debug("Stopping all runs.")
+ for run in list(self._run_threads.keys()):
+ self._stop_run(run)
+
+ def _exit(self):
+ self._stop_all_runs()
+ self._exit_flag = True
+ # _terminate_thread(self._main_thread)
+
+ def _heartbeat(self):
+ while True:
+ if self._exit_flag:
+ return
+ # if not self._main_thread.is_alive():
+ # return
+ run_status = {
+ run: True
+ for run, status in self._run_status.items()
+ if status in (RunStatus.QUEUED, RunStatus.RUNNING)
+ }
+ commands = self._api.agent_heartbeat(self._agent_id, {}, run_status)
+ if commands:
+ job = Job(commands[0])
+ logger.debug(f"Job received: {job}")
+ if job.type in ["run", "resume"]:
+ self._queue.put(job)
+ self._run_status[job.run_id] = RunStatus.QUEUED
+ elif job.type == "stop":
+ self._stop_run(job.run_id)
+ elif job.type == "exit":
+ self._exit()
+ return
+ time.sleep(5)
+
+ def _run_jobs_from_queue(self):
+ global _INSTANCES
+ _INSTANCES += 1
+ try:
+ waiting = False
+ count = 0
+ while True:
+ if self._exit_flag:
+ return
+ try:
+ try:
+ job = self._queue.get(timeout=5)
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Exiting.")
+ return
+ except queue.Empty:
+ if not waiting:
+ logger.debug("Paused.")
+ wandb.termlog("Sweep Agent: Waiting for job.")
+ waiting = True
+ time.sleep(5)
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Exiting.")
+ return
+ continue
+ if waiting:
+ logger.debug("Resumed.")
+ wandb.termlog("Job received.")
+ waiting = False
+ count += 1
+ run_id = job.run_id
+ if self._run_status[run_id] == RunStatus.STOPPED:
+ continue
+ logger.debug(f"Spawning new thread for run {run_id}.")
+ thread = threading.Thread(target=self._run_job, args=(job,))
+ self._run_threads[run_id] = thread
+ thread.start()
+ self._run_status[run_id] = RunStatus.RUNNING
+ thread.join()
+ logger.debug(f"Thread joined for run {run_id}.")
+ if self._run_status[run_id] == RunStatus.RUNNING:
+ self._run_status[run_id] = RunStatus.DONE
+ elif self._run_status[run_id] == RunStatus.ERRORED:
+ exc = self._exceptions[run_id]
+ # Extract to reduce a decision point to avoid ruff c901
+ log_str, term_str = _get_exception_logger_and_term_strs(exc)
+ logger.error(f"Run {run_id} errored:\n{log_str}")
+ wandb.termerror(f"Run {run_id} errored:{term_str}")
+ if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true":
+ self._exit_flag = True
+ return
+ elif (
+ time.time() - self._start_time < self.FLAPPING_MAX_SECONDS
+ ) and (len(self._exceptions) >= self.FLAPPING_MAX_FAILURES):
+ msg = f"Detected {self.FLAPPING_MAX_FAILURES} failed runs in the first {self.FLAPPING_MAX_SECONDS} seconds, killing sweep."
+ logger.error(msg)
+ wandb.termerror(msg)
+ wandb.termlog(
+ "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true"
+ )
+ self._exit_flag = True
+ return
+ if (
+ self._max_initial_failures < len(self._exceptions)
+ and len(self._exceptions) >= count
+ ):
+ msg = f"Detected {self._max_initial_failures} failed runs in a row at start, killing sweep."
+ logger.error(msg)
+ wandb.termerror(msg)
+ wandb.termlog(
+ "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val"
+ )
+ self._exit_flag = True
+ return
+ if self._count and self._count == count:
+ logger.debug("Exiting main loop because max count reached.")
+ self._exit_flag = True
+ return
+ except KeyboardInterrupt:
+ logger.debug("Ctrl + C detected. Stopping sweep.")
+ wandb.termlog("Ctrl + C detected. Stopping sweep.")
+ self._exit()
+ return
+ except Exception:
+ if self._exit_flag:
+ logger.debug("Exiting main loop due to exit flag.")
+ wandb.termlog("Sweep Agent: Killed.")
+ return
+ else:
+ raise
+ finally:
+ _INSTANCES -= 1
+
+ def _run_job(self, job):
+ try:
+ run_id = job.run_id
+
+ config_file = os.path.join(
+ "wandb", "sweep-" + self._sweep_id, "config-" + run_id + ".yaml"
+ )
+ os.environ[wandb.env.RUN_ID] = run_id
+ base_dir = os.environ.get(wandb.env.DIR, "")
+ sweep_param_path = os.path.join(base_dir, config_file)
+ os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path
+ wandb.wandb_lib.config_util.save_config_file_from_dict(
+ sweep_param_path, job.config
+ )
+ os.environ[wandb.env.SWEEP_ID] = self._sweep_id
+ wandb.teardown()
+
+ wandb.termlog(f"Agent Starting Run: {run_id} with config:")
+ for k, v in job.config.items():
+ wandb.termlog("\t{}: {}".format(k, v["value"]))
+
+ try:
+ self._function()
+ except KeyboardInterrupt:
+ raise
+ except Exception as e:
+ # Log the run's exceptions directly to stderr to match CLI case, and wrap so we
+ # can identify it as coming from the job later later. This will get automatically
+ # logged by console_capture.py. Exception handler below will also handle exceptions
+ # in setup code.
+ exc_repr = _format_exception_traceback(e)
+ print(exc_repr, file=sys.stderr) # noqa: T201
+ raise _JobError(f"Run threw exception: {str(e)}") from e
+ wandb.finish()
+ except KeyboardInterrupt:
+ raise
+ except Exception as e:
+ wandb.finish(exit_code=1)
+ if self._run_status[run_id] == RunStatus.RUNNING:
+ self._run_status[run_id] = RunStatus.ERRORED
+ self._exceptions[run_id] = e
+ finally:
+ # clean up the environment changes made
+ os.environ.pop(wandb.env.RUN_ID, None)
+ os.environ.pop(wandb.env.SWEEP_ID, None)
+ os.environ.pop(wandb.env.SWEEP_PARAM_PATH, None)
+
+ def run(self):
+ logger.info(
+ f"Starting sweep agent: entity={self._entity}, project={self._project}, count={self._count}"
+ )
+ self._setup()
+ # self._main_thread = threading.Thread(target=self._run_jobs_from_queue)
+ self._heartbeat_thread = threading.Thread(target=self._heartbeat)
+ self._heartbeat_thread.daemon = True
+ # self._main_thread.start()
+ self._heartbeat_thread.start()
+ # self._main_thread.join()
+ self._run_jobs_from_queue()
+
+
+def pyagent(sweep_id, function, entity=None, project=None, count=None):
+ """Generic agent entrypoint, used for CLI or jupyter.
+
+ Args:
+ sweep_id (dict): Sweep ID generated by CLI or sweep API
+ function (func, optional): A function to call instead of the "program"
+ entity (str, optional): W&B Entity
+ project (str, optional): W&B Project
+ count (int, optional): the number of trials to run.
+ """
+ if not callable(function):
+ raise TypeError("function parameter must be callable!")
+ agent = Agent(
+ sweep_id,
+ function=function,
+ entity=entity,
+ project=project,
+ count=count,
+ )
+ agent.run()
+
+
+def _format_exception_traceback(exc):
+ return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
+
+
+class _JobError(Exception):
+ """Exception raised when a job fails during execution."""
+
+ pass
+
+
+def _get_exception_logger_and_term_strs(exc):
+ if isinstance(exc, _JobError) and exc.__cause__:
+ # If it's a JobException, get the original exception for display
+ job_exc = exc.__cause__
+ log_str = _format_exception_traceback(job_exc)
+ # Don't long full stacktrace to terminal again because we already
+ # printed it to stderr.
+ term_str = " " + str(job_exc)
+ else:
+ log_str = _format_exception_traceback(exc)
+ term_str = "\n" + log_str
+ return log_str, term_str
+
+
+_INSTANCES = 0
+
+
+def is_running():
+ return bool(_INSTANCES)
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..322db51b9221dd19be7e41a8666d6213be6431fc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/input_types.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/input_types.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..641151367d2d4b6e4cae52d325efc80426f218cd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/input_types.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/integrations_by_entity.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/integrations_by_entity.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ff1cb3a1367bfe84f08a69bb5890c791e6c2ce1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/integrations_by_entity.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c24fc4f8db154d84a225557ba6f12ac6aec57f48
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1857ddd249886c74b727c108159bb5c08ae7a4f6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7298b302d28df37a7dded572122ceb8c4b81c39
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/beta/__pycache__/workflows.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/beta/__pycache__/workflows.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80c3ab24b84d076cbaeccd08662e30ce832d7d5a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/beta/__pycache__/workflows.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/beta/workflows.py b/venv/lib/python3.10/site-packages/wandb/beta/workflows.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e3b98cc70fbb27da48a72b1a7c7a9797fabe027
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/beta/workflows.py
@@ -0,0 +1,324 @@
+from __future__ import annotations
+
+import json
+import os
+import warnings
+from typing import Any
+
+from typing_extensions import deprecated
+
+import wandb
+from wandb.data_types import WBValue, _SavedModel
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk import wandb_setup
+from wandb.sdk.artifacts.artifact import Artifact
+from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry
+from wandb.sdk.lib.deprecate import deprecate as wandb_deprecate
+
+warnings.warn(
+ message=f"The {__name__!r} module is deprecated and will be removed in a future version. Please use the equivalent 'wandb.Run' methods instead.",
+ category=DeprecationWarning,
+ stacklevel=2,
+)
+
+
+def _add_any(
+ artifact: Artifact,
+ path_or_obj: str | ArtifactManifestEntry | WBValue, # todo: add dataframe
+ name: str | None,
+) -> Any:
+ """Add an object to an artifact.
+
+ High-level wrapper to add object(s) to an artifact - calls any of the .add* methods
+ under Artifact depending on the type of object that's passed in. This will probably
+ be moved to the Artifact class in the future.
+
+ Args:
+ artifact: artifact created with `wandb.Artifact(...)`
+ path_or_obj: either a str or valid object which indicates what to add
+ to an artifact.
+ name: the name of the object which is added to an artifact.
+
+ Returns:
+ Type[Any] - Union[None, ArtifactManifestEntry, etc]
+
+ """
+ if isinstance(path_or_obj, ArtifactManifestEntry):
+ return artifact.add_reference(path_or_obj, name)
+ elif isinstance(path_or_obj, WBValue):
+ return artifact.add(path_or_obj, name)
+ elif isinstance(path_or_obj, str):
+ if os.path.isdir(path_or_obj):
+ return artifact.add_dir(path_or_obj)
+ elif os.path.isfile(path_or_obj):
+ return artifact.add_file(path_or_obj)
+ else:
+ with artifact.new_file(name) as f:
+ f.write(json.dumps(path_or_obj, sort_keys=True))
+ else:
+ raise TypeError(
+ "Expected `path_or_obj` to be instance of `ArtifactManifestEntry`,"
+ f" `WBValue`, or `str, found {type(path_or_obj)}"
+ )
+
+
+def _log_artifact_version(
+ name: str,
+ type: str,
+ entries: dict[str, str | ArtifactManifestEntry | WBValue],
+ aliases: str | list[str] | None = None,
+ description: str | None = None,
+ metadata: dict | None = None,
+ project: str | None = None,
+ scope_project: bool | None = None,
+ job_type: str = "auto",
+) -> Artifact:
+ """Create an artifact, populate it, and log it with a run.
+
+ If a run is not present, we create one.
+
+ Args:
+ name: `str` - name of the artifact. If not scoped to a project, name will be
+ suffixed by "-{run_id}".
+ type: `str` - type of the artifact, used in the UI to group artifacts of the
+ same type.
+ entries: `Dict` - dictionary containing the named objects we want added to this
+ artifact.
+ description: `str` - text description of artifact.
+ metadata: `Dict` - users can pass in artifact-specific metadata here, will be
+ visible in the UI.
+ project: `str` - project under which to place this artifact.
+ scope_project: `bool` - if True, we will not suffix `name` with "-{run_id}".
+ job_type: `str` - Only applied if run is not present and we create one.
+ Used to identify runs of a certain job type, i.e "evaluation".
+
+ Returns:
+ Artifact
+
+ """
+ run = wandb_setup.singleton().most_recent_active_run
+ if not run:
+ run = wandb.init(
+ project=project,
+ job_type=job_type,
+ settings=wandb.Settings(silent=True),
+ )
+
+ if not scope_project:
+ name = f"{name}-{run.id}"
+
+ if metadata is None:
+ metadata = {}
+
+ art = wandb.Artifact(name, type, description, metadata, False, None)
+
+ for path in entries:
+ _add_any(art, entries[path], path)
+
+ # "latest" should always be present as an alias
+ aliases = wandb.util._resolve_aliases(aliases)
+ run.log_artifact(art, aliases=aliases)
+
+ return art
+
+
+_LOG_MODEL_DEPRECATION_MSG = "`log_model` is deprecated and will be removed in a future version. Please use `Run.log_artifact` instead."
+
+
+@deprecated(_LOG_MODEL_DEPRECATION_MSG)
+def log_model(
+ model_obj: Any,
+ name: str = "model",
+ aliases: str | list[str] | None = None,
+ description: str | None = None,
+ metadata: dict | None = None,
+ project: str | None = None,
+ scope_project: bool | None = None,
+ **kwargs: dict[str, Any],
+) -> _SavedModel:
+ """Log a model object to enable model-centric workflows in the UI.
+
+ Supported frameworks include PyTorch, Keras, Tensorflow, Scikit-learn, etc. Under
+ the hood, we create a model artifact, bind it to the run that produced this model,
+ associate it with the latest metrics logged with `run.log(...)` and more.
+
+ Args:
+ model_obj: any model object created with the following ML frameworks: PyTorch,
+ Keras, Tensorflow, Scikit-learn. name: `str` - name of the model artifact
+ that will be created to house this model_obj.
+ aliases: `str, List[str]` - optional alias(es) that will be applied on this
+ model and allow for unique identification. The alias "latest" will always be
+ applied to the latest version of a model.
+ description: `str` - text description/notes about the model - will be visible in
+ the Model Card UI.
+ metadata: `Dict` - model-specific metadata goes here - will be visible the UI.
+ project: `str` - project under which to place this artifact.
+ scope_project: `bool` - If true, name of this model artifact will not be
+ suffixed by `-{run_id}`.
+
+ Returns:
+ _SavedModel instance
+
+ Example:
+ ```python
+ import torch.nn as nn
+ import torch.nn.functional as F
+
+
+ class Net(nn.Module):
+ def __init__(self):
+ super(Net, self).__init__()
+ self.fc1 = nn.Linear(10, 10)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = F.relu(x)
+ return x
+
+
+ model = Net()
+ sm = log_model(model, "my-simple-model", aliases=["best"])
+ ```
+
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__log_model,
+ warning_message=_LOG_MODEL_DEPRECATION_MSG,
+ )
+
+ model = _SavedModel.init(model_obj, **kwargs)
+ _ = _log_artifact_version(
+ name=name,
+ type="model",
+ entries={
+ "index": model,
+ },
+ aliases=aliases,
+ description=description,
+ metadata=metadata,
+ project=project,
+ scope_project=scope_project,
+ job_type="log_model",
+ )
+ # TODO: handle offline mode appropriately.
+ return model
+
+
+_USE_MODEL_DEPRECATION_MSG = "`use_model` is deprecated and will be removed in a future version. Please update your code to use `Run.use_artifact` instead."
+
+
+@deprecated(_USE_MODEL_DEPRECATION_MSG)
+def use_model(aliased_path: str, unsafe: bool = False) -> _SavedModel:
+ """Fetch a saved model from an alias.
+
+ Under the hood, we use the alias to fetch the model artifact containing the
+ serialized model files and rebuild the model object from these files. We also
+ declare the fetched model artifact as an input to the run (with `run.use_artifact`).
+
+ Args:
+ aliased_path: `str` - the following forms are valid: "name:version",
+ "name:alias". May be prefixed with "entity/project".
+ unsafe: `bool` - must be True to indicate the user understands the risks
+ associated with loading external models.
+
+ Returns:
+ _SavedModel instance
+
+ Example:
+ ```python
+ # Assuming the model with the name "my-simple-model" is trusted:
+ sm = use_model("my-simple-model:latest", unsafe=True)
+ model = sm.model_obj()
+ ```
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__use_model,
+ warning_message=_USE_MODEL_DEPRECATION_MSG,
+ )
+
+ if not unsafe:
+ raise ValueError("The 'unsafe' parameter must be set to True to load a model.")
+
+ if ":" not in aliased_path:
+ raise ValueError(
+ "aliased_path must be of the form 'name:alias' or 'name:version'."
+ )
+
+ # Returns a _SavedModel instance
+ if run := wandb_setup.singleton().most_recent_active_run:
+ artifact = run.use_artifact(aliased_path)
+ sm = artifact.get("index")
+
+ if sm is None or not isinstance(sm, _SavedModel):
+ raise ValueError(
+ "Deserialization into model object failed: _SavedModel instance could not be initialized properly."
+ )
+
+ return sm
+ else:
+ raise ValueError(
+ "use_model can only be called inside a run. Please call wandb.init() before use_model(...)"
+ )
+
+
+_LINK_MODEL_DEPRECATION_MSG = "`link_model` is deprecated and will be removed in a future version. Please use `Run.link_artifact` instead."
+
+
+@deprecated(_LINK_MODEL_DEPRECATION_MSG)
+def link_model(
+ model: _SavedModel,
+ target_path: str,
+ aliases: str | list[str] | None = None,
+) -> None:
+ """Link the given model to a portfolio.
+
+ A portfolio is a promoted collection which contains (in this case) model artifacts.
+ Linking to a portfolio allows for useful model-centric workflows in the UI.
+
+ Args:
+ model: `_SavedModel` - an instance of _SavedModel, most likely from the output
+ of `log_model` or `use_model`.
+ target_path: `str` - the target portfolio. The following forms are valid for the
+ string: {portfolio}, {project/portfolio},{entity}/{project}/{portfolio}.
+ aliases: `str, List[str]` - optional alias(es) that will only be applied on this
+ linked model inside the portfolio. The alias "latest" will always be applied
+ to the latest version of a model.
+
+ Returns:
+ None
+
+ Example:
+ sm = use_model("my-simple-model:latest")
+ link_model(sm, "my-portfolio")
+
+ """
+ wandb_deprecate(
+ field_name=Deprecated.beta__workflows__link_model,
+ warning_message=_LINK_MODEL_DEPRECATION_MSG,
+ )
+
+ aliases = wandb.util._resolve_aliases(aliases)
+
+ if run := wandb_setup.singleton().most_recent_active_run:
+ # _artifact_source, if it exists, points to a Public Artifact.
+ # Its existence means that _SavedModel was deserialized from a logged artifact, most likely from `use_model`.
+ if model._artifact_source:
+ artifact = model._artifact_source.artifact
+ # If the _SavedModel has been added to a Local Artifact (most likely through `.add(WBValue)`), then
+ # model._artifact_target will point to that Local Artifact.
+ elif model._artifact_target and model._artifact_target.artifact._final:
+ artifact = model._artifact_target.artifact
+ else:
+ raise ValueError(
+ "Linking requires that the given _SavedModel belongs to an artifact"
+ )
+
+ run.link_artifact(artifact, target_path, aliases)
+
+ else:
+ if model._artifact_source is not None:
+ model._artifact_source.artifact.link(target_path, aliases)
+ else:
+ raise ValueError(
+ "Linking requires that the given _SavedModel belongs to a logged artifact."
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__init__.py b/venv/lib/python3.10/site-packages/wandb/errors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa45ad8aced101f4bec07df6f1d8972dabffd34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/__init__.py
@@ -0,0 +1,17 @@
+__all__ = (
+ "Error",
+ "CommError",
+ "AuthenticationError",
+ "UsageError",
+ "UnsupportedError",
+ "WandbCoreNotAvailableError",
+)
+
+from .errors import (
+ AuthenticationError,
+ CommError,
+ Error,
+ UnsupportedError,
+ UsageError,
+ WandbCoreNotAvailableError,
+)
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..615a0390f176c78b19666e4a15c832591636f8de
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61e9fea3bd0af0c16eb5cbdd3d7e0b4eecd1c437
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/errors.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6641ade2d89e388960b8744a61eb496426664a57
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/links.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5d59457e555b49952d5d166e85b22029b3c0b67
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/term.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38d92144d6f473fc3f6665b80e96c25da6fefbf1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/util.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e816f0abdede0842aeadfb7281f2441dc345ddc3
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/errors/__pycache__/warnings.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/errors.py b/venv/lib/python3.10/site-packages/wandb/errors/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..db543e492eeddc5b1237e4980f5caf3452d0bc76
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/errors.py
@@ -0,0 +1,40 @@
+from typing import Optional
+
+
+class Error(Exception):
+ """Base W&B Error.
+
+
+ """
+
+ def __init__(self, message, context: Optional[dict] = None) -> None:
+ super().__init__(message)
+ self.message = message
+ # sentry context capture
+ if context:
+ self.context = context
+
+
+class CommError(Error):
+ """Error communicating with W&B servers."""
+
+ def __init__(self, msg, exc=None) -> None:
+ self.exc = exc
+ self.message = msg
+ super().__init__(self.message)
+
+
+class AuthenticationError(CommError):
+ """Raised when authentication fails."""
+
+
+class UsageError(Error):
+ """Raised when an invalid usage of the SDK API is detected."""
+
+
+class UnsupportedError(UsageError):
+ """Raised when trying to use a feature that is not supported."""
+
+
+class WandbCoreNotAvailableError(Error):
+ """Raised when wandb core is not available."""
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/links.py b/venv/lib/python3.10/site-packages/wandb/errors/links.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff87cde68e779ab1d857a347dfbf6bb6445e74e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/links.py
@@ -0,0 +1,73 @@
+"""Module containing the WBURLs class and WBURL dataclass.
+
+Used to store predefined URLs that can be associated with a name. The URLs are
+shortened using with the `wandb.me` domain, using dub.co as the shortening service.
+If the URLs need to be updates, use the dub.co service to point to the new URL.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+@dataclass
+class WBURL:
+ url: str
+ description: str
+
+
+class Registry:
+ """A collection of URLs that can be associated with a name."""
+
+ def __init__(self) -> None:
+ self.urls: dict[str, WBURL] = {
+ "wandb-launch": WBURL(
+ "https://wandb.me/launch",
+ "Link to the W&B launch marketing page",
+ ),
+ "wandb-init": WBURL(
+ "https://wandb.me/wandb-init",
+ "Link to the wandb.init reference documentation page",
+ ),
+ "define-metric": WBURL(
+ "https://wandb.me/define-metric",
+ "Link to the W&B developer guide documentation page on wandb.define_metric",
+ ),
+ "developer-guide": WBURL(
+ "https://wandb.me/developer-guide",
+ "Link to the W&B developer guide top level page",
+ ),
+ "wandb-core": WBURL(
+ "https://wandb.me/wandb-core",
+ "Link to the documentation for the wandb-core service",
+ ),
+ "wandb-server": WBURL(
+ "https://wandb.me/wandb-server",
+ "Link to the documentation for the self-hosted W&B server",
+ ),
+ "multiprocess": WBURL(
+ "https://wandb.me/multiprocess",
+ (
+ "Link to the W&B developer guide documentation page on how to "
+ "use wandb in a multiprocess environment"
+ ),
+ ),
+ }
+
+ def url(self, name: str) -> str:
+ """Get the URL associated with the given name."""
+ wb_url = self.urls.get(name)
+ if wb_url:
+ return wb_url.url
+ raise ValueError(f"URL not found for {name}")
+
+ def description(self, name: str) -> str:
+ """Get the description associated with the given name."""
+ wb_url = self.urls.get(name)
+ if wb_url:
+ return wb_url.description
+ raise ValueError(f"Description not found for {name}")
+
+
+# This is an instance of the Links class that can be used to access the URLs
+url_registry = Registry()
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/term.py b/venv/lib/python3.10/site-packages/wandb/errors/term.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ddeced609bb33cfd9486d0b0ac409865c9a243
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/term.py
@@ -0,0 +1,415 @@
+"""Global functions for printing to stderr for wandb."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import re
+import shutil
+import sys
+import threading
+from typing import TYPE_CHECKING, Iterator, Protocol
+
+import click
+
+if TYPE_CHECKING:
+ import wandb
+
+LOG_STRING = click.style("wandb", fg="blue", bold=True)
+LOG_STRING_NOCOLOR = "wandb"
+ERROR_STRING = click.style("ERROR", bg="red", fg="green")
+WARN_STRING = click.style("WARNING", fg="yellow")
+
+_silent: bool = False
+"""If true, _logger is used instead of printing to stderr."""
+
+_logger: SupportsLeveledLogging | None = None
+"""A fallback logger for _silent mode."""
+
+_show_info: bool = True
+"""If false, then termlog() uses silent mode (see _silent)."""
+
+_show_warnings: bool = True
+"""If false, then termwarn() uses silent mode (see _silent)."""
+
+_show_errors: bool = True
+"""If false, then termerror() uses silent mode (see _silent)."""
+
+
+_printed_messages: set[str] = set()
+"""Messages logged with repeat=False."""
+
+_dynamic_text_lock = threading.Lock()
+"""Lock held for dynamic text operations.
+
+All uses of `_dynamic_blocks` and calls to functions that start with
+the `_l_` prefix must be guarded by this lock.
+"""
+
+_dynamic_blocks: list[DynamicBlock] = []
+"""Active dynamic text areas, created with dynamic_text()."""
+
+
+class SupportsLeveledLogging(Protocol):
+ """Portion of the standard logging.Logger used in this module."""
+
+ def info(self, msg: str) -> None: ...
+ def warning(self, msg: str) -> None: ...
+ def error(self, msg: str) -> None: ...
+
+
+def termsetup(
+ settings: wandb.Settings,
+ logger: SupportsLeveledLogging | None,
+) -> None:
+ """Configure the global logging functions.
+
+ Args:
+ settings: The settings object passed to wandb.setup() or wandb.init().
+ logger: A fallback logger to use for "silent" mode. In this mode,
+ the logger is used instead of printing to stderr.
+ """
+ global _silent, _show_info, _show_warnings, _show_errors, _logger
+ _silent = settings.silent
+ _show_info = settings.show_info
+ _show_warnings = settings.show_warnings
+ _show_errors = settings.show_errors
+ _logger = logger
+
+
+@contextlib.contextmanager
+def dynamic_text() -> Iterator[DynamicBlock | None]:
+ """A context manager that provides a handle to a new dynamic text area.
+
+ The text goes to stderr. Returns None if dynamic text is not supported.
+
+ Dynamic text must only be used while `wandb` has control of the terminal,
+ or else text written by other programs will be overwritten. It's
+ appropriate to use during a blocking operation.
+
+ ```
+ with term.dynamic_text() as text_area:
+ if text_area:
+ text_area.set_text("Writing to a terminal.")
+ for i in range(2000):
+ text_area.set_text(f"Still going... ({i}/2000)")
+ time.sleep(0.001)
+ else:
+ wandb.termlog("Writing to a file or dumb terminal.")
+ time.sleep(1)
+ wandb.termlog("Finished 1000/2000 tasks, still working...")
+ time.sleep(1)
+ wandb.termlog("Done!", err=True)
+ ```
+ """
+ # For now, dynamic text always corresponds to the "INFO" level.
+ if _silent or not _show_info:
+ yield None
+ return
+
+ # NOTE: In Jupyter notebooks, this will return False. Notebooks
+ # support ANSI color sequences and the '\r' character, but not
+ # cursor motions or line clear commands.
+ if not _sys_stderr_isatty():
+ yield None
+ return
+
+ # This is a convention to indicate that the terminal doesn't support
+ # clearing the screen / positioning the cursor.
+ if os.environ.get("TERM") == "dumb":
+ yield None
+ return
+
+ # NOTE: On Windows < 10, ANSI escape sequences such as \x1b[Am and \x1b[2K,
+ # used to move the cursor and clear text, aren't supported by the built-in
+ # console. However, we rely on the click library's use of colorama which
+ # emulates support for such sequences.
+ #
+ # For this reason, we don't have special checks for Windows.
+
+ block = DynamicBlock()
+
+ with _dynamic_text_lock:
+ _dynamic_blocks.append(block)
+
+ try:
+ yield block
+ finally:
+ with _dynamic_text_lock:
+ block._lines_to_print = []
+ _l_rerender_dynamic_blocks()
+ _dynamic_blocks.remove(block)
+
+
+def _sys_stderr_isatty() -> bool:
+ """Returns sys.stderr.isatty().
+
+ Defined here for patching in tests.
+ """
+ return sys.stderr.isatty()
+
+
+def termlog(
+ string: str = "",
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ r"""Log an informational message to stderr.
+
+ The message may contain ANSI color sequences and the \n character.
+ Colors are stripped if stderr is not a TTY.
+
+ Args:
+ string: The message to display.
+ newline: Whether to add a newline to the end of the string.
+ repeat: If false, then the string is not printed if an exact match has
+ already been printed through any of the other logging functions
+ in this file.
+ prefix: Whether to include the 'wandb:' prefix.
+ """
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_info,
+ )
+
+
+def termwarn(
+ string: str,
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ """Log a warning to stderr.
+
+ The arguments are the same as for `termlog()`.
+ """
+ string = "\n".join([f"{WARN_STRING} {s}" for s in string.split("\n")])
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_warnings,
+ level=logging.WARNING,
+ )
+
+
+def termerror(
+ string: str,
+ newline: bool = True,
+ repeat: bool = True,
+ prefix: bool = True,
+) -> None:
+ """Log an error to stderr.
+
+ The arguments are the same as for `termlog()`.
+ """
+ string = "\n".join([f"{ERROR_STRING} {s}" for s in string.split("\n")])
+ _log(
+ string,
+ newline=newline,
+ repeat=repeat,
+ prefix=prefix,
+ silent=not _show_errors,
+ level=logging.ERROR,
+ )
+
+
+class DynamicBlock:
+ """A handle to a changeable text area in the terminal."""
+
+ def __init__(self):
+ self._lines_to_print = []
+ self._num_lines_printed = 0
+
+ def set_text(self, text: str, prefix=True) -> None:
+ r"""Replace the text in this block.
+
+ Args:
+ text: The text to put in the block, with lines separated
+ by \n characters. The text should not end in \n unless
+ a blank line at the end of the block is desired.
+ prefix: Whether to include the "wandb:" prefix.
+ """
+ with _dynamic_text_lock:
+ self._lines_to_print = text.splitlines()
+
+ if prefix:
+ self._lines_to_print = [
+ f"{LOG_STRING}: {line}" for line in self._lines_to_print
+ ]
+
+ _l_rerender_dynamic_blocks()
+
+ def _l_clear(self) -> None:
+ """Send terminal commands to clear all previously printed lines.
+
+ The lock must be held, and the cursor must be on the line after this
+ block of text.
+ """
+ # NOTE: We rely on the fact that click.echo() uses colorama which
+ # emulates these ANSI sequences on older Windows versions.
+ #
+ # \r move cursor to start of line
+ # \x1b[Am move cursor up
+ # \x1b[2K delete line (sometimes moves cursor)
+ # \r move cursor to start of line
+ move_up_and_delete_line = "\r\x1b[Am\x1b[2K\r"
+ click.echo(
+ move_up_and_delete_line * self._num_lines_printed,
+ file=sys.stderr,
+ nl=False,
+ )
+ self._num_lines_printed = 0
+
+ def _l_print(self) -> None:
+ """Print out this block of text.
+
+ The lock must be held.
+ """
+ if self._lines_to_print:
+ # Trim lines before printing. This is crucial because the \x1b[Am
+ # (cursor up) sequence used when clearing the text moves up by one
+ # visual line, and the terminal may be wrapping long lines onto
+ # multiple visual lines.
+ #
+ # There is no ANSI escape sequence that moves the cursor up by one
+ # "physical" line instead. Note that the user may resize their
+ # terminal.
+ term_width = _shutil_get_terminal_width()
+ click.echo(
+ "\n".join(
+ _ansi_shorten(line, term_width) #
+ for line in self._lines_to_print
+ ),
+ file=sys.stderr,
+ )
+
+ self._num_lines_printed += len(self._lines_to_print)
+
+
+def _shutil_get_terminal_width() -> int:
+ """Returns the width of the terminal.
+
+ Defined here for patching in tests.
+ """
+ columns, _ = shutil.get_terminal_size()
+ return columns
+
+
+_ANSI_RE = re.compile("\x1b\\[(K|.*?m)")
+
+
+def _ansi_shorten(text: str, width: int) -> str:
+ """Shorten text potentially containing ANSI sequences to fit a width."""
+ first_ansi = _ANSI_RE.search(text)
+
+ if not first_ansi:
+ return _raw_shorten(text, width)
+
+ if first_ansi.start() > width - 3:
+ return _raw_shorten(text[: first_ansi.start()], width)
+
+ return text[: first_ansi.end()] + _ansi_shorten(
+ text[first_ansi.end() :],
+ # Key part: the ANSI sequence doesn't reduce the remaining width.
+ width - first_ansi.start(),
+ )
+
+
+def _raw_shorten(text: str, width: int) -> str:
+ """Shorten text to fit a width, replacing the end with "...".
+
+ Unlike textwrap.shorten(), this does not drop whitespace or do anything
+ smart.
+ """
+ if len(text) <= width:
+ return text
+
+ return text[: width - 3] + "..."
+
+
+def _log(
+ string="",
+ newline=True,
+ repeat=True,
+ prefix=True,
+ silent=False,
+ level=logging.INFO,
+) -> None:
+ with _dynamic_text_lock, _l_above_dynamic_text():
+ if not repeat:
+ if string in _printed_messages:
+ return
+
+ if len(_printed_messages) < 1000:
+ _printed_messages.add(string)
+
+ if prefix:
+ string = "\n".join([f"{LOG_STRING}: {s}" for s in string.split("\n")])
+
+ silent = silent or _silent
+ if not silent:
+ click.echo(string, file=sys.stderr, nl=newline)
+ elif not _logger:
+ pass # No fallback logger, so nothing to do.
+ elif level == logging.ERROR:
+ _logger.error(click.unstyle(string))
+ elif level == logging.WARNING:
+ _logger.warning(click.unstyle(string))
+ else:
+ _logger.info(click.unstyle(string))
+
+
+def _l_rerender_dynamic_blocks() -> None:
+ """Clear and re-print all dynamic text.
+
+ The lock must be held. The cursor must be positioned at the start of
+ the first line after the dynamic text area.
+ """
+ with _l_above_dynamic_text():
+ # We just want the side-effect of rerendering the dynamic text.
+ pass
+
+
+@contextlib.contextmanager
+def _l_above_dynamic_text():
+ """A context manager for inserting static text above any dynamic text.
+
+ The lock must be held. The cursor must be positioned at the start of the
+ first line after the dynamic text area.
+
+ The dynamic text is re-rendered.
+ """
+ _l_clear_dynamic_blocks()
+
+ try:
+ yield
+ finally:
+ _l_print_dynamic_blocks()
+
+
+def _l_clear_dynamic_blocks() -> None:
+ """Delete all dynamic text.
+
+ The lock must be held, and the cursor must be positioned at the start
+ of the first line after the dynamic text area. After this, the cursor
+ is positioned at the start of the first line after all static text.
+ """
+ for block in reversed(_dynamic_blocks):
+ block._l_clear()
+
+
+def _l_print_dynamic_blocks() -> None:
+ """Output all dynamic text.
+
+ The lock must be held. After this, the cursor is positioned at the start
+ of the first line after the dynamic text area.
+ """
+ for block in _dynamic_blocks:
+ block._l_print()
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/util.py b/venv/lib/python3.10/site-packages/wandb/errors/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..0dd207c9e59f6ad15405b753c29f8b241238941a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/util.py
@@ -0,0 +1,57 @@
+from typing import Optional
+
+from wandb.proto import wandb_internal_pb2 as pb
+
+from . import AuthenticationError, CommError, Error, UnsupportedError, UsageError
+
+to_exception_map = {
+ pb.ErrorInfo.UNKNOWN: Error,
+ pb.ErrorInfo.COMMUNICATION: CommError,
+ pb.ErrorInfo.AUTHENTICATION: AuthenticationError,
+ pb.ErrorInfo.USAGE: UsageError,
+ pb.ErrorInfo.UNSUPPORTED: UnsupportedError,
+}
+
+from_exception_map = {v: k for k, v in to_exception_map.items()}
+
+
+class ProtobufErrorHandler:
+ """Converts protobuf errors to exceptions and vice versa."""
+
+ @staticmethod
+ def to_exception(error: pb.ErrorInfo) -> Optional[Error]:
+ """Convert a protobuf error to an exception.
+
+ Args:
+ error: The protobuf error to convert.
+
+ Returns:
+ The corresponding exception.
+
+ """
+ if not error.SerializeToString():
+ return None
+
+ if error.code in to_exception_map:
+ return to_exception_map[error.code](error.message)
+ return Error(error.message)
+
+ @classmethod
+ def from_exception(cls, exc: Error) -> "pb.ErrorInfo":
+ """Convert an wandb error to a protobuf error message.
+
+ Args:
+ exc: The exception to convert.
+
+ Returns:
+ The corresponding protobuf error message.
+ """
+ if not isinstance(exc, Error):
+ raise TypeError("exc must be a subclass of wandb.errors.Error")
+
+ code = None
+ for subclass in type(exc).__mro__:
+ if subclass in from_exception_map:
+ code = from_exception_map[subclass] # type: ignore
+ break
+ return pb.ErrorInfo(code=code, message=str(exc)) # type: ignore
diff --git a/venv/lib/python3.10/site-packages/wandb/errors/warnings.py b/venv/lib/python3.10/site-packages/wandb/errors/warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f956757b378de6f5481aeb467961013ad264f3a9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/errors/warnings.py
@@ -0,0 +1,2 @@
+class WandbWarning(Warning):
+ """Base W&B Warning."""
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__init__.py b/venv/lib/python3.10/site-packages/wandb/filesync/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a4fd72a567243f340fca376d10a051f81fad41b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/dir_watcher.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/dir_watcher.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c23ca540ab552336070e9364e851fb1c29baa4b4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/dir_watcher.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd49c8f8c456fb29e627c032a177b6d9ee383e88
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/stats.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_checksum.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_checksum.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58d742efd3f654a419e5acb1f4d0cd72b3a7ba62
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_checksum.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_prepare.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_prepare.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4e2010fbd74743f44b24dcfc6121a826a255717
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_prepare.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_upload.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_upload.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84cb6b72c5e3873029677b174ad8b4a45d43048e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/step_upload.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/upload_job.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/upload_job.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f55f79dafe645b9f0798a437d025fe48fa798f1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/filesync/__pycache__/upload_job.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py b/venv/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a423fc8a88f3794489752e84f969f434e300a10
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/dir_watcher.py
@@ -0,0 +1,404 @@
+import abc
+import fnmatch
+import glob
+import logging
+import os
+import queue
+import time
+from typing import TYPE_CHECKING, Any, Mapping, MutableMapping, MutableSet, Optional
+
+from wandb import util
+from wandb.sdk.interface.interface import GlobStr
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ import wandb.vendor.watchdog_0_9_0.observers.api as wd_api
+ import wandb.vendor.watchdog_0_9_0.observers.polling as wd_polling
+ import wandb.vendor.watchdog_0_9_0.watchdog.events as wd_events
+ from wandb.sdk.interface.interface import PolicyName
+ from wandb.sdk.internal.file_pusher import FilePusher
+ from wandb.sdk.internal.settings_static import SettingsStatic
+else:
+ wd_polling = util.vendor_import("wandb_watchdog.observers.polling")
+ wd_events = util.vendor_import("wandb_watchdog.events")
+
+PathStr = str # TODO(spencerpearson): would be nice to use Path here
+
+
+logger = logging.getLogger(__name__)
+
+
+class FileEventHandler(abc.ABC):
+ def __init__(
+ self,
+ file_path: PathStr,
+ save_name: LogicalPath,
+ file_pusher: "FilePusher",
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ self.file_path = file_path
+ # Convert windows paths to unix paths
+ self.save_name = LogicalPath(save_name)
+ self._file_pusher = file_pusher
+ self._last_sync: Optional[float] = None
+
+ @property
+ @abc.abstractmethod
+ def policy(self) -> "PolicyName":
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def on_modified(self, force: bool = False) -> None:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def finish(self) -> None:
+ raise NotImplementedError
+
+ def on_renamed(self, new_path: PathStr, new_name: LogicalPath) -> None:
+ self.file_path = new_path
+ self.save_name = new_name
+ self.on_modified()
+
+
+class PolicyNow(FileEventHandler):
+ """This policy only uploads files now."""
+
+ def on_modified(self, force: bool = False) -> None:
+ # only upload if we've never uploaded or when .save is called
+ if self._last_sync is None or force:
+ self._file_pusher.file_changed(self.save_name, self.file_path)
+ self._last_sync = os.path.getmtime(self.file_path)
+
+ def finish(self) -> None:
+ pass
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "now"
+
+
+class PolicyEnd(FileEventHandler):
+ """This policy only updates at the end of the run."""
+
+ def on_modified(self, force: bool = False) -> None:
+ pass
+
+ # TODO: make sure we call this
+ def finish(self) -> None:
+ # We use copy=False to avoid possibly expensive copies, and because
+ # user files shouldn't still be changing at the end of the run.
+ self._last_sync = os.path.getmtime(self.file_path)
+ self._file_pusher.file_changed(self.save_name, self.file_path, copy=False)
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "end"
+
+
+class PolicyLive(FileEventHandler):
+ """Event handler that uploads respecting throttling.
+
+ Uploads files every RATE_LIMIT_SECONDS, which changes as the size increases to deal
+ with throttling.
+ """
+
+ RATE_LIMIT_SECONDS = 15
+ unit_dict = dict(util.POW_10_BYTES)
+ # Wait to upload until size has increased 20% from last upload
+ RATE_LIMIT_SIZE_INCREASE = 1.2
+
+ def __init__(
+ self,
+ file_path: PathStr,
+ save_name: LogicalPath,
+ file_pusher: "FilePusher",
+ settings: Optional["SettingsStatic"] = None,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(file_path, save_name, file_pusher, *args, **kwargs)
+ self._last_uploaded_time: Optional[float] = None
+ self._last_uploaded_size: int = 0
+ if settings is not None:
+ if settings.x_live_policy_rate_limit is not None:
+ self.RATE_LIMIT_SECONDS = settings.x_live_policy_rate_limit
+ self._min_wait_time: Optional[float] = settings.x_live_policy_wait_time
+ else:
+ self._min_wait_time = None
+
+ @property
+ def current_size(self) -> int:
+ return os.path.getsize(self.file_path)
+
+ @classmethod
+ def min_wait_for_size(cls, size: int) -> float:
+ if size < 10 * cls.unit_dict["MB"]:
+ return 60
+ elif size < 100 * cls.unit_dict["MB"]:
+ return 5 * 60
+ elif size < cls.unit_dict["GB"]:
+ return 10 * 60
+ else:
+ return 20 * 60
+
+ def should_update(self) -> bool:
+ if self._last_uploaded_time is not None:
+ # Check rate limit by time elapsed
+ time_elapsed = time.time() - self._last_uploaded_time
+ # if more than 15 seconds has passed potentially upload it
+ if time_elapsed < self.RATE_LIMIT_SECONDS:
+ return False
+
+ # Check rate limit by size increase
+ if float(self._last_uploaded_size) > 0:
+ size_increase = self.current_size / float(self._last_uploaded_size)
+ if size_increase < self.RATE_LIMIT_SIZE_INCREASE:
+ return False
+ return time_elapsed > (
+ self._min_wait_time or self.min_wait_for_size(self.current_size)
+ )
+
+ # if the file has never been uploaded, we'll upload it
+ return True
+
+ def on_modified(self, force: bool = False) -> None:
+ if self.current_size == 0:
+ return
+ if self._last_sync == os.path.getmtime(self.file_path):
+ return
+ if force or self.should_update():
+ self.save_file()
+
+ def save_file(self) -> None:
+ self._last_sync = os.path.getmtime(self.file_path)
+ self._last_uploaded_time = time.time()
+ self._last_uploaded_size = self.current_size
+ self._file_pusher.file_changed(self.save_name, self.file_path)
+
+ def finish(self) -> None:
+ self.on_modified(force=True)
+
+ @property
+ def policy(self) -> "PolicyName":
+ return "live"
+
+
+class DirWatcher:
+ def __init__(
+ self,
+ settings: "SettingsStatic",
+ file_pusher: "FilePusher",
+ file_dir: Optional[PathStr] = None,
+ ) -> None:
+ self._file_count = 0
+ self._dir = file_dir or settings.files_dir
+ self._settings = settings
+ self._savename_file_policies: MutableMapping[LogicalPath, PolicyName] = {}
+ self._user_file_policies: Mapping[PolicyName, MutableSet[GlobStr]] = {
+ "end": set(),
+ "live": set(),
+ "now": set(),
+ }
+ self._file_pusher = file_pusher
+ self._file_event_handlers: MutableMapping[LogicalPath, FileEventHandler] = {}
+ self._file_observer = wd_polling.PollingObserver()
+ self._file_observer.schedule(
+ self._per_file_event_handler(), self._dir, recursive=True
+ )
+ self._file_observer.start()
+ logger.info("watching files in: %s", settings.files_dir)
+
+ @property
+ def emitter(self) -> Optional["wd_api.EventEmitter"]:
+ try:
+ return next(iter(self._file_observer.emitters))
+ except StopIteration:
+ return None
+
+ def update_policy(self, path: GlobStr, policy: "PolicyName") -> None:
+ # When we're dealing with one of our own media files, there's no need
+ # to store the policy in memory. _get_file_event_handler will always
+ # return PolicyNow. Using the path makes syncing historic runs much
+ # faster if the name happens to include glob escapable characters. In
+ # the future we may add a flag to "files" records that indicates it's
+ # policy is not dynamic and doesn't need to be stored / checked.
+ save_name = LogicalPath(
+ os.path.relpath(os.path.join(self._dir, path), self._dir)
+ )
+ if save_name.startswith("media/"):
+ pass
+ elif path == glob.escape(path):
+ self._savename_file_policies[save_name] = policy
+ else:
+ self._user_file_policies[policy].add(path)
+
+ for src_path in glob.glob(os.path.join(self._dir, path)):
+ save_name = LogicalPath(os.path.relpath(src_path, self._dir))
+ feh = self._get_file_event_handler(src_path, save_name)
+ # handle the case where the policy changed
+ if feh.policy != policy:
+ try:
+ del self._file_event_handlers[save_name]
+ except KeyError:
+ # TODO: probably should do locking, but this handles moved files for now
+ pass
+ feh = self._get_file_event_handler(src_path, save_name)
+ feh.on_modified(force=True)
+
+ def _per_file_event_handler(self) -> "wd_events.FileSystemEventHandler":
+ """Create a Watchdog file event handler that does different things for every file."""
+ file_event_handler = wd_events.PatternMatchingEventHandler()
+ file_event_handler.on_created = self._on_file_created
+ file_event_handler.on_modified = self._on_file_modified
+ file_event_handler.on_moved = self._on_file_moved
+ file_event_handler._patterns = [os.path.join(self._dir, os.path.normpath("*"))]
+ # Ignore hidden files/folders
+ # TODO: what other files should we skip?
+ file_event_handler._ignore_patterns = [
+ "*.tmp",
+ "*.wandb",
+ "wandb-summary.json",
+ os.path.join(self._dir, ".*"),
+ os.path.join(self._dir, "*/.*"),
+ ]
+ for glb in self._settings.ignore_globs:
+ file_event_handler._ignore_patterns.append(os.path.join(self._dir, glb))
+
+ return file_event_handler
+
+ def _on_file_created(self, event: "wd_events.FileCreatedEvent") -> None:
+ logger.info("file/dir created: %s", event.src_path)
+ if os.path.isdir(event.src_path):
+ return None
+ self._file_count += 1
+ # We do the directory scan less often as it grows
+ if self._file_count % 100 == 0:
+ emitter = self.emitter
+ if emitter:
+ emitter._timeout = int(self._file_count / 100) + 1
+ save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ self._get_file_event_handler(event.src_path, save_name).on_modified()
+
+ # TODO(spencerpearson): this pattern repeats so many times we should have a method/function for it
+ # def _save_name(self, path: PathStr) -> LogicalPath:
+ # return LogicalPath(os.path.relpath(path, self._dir))
+
+ def _on_file_modified(self, event: "wd_events.FileModifiedEvent") -> None:
+ logger.info(f"file/dir modified: {event.src_path}")
+ if os.path.isdir(event.src_path):
+ return None
+ save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ self._get_file_event_handler(event.src_path, save_name).on_modified()
+
+ def _on_file_moved(self, event: "wd_events.FileMovedEvent") -> None:
+ # TODO: test me...
+ logger.info(f"file/dir moved: {event.src_path} -> {event.dest_path}")
+ if os.path.isdir(event.dest_path):
+ return None
+ old_save_name = LogicalPath(os.path.relpath(event.src_path, self._dir))
+ new_save_name = LogicalPath(os.path.relpath(event.dest_path, self._dir))
+
+ # We have to move the existing file handler to the new name
+ handler = self._get_file_event_handler(event.src_path, old_save_name)
+ self._file_event_handlers[new_save_name] = handler
+ del self._file_event_handlers[old_save_name]
+
+ handler.on_renamed(event.dest_path, new_save_name)
+
+ def _get_file_event_handler(
+ self, file_path: PathStr, save_name: LogicalPath
+ ) -> FileEventHandler:
+ """Get or create an event handler for a particular file.
+
+ file_path: the file's actual path
+ save_name: its path relative to the run directory (aka the watch directory)
+ """
+ # Always return PolicyNow for any of our media files.
+ if save_name.startswith("media/"):
+ return PolicyNow(file_path, save_name, self._file_pusher, self._settings)
+ if save_name not in self._file_event_handlers:
+ # TODO: we can use PolicyIgnore if there are files we never want to sync
+ if "tfevents" in save_name or "graph.pbtxt" in save_name:
+ self._file_event_handlers[save_name] = PolicyLive(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ elif save_name in self._savename_file_policies:
+ policy_name = self._savename_file_policies[save_name]
+ make_handler = (
+ PolicyLive
+ if policy_name == "live"
+ else PolicyNow
+ if policy_name == "now"
+ else PolicyEnd
+ )
+ self._file_event_handlers[save_name] = make_handler(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ else:
+ make_handler = PolicyEnd
+ for policy, globs in self._user_file_policies.items():
+ if policy == "end":
+ continue
+ # Convert set to list to avoid RuntimeError's
+ # TODO: we may need to add locks
+ for g in list(globs):
+ paths = glob.glob(os.path.join(self._dir, g))
+ if any(save_name in p for p in paths):
+ if policy == "live":
+ make_handler = PolicyLive
+ elif policy == "now":
+ make_handler = PolicyNow
+ self._file_event_handlers[save_name] = make_handler(
+ file_path, save_name, self._file_pusher, self._settings
+ )
+ return self._file_event_handlers[save_name]
+
+ def finish(self) -> None:
+ logger.info("shutting down directory watcher")
+ try:
+ # avoid hanging if we crashed before the observer was started
+ if self._file_observer.is_alive():
+ # rather unfortunately we need to manually do a final scan of the dir
+ # with `queue_events`, then iterate through all events before stopping
+ # the observer to catch all files written. First we need to prevent the
+ # existing thread from consuming our final events, then we process them
+ self._file_observer._timeout = 0
+ self._file_observer._stopped_event.set()
+ self._file_observer.join()
+ self.emitter.queue_events(0) # type: ignore[union-attr]
+ while True:
+ try:
+ self._file_observer.dispatch_events(
+ self._file_observer.event_queue, 0
+ )
+ except queue.Empty:
+ break
+ # Calling stop unschedules any inflight events so we handled them above
+ self._file_observer.stop()
+ # TODO: py2 TypeError: PyCObject_AsVoidPtr called with null pointer
+ except TypeError:
+ pass
+ # TODO: py3 SystemError: returned an error
+ except SystemError:
+ pass
+
+ # Ensure we've at least noticed every file in the run directory. Sometimes
+ # we miss things because asynchronously watching filesystems isn't reliable.
+ logger.info("scan: %s", self._dir)
+
+ for dirpath, _, filenames in os.walk(self._dir):
+ for fname in filenames:
+ file_path = os.path.join(dirpath, fname)
+ save_name = LogicalPath(os.path.relpath(file_path, self._dir))
+ ignored = False
+ for glb in self._settings.ignore_globs:
+ if len(fnmatch.filter([save_name], glb)) > 0:
+ ignored = True
+ logger.info("ignored: %s matching glob %s", save_name, glb)
+ break
+ if ignored:
+ continue
+ logger.info("scan save: %s %s", file_path, save_name)
+ self._get_file_event_handler(file_path, save_name).finish()
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/stats.py b/venv/lib/python3.10/site-packages/wandb/filesync/stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..95c3523a37a2a82ce17bd40a6b4a667db04ff0ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/stats.py
@@ -0,0 +1,100 @@
+import threading
+from typing import MutableMapping, NamedTuple
+
+import wandb
+
+
+class FileStats(NamedTuple):
+ deduped: bool
+ total: int
+ uploaded: int
+ failed: bool
+ artifact_file: bool
+
+
+class Summary(NamedTuple):
+ uploaded_bytes: int
+ total_bytes: int
+ deduped_bytes: int
+
+
+class FileCountsByCategory(NamedTuple):
+ artifact: int
+ wandb: int
+ media: int
+ other: int
+
+
+class Stats:
+ def __init__(self) -> None:
+ self._stats: MutableMapping[str, FileStats] = {}
+ self._lock = threading.Lock()
+
+ def init_file(
+ self, save_name: str, size: int, is_artifact_file: bool = False
+ ) -> None:
+ with self._lock:
+ self._stats[save_name] = FileStats(
+ deduped=False,
+ total=size,
+ uploaded=0,
+ failed=False,
+ artifact_file=is_artifact_file,
+ )
+
+ def set_file_deduped(self, save_name: str) -> None:
+ with self._lock:
+ orig = self._stats[save_name]
+ self._stats[save_name] = orig._replace(
+ deduped=True,
+ uploaded=orig.total,
+ )
+
+ def update_uploaded_file(self, save_name: str, total_uploaded: int) -> None:
+ with self._lock:
+ self._stats[save_name] = self._stats[save_name]._replace(
+ uploaded=total_uploaded,
+ )
+
+ def update_failed_file(self, save_name: str) -> None:
+ with self._lock:
+ self._stats[save_name] = self._stats[save_name]._replace(
+ uploaded=0,
+ failed=True,
+ )
+
+ def summary(self) -> Summary:
+ # Need to use list to ensure we get a copy, since other threads may
+ # modify this while we iterate
+ with self._lock:
+ stats = list(self._stats.values())
+ return Summary(
+ uploaded_bytes=sum(f.uploaded for f in stats),
+ total_bytes=sum(f.total for f in stats),
+ deduped_bytes=sum(f.total for f in stats if f.deduped),
+ )
+
+ def file_counts_by_category(self) -> FileCountsByCategory:
+ artifact_files = 0
+ wandb_files = 0
+ media_files = 0
+ other_files = 0
+ # Need to use list to ensure we get a copy, since other threads may
+ # modify this while we iterate
+ with self._lock:
+ file_stats = list(self._stats.items())
+ for save_name, stats in file_stats:
+ if stats.artifact_file:
+ artifact_files += 1
+ elif wandb.wandb_lib.filenames.is_wandb_file(save_name): # type: ignore[attr-defined] # TODO(spencerpearson): this is probably synonymous with wandb.sdk.lib.filenames...?
+ wandb_files += 1
+ elif save_name.startswith("media"):
+ media_files += 1
+ else:
+ other_files += 1
+ return FileCountsByCategory(
+ artifact=artifact_files,
+ wandb=wandb_files,
+ media=media_files,
+ other=other_files,
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/step_checksum.py b/venv/lib/python3.10/site-packages/wandb/filesync/step_checksum.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0acd96e80e8ad7b4fb8027da718a3b28780f86e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/step_checksum.py
@@ -0,0 +1,142 @@
+"""Batching file prepare requests to our API."""
+
+import concurrent.futures
+import functools
+import os
+import queue
+import shutil
+import threading
+from typing import TYPE_CHECKING, NamedTuple, Optional, Union, cast
+
+from wandb.filesync import step_upload
+from wandb.sdk.lib import filesystem, runid
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ import tempfile
+
+ from wandb.filesync import stats
+ from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest
+ from wandb.sdk.artifacts.artifact_saver import SaveFn
+ from wandb.sdk.internal import internal_api
+
+
+class RequestUpload(NamedTuple):
+ path: str
+ save_name: LogicalPath
+ copy: bool
+
+
+class RequestStoreManifestFiles(NamedTuple):
+ manifest: "ArtifactManifest"
+ artifact_id: str
+ save_fn: "SaveFn"
+
+
+class RequestCommitArtifact(NamedTuple):
+ artifact_id: str
+ finalize: bool
+ before_commit: step_upload.PreCommitFn
+ result_future: "concurrent.futures.Future[None]"
+
+
+class RequestFinish(NamedTuple):
+ callback: Optional[step_upload.OnRequestFinishFn]
+
+
+Event = Union[
+ RequestUpload, RequestStoreManifestFiles, RequestCommitArtifact, RequestFinish
+]
+
+
+class StepChecksum:
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ tempdir: "tempfile.TemporaryDirectory",
+ request_queue: "queue.Queue[Event]",
+ output_queue: "queue.Queue[step_upload.Event]",
+ stats: "stats.Stats",
+ ) -> None:
+ self._api = api
+ self._tempdir = tempdir
+ self._request_queue = request_queue
+ self._output_queue = output_queue
+ self._stats = stats
+
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ def _thread_body(self) -> None:
+ while True:
+ req = self._request_queue.get()
+ if isinstance(req, RequestUpload):
+ path = req.path
+ if req.copy:
+ path = os.path.join(
+ self._tempdir.name,
+ f"{runid.generate_id()}-{req.save_name}",
+ )
+ filesystem.mkdir_exists_ok(os.path.dirname(path))
+ try:
+ # certain linux distros throw an exception when copying
+ # large files: https://bugs.python.org/issue43743
+ shutil.copy2(req.path, path)
+ except OSError:
+ shutil._USE_CP_SENDFILE = False # type: ignore[attr-defined]
+ shutil.copy2(req.path, path)
+ self._stats.init_file(req.save_name, os.path.getsize(path))
+ self._output_queue.put(
+ step_upload.RequestUpload(
+ path,
+ req.save_name,
+ None,
+ None,
+ req.copy,
+ None,
+ None,
+ )
+ )
+ elif isinstance(req, RequestStoreManifestFiles):
+ for entry in req.manifest.entries.values():
+ if entry.local_path:
+ self._stats.init_file(
+ entry.local_path,
+ cast(int, entry.size),
+ is_artifact_file=True,
+ )
+ self._output_queue.put(
+ step_upload.RequestUpload(
+ entry.local_path,
+ entry.path,
+ req.artifact_id,
+ entry.digest,
+ False,
+ functools.partial(req.save_fn, entry),
+ entry.digest,
+ )
+ )
+ elif isinstance(req, RequestCommitArtifact):
+ self._output_queue.put(
+ step_upload.RequestCommitArtifact(
+ req.artifact_id,
+ req.finalize,
+ req.before_commit,
+ req.result_future,
+ )
+ )
+ elif isinstance(req, RequestFinish):
+ break
+ else:
+ raise TypeError
+
+ self._output_queue.put(step_upload.RequestFinish(req.callback))
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
+
+ def finish(self) -> None:
+ self._request_queue.put(RequestFinish(None))
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/step_prepare.py b/venv/lib/python3.10/site-packages/wandb/filesync/step_prepare.py
new file mode 100644
index 0000000000000000000000000000000000000000..95a4a21b4593a62dd21d080e847c212eef7e2ca7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/step_prepare.py
@@ -0,0 +1,179 @@
+"""Batching file prepare requests to our API."""
+
+import queue
+import threading
+import time
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ Dict,
+ List,
+ Mapping,
+ NamedTuple,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+if TYPE_CHECKING:
+ from wandb.sdk.internal.internal_api import (
+ Api,
+ CreateArtifactFileSpecInput,
+ CreateArtifactFilesResponseFile,
+ )
+
+
+# Request for a file to be prepared.
+class RequestPrepare(NamedTuple):
+ file_spec: "CreateArtifactFileSpecInput"
+ response_channel: "queue.Queue[ResponsePrepare]"
+
+
+class RequestFinish(NamedTuple):
+ pass
+
+
+class ResponsePrepare(NamedTuple):
+ birth_artifact_id: str
+ upload_url: Optional[str]
+ upload_headers: Sequence[str]
+ upload_id: Optional[str]
+ storage_path: Optional[str]
+ multipart_upload_urls: Optional[Dict[int, str]]
+
+
+Request = Union[RequestPrepare, RequestFinish]
+
+
+def _clamp(x: float, low: float, high: float) -> float:
+ return max(low, min(x, high))
+
+
+def gather_batch(
+ request_queue: "queue.Queue[Request]",
+ batch_time: float,
+ inter_event_time: float,
+ max_batch_size: int,
+ clock: Callable[[], float] = time.monotonic,
+) -> Tuple[bool, Sequence[RequestPrepare]]:
+ batch_start_time = clock()
+ remaining_time = batch_time
+
+ first_request = request_queue.get()
+ if isinstance(first_request, RequestFinish):
+ return True, []
+
+ batch: List[RequestPrepare] = [first_request]
+
+ while remaining_time > 0 and len(batch) < max_batch_size:
+ try:
+ request = request_queue.get(
+ timeout=_clamp(
+ x=inter_event_time,
+ low=1e-12, # 0 = "block forever", so just use something tiny
+ high=remaining_time,
+ ),
+ )
+ if isinstance(request, RequestFinish):
+ return True, batch
+
+ batch.append(request)
+ remaining_time = batch_time - (clock() - batch_start_time)
+
+ except queue.Empty:
+ break
+
+ return False, batch
+
+
+def prepare_response(response: "CreateArtifactFilesResponseFile") -> ResponsePrepare:
+ multipart_resp = response.get("uploadMultipartUrls")
+ part_list = multipart_resp["uploadUrlParts"] if multipart_resp else []
+ multipart_parts = {u["partNumber"]: u["uploadUrl"] for u in part_list} or None
+
+ return ResponsePrepare(
+ birth_artifact_id=response["artifact"]["id"],
+ upload_url=response["uploadUrl"],
+ upload_headers=response["uploadHeaders"],
+ upload_id=multipart_resp and multipart_resp.get("uploadID"),
+ storage_path=response.get("storagePath"),
+ multipart_upload_urls=multipart_parts,
+ )
+
+
+class StepPrepare:
+ """A thread that batches requests to our file prepare API.
+
+ Any number of threads may call prepare() in parallel. The PrepareBatcher thread
+ will batch requests up and send them all to the backend at once.
+ """
+
+ def __init__(
+ self,
+ api: "Api",
+ batch_time: float,
+ inter_event_time: float,
+ max_batch_size: int,
+ request_queue: Optional["queue.Queue[Request]"] = None,
+ ) -> None:
+ self._api = api
+ self._inter_event_time = inter_event_time
+ self._batch_time = batch_time
+ self._max_batch_size = max_batch_size
+ self._request_queue: queue.Queue[Request] = request_queue or queue.Queue()
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ def _thread_body(self) -> None:
+ while True:
+ finish, batch = gather_batch(
+ request_queue=self._request_queue,
+ batch_time=self._batch_time,
+ inter_event_time=self._inter_event_time,
+ max_batch_size=self._max_batch_size,
+ )
+ if batch:
+ batch_response = self._prepare_batch(batch)
+ # send responses
+ for prepare_request in batch:
+ name = prepare_request.file_spec["name"]
+ response_file = batch_response[name]
+ response = prepare_response(response_file)
+ prepare_request.response_channel.put(response)
+ if finish:
+ break
+
+ def _prepare_batch(
+ self, batch: Sequence[RequestPrepare]
+ ) -> Mapping[str, "CreateArtifactFilesResponseFile"]:
+ """Execute the prepareFiles API call.
+
+ Args:
+ batch: List of RequestPrepare objects
+ Returns:
+ dict of (save_name: ResponseFile) pairs where ResponseFile is a dict with
+ an uploadUrl key. The value of the uploadUrl key is None if the file
+ already exists, or a url string if the file should be uploaded.
+ """
+ return self._api.create_artifact_files([req.file_spec for req in batch])
+
+ def prepare(
+ self, file_spec: "CreateArtifactFileSpecInput"
+ ) -> "queue.Queue[ResponsePrepare]":
+ response_queue: queue.Queue[ResponsePrepare] = queue.Queue()
+ self._request_queue.put(RequestPrepare(file_spec, response_queue))
+ return response_queue
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def finish(self) -> None:
+ self._request_queue.put(RequestFinish())
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
+
+ def shutdown(self) -> None:
+ self.finish()
+ self._thread.join()
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/step_upload.py b/venv/lib/python3.10/site-packages/wandb/filesync/step_upload.py
new file mode 100644
index 0000000000000000000000000000000000000000..0840293d35aaf53aeaf8d211783f9be957beafe2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/step_upload.py
@@ -0,0 +1,287 @@
+"""Batching file prepare requests to our API."""
+
+import concurrent.futures
+import logging
+import queue
+import sys
+import threading
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ MutableMapping,
+ MutableSequence,
+ MutableSet,
+ NamedTuple,
+ Optional,
+ Union,
+)
+
+from wandb.errors.term import termerror
+from wandb.filesync import upload_job
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from typing import TypedDict
+
+ from wandb.filesync import stats
+ from wandb.sdk.internal import file_stream, internal_api, progress
+ from wandb.sdk.internal.settings_static import SettingsStatic
+
+ class ArtifactStatus(TypedDict):
+ finalize: bool
+ pending_count: int
+ commit_requested: bool
+ pre_commit_callbacks: MutableSet["PreCommitFn"]
+ result_futures: MutableSet["concurrent.futures.Future[None]"]
+
+
+PreCommitFn = Callable[[], None]
+OnRequestFinishFn = Callable[[], None]
+SaveFn = Callable[["progress.ProgressFn"], bool]
+
+logger = logging.getLogger(__name__)
+
+
+class RequestUpload(NamedTuple):
+ path: str
+ save_name: LogicalPath
+ artifact_id: Optional[str]
+ md5: Optional[str]
+ copied: bool
+ save_fn: Optional[SaveFn]
+ digest: Optional[str]
+
+
+class RequestCommitArtifact(NamedTuple):
+ artifact_id: str
+ finalize: bool
+ before_commit: PreCommitFn
+ result_future: "concurrent.futures.Future[None]"
+
+
+class RequestFinish(NamedTuple):
+ callback: Optional[OnRequestFinishFn]
+
+
+class EventJobDone(NamedTuple):
+ job: RequestUpload
+ exc: Optional[BaseException]
+
+
+Event = Union[RequestUpload, RequestCommitArtifact, RequestFinish, EventJobDone]
+
+
+class StepUpload:
+ def __init__(
+ self,
+ api: "internal_api.Api",
+ stats: "stats.Stats",
+ event_queue: "queue.Queue[Event]",
+ max_threads: int,
+ file_stream: "file_stream.FileStreamApi",
+ settings: Optional["SettingsStatic"] = None,
+ ) -> None:
+ self._api = api
+ self._stats = stats
+ self._event_queue = event_queue
+ self._file_stream = file_stream
+
+ self._thread = threading.Thread(target=self._thread_body)
+ self._thread.daemon = True
+
+ self._pool = concurrent.futures.ThreadPoolExecutor(
+ thread_name_prefix="wandb-upload",
+ max_workers=max_threads,
+ )
+
+ # Indexed by files' `save_name`'s, which are their ID's in the Run.
+ self._running_jobs: MutableMapping[LogicalPath, RequestUpload] = {}
+ self._pending_jobs: MutableSequence[RequestUpload] = []
+
+ self._artifacts: MutableMapping[str, ArtifactStatus] = {}
+
+ self.silent = bool(settings.silent) if settings else False
+
+ def _thread_body(self) -> None:
+ event: Optional[Event]
+ # Wait for event in the queue, and process one by one until a
+ # finish event is received
+ finish_callback = None
+ while True:
+ event = self._event_queue.get()
+ if isinstance(event, RequestFinish):
+ finish_callback = event.callback
+ break
+ self._handle_event(event)
+
+ # We've received a finish event. At this point, further Upload requests
+ # are invalid.
+
+ # After a finish event is received, iterate through the event queue
+ # one by one and process all remaining events.
+ while True:
+ try:
+ event = self._event_queue.get(True, 0.2)
+ except queue.Empty:
+ event = None
+ if event:
+ self._handle_event(event)
+ elif not self._running_jobs:
+ # Queue was empty and no jobs left.
+ self._pool.shutdown(wait=False)
+ if finish_callback:
+ finish_callback()
+ break
+
+ def _handle_event(self, event: Event) -> None:
+ if isinstance(event, EventJobDone):
+ job = event.job
+
+ if event.exc is not None:
+ logger.exception(
+ "Failed to upload file: %s", job.path, exc_info=event.exc
+ )
+
+ if job.artifact_id:
+ if event.exc is None:
+ self._artifacts[job.artifact_id]["pending_count"] -= 1
+ self._maybe_commit_artifact(job.artifact_id)
+ else:
+ if not self.silent:
+ termerror(
+ "Uploading artifact file failed. Artifact won't be committed."
+ )
+ self._fail_artifact_futures(job.artifact_id, event.exc)
+ self._running_jobs.pop(job.save_name)
+ # If we have any pending jobs, start one now
+ if self._pending_jobs:
+ event = self._pending_jobs.pop(0)
+ self._start_upload_job(event)
+ elif isinstance(event, RequestCommitArtifact):
+ if event.artifact_id not in self._artifacts:
+ self._init_artifact(event.artifact_id)
+ self._artifacts[event.artifact_id]["commit_requested"] = True
+ self._artifacts[event.artifact_id]["finalize"] = event.finalize
+ self._artifacts[event.artifact_id]["pre_commit_callbacks"].add(
+ event.before_commit
+ )
+ self._artifacts[event.artifact_id]["result_futures"].add(
+ event.result_future
+ )
+ self._maybe_commit_artifact(event.artifact_id)
+ elif isinstance(event, RequestUpload):
+ if event.artifact_id is not None:
+ if event.artifact_id not in self._artifacts:
+ self._init_artifact(event.artifact_id)
+ self._artifacts[event.artifact_id]["pending_count"] += 1
+ self._start_upload_job(event)
+ else:
+ raise TypeError(f"Event has unexpected type: {event!s}")
+
+ def _start_upload_job(self, event: RequestUpload) -> None:
+ # Operations on a single backend file must be serialized. if
+ # we're already uploading this file, put the event on the
+ # end of the queue
+ if event.save_name in self._running_jobs:
+ self._pending_jobs.append(event)
+ return
+
+ self._spawn_upload(event)
+
+ def _spawn_upload(self, event: RequestUpload) -> None:
+ """Spawn an upload job, and handles the bookkeeping of `self._running_jobs`.
+
+ Context: it's important that, whenever we add an entry to `self._running_jobs`,
+ we ensure that a corresponding `EventJobDone` message will eventually get handled;
+ otherwise, the `_running_jobs` entry will never get removed, and the StepUpload
+ will never shut down.
+
+ The sole purpose of this function is to make sure that the code that adds an entry
+ to `self._running_jobs` is textually right next to the code that eventually enqueues
+ the `EventJobDone` message. This should help keep them in sync.
+ """
+ # Adding the entry to `self._running_jobs` MUST happen in the main thread,
+ # NOT in the job that gets submitted to the thread-pool, to guard against
+ # this sequence of events:
+ # - StepUpload receives a RequestUpload
+ # ...and therefore spawns a thread to do the upload
+ # - StepUpload receives a RequestFinish
+ # ...and checks `self._running_jobs` to see if there are any tasks to wait for...
+ # ...and there are none, because the addition to `self._running_jobs` happens in
+ # the background thread, which the scheduler hasn't yet run...
+ # ...so the StepUpload shuts down. Even though we haven't uploaded the file!
+ #
+ # This would be very bad!
+ # So, this line has to happen _outside_ the `pool.submit()`.
+ self._running_jobs[event.save_name] = event
+
+ def run_and_notify() -> None:
+ try:
+ self._do_upload(event)
+ finally:
+ self._event_queue.put(EventJobDone(event, exc=sys.exc_info()[1]))
+
+ self._pool.submit(run_and_notify)
+
+ def _do_upload(self, event: RequestUpload) -> None:
+ job = upload_job.UploadJob(
+ self._stats,
+ self._api,
+ self._file_stream,
+ self.silent,
+ event.save_name,
+ event.path,
+ event.artifact_id,
+ event.md5,
+ event.copied,
+ event.save_fn,
+ event.digest,
+ )
+ job.run()
+
+ def _init_artifact(self, artifact_id: str) -> None:
+ self._artifacts[artifact_id] = {
+ "finalize": False,
+ "pending_count": 0,
+ "commit_requested": False,
+ "pre_commit_callbacks": set(),
+ "result_futures": set(),
+ }
+
+ def _maybe_commit_artifact(self, artifact_id: str) -> None:
+ artifact_status = self._artifacts[artifact_id]
+ if (
+ artifact_status["pending_count"] == 0
+ and artifact_status["commit_requested"]
+ ):
+ try:
+ for pre_callback in artifact_status["pre_commit_callbacks"]:
+ pre_callback()
+ if artifact_status["finalize"]:
+ self._api.commit_artifact(artifact_id)
+ except Exception as exc:
+ termerror(
+ f"Committing artifact failed. Artifact {artifact_id} won't be finalized."
+ )
+ termerror(str(exc))
+ self._fail_artifact_futures(artifact_id, exc)
+ else:
+ self._resolve_artifact_futures(artifact_id)
+
+ def _fail_artifact_futures(self, artifact_id: str, exc: BaseException) -> None:
+ futures = self._artifacts[artifact_id]["result_futures"]
+ for result_future in futures:
+ result_future.set_exception(exc)
+ futures.clear()
+
+ def _resolve_artifact_futures(self, artifact_id: str) -> None:
+ futures = self._artifacts[artifact_id]["result_futures"]
+ for result_future in futures:
+ result_future.set_result(None)
+ futures.clear()
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def is_alive(self) -> bool:
+ return self._thread.is_alive()
diff --git a/venv/lib/python3.10/site-packages/wandb/filesync/upload_job.py b/venv/lib/python3.10/site-packages/wandb/filesync/upload_job.py
new file mode 100644
index 0000000000000000000000000000000000000000..3db449571b3f3e06310e76cb267d0dc042557915
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/filesync/upload_job.py
@@ -0,0 +1,142 @@
+import logging
+import os
+from typing import TYPE_CHECKING, Optional
+
+import wandb
+from wandb.sdk.lib.paths import LogicalPath
+
+if TYPE_CHECKING:
+ from wandb.filesync import dir_watcher, stats, step_upload
+ from wandb.sdk.internal import file_stream, internal_api
+
+
+logger = logging.getLogger(__name__)
+
+
+class UploadJob:
+ def __init__(
+ self,
+ stats: "stats.Stats",
+ api: "internal_api.Api",
+ file_stream: "file_stream.FileStreamApi",
+ silent: bool,
+ save_name: LogicalPath,
+ path: "dir_watcher.PathStr",
+ artifact_id: Optional[str],
+ md5: Optional[str],
+ copied: bool,
+ save_fn: Optional["step_upload.SaveFn"],
+ digest: Optional[str],
+ ) -> None:
+ """A file uploader.
+
+ Args:
+ push_function: function(save_name, actual_path) which actually uploads
+ the file.
+ save_name: string logical location of the file relative to the run
+ directory.
+ path: actual string path of the file to upload on the filesystem.
+ """
+ self._stats = stats
+ self._api = api
+ self._file_stream = file_stream
+ self.silent = silent
+ self.save_name = save_name
+ self.save_path = path
+ self.artifact_id = artifact_id
+ self.md5 = md5
+ self.copied = copied
+ self.save_fn = save_fn
+ self.digest = digest
+ super().__init__()
+
+ def run(self) -> None:
+ success = False
+ try:
+ self.push()
+ success = True
+ finally:
+ if self.copied and os.path.isfile(self.save_path):
+ os.remove(self.save_path)
+ if success:
+ self._file_stream.push_success(self.artifact_id, self.save_name) # type: ignore
+
+ def push(self) -> None:
+ if self.save_fn:
+ # Retry logic must happen in save_fn currently
+ try:
+ deduped = self.save_fn(
+ lambda _, t: self._stats.update_uploaded_file(self.save_path, t)
+ )
+ except Exception as e:
+ self._stats.update_failed_file(self.save_path)
+ logger.exception("Failed to upload file: %s", self.save_path)
+ wandb._sentry.exception(e)
+ message = str(e)
+ # TODO: this is usually XML, but could be JSON
+ if hasattr(e, "response"):
+ message = e.response.content
+ wandb.termerror(
+ f'Error uploading "{self.save_path}": {type(e).__name__}, {message}'
+ )
+ raise
+
+ if deduped:
+ logger.info("Skipped uploading %s", self.save_path)
+ self._stats.set_file_deduped(self.save_path)
+ else:
+ logger.info("Uploaded file %s", self.save_path)
+ return
+
+ if self.md5:
+ # This is the new artifact manifest upload flow, in which we create the
+ # database entry for the manifest file before creating it. This is used for
+ # artifact L0 files. Which now is only artifact_manifest.json
+ _, response = self._api.create_artifact_manifest(
+ self.save_name, self.md5, self.artifact_id
+ )
+ upload_url = response["uploadUrl"]
+ upload_headers = response["uploadHeaders"]
+ else:
+ # The classic file upload flow. We get a signed url and upload the file
+ # then the backend handles the cloud storage metadata callback to create the
+ # file entry. This flow has aged like a fine wine.
+ project = self._api.get_project()
+ _, upload_headers, result = self._api.upload_urls(project, [self.save_name])
+ file_info = result[self.save_name]
+ upload_url = file_info["uploadUrl"]
+
+ if upload_url is None:
+ logger.info("Skipped uploading %s", self.save_path)
+ self._stats.set_file_deduped(self.save_name)
+ else:
+ extra_headers = self._api._extra_http_headers
+ for upload_header in upload_headers:
+ key, val = upload_header.split(":", 1)
+ extra_headers[key] = val
+ # Copied from push TODO(artifacts): clean up
+ # If the upload URL is relative, fill it in with the base URL,
+ # since its a proxied file store like the on-prem VM.
+ if upload_url.startswith("/"):
+ upload_url = f"{self._api.api_url}{upload_url}"
+ try:
+ with open(self.save_path, "rb") as f:
+ self._api.upload_file_retry(
+ upload_url,
+ f,
+ lambda _, t: self.progress(t),
+ extra_headers=extra_headers,
+ )
+ logger.info("Uploaded file %s", self.save_path)
+ except Exception as e:
+ self._stats.update_failed_file(self.save_name)
+ logger.exception("Failed to upload file: %s", self.save_path)
+ wandb._sentry.exception(e)
+ if not self.silent:
+ wandb.termerror(
+ f'Error uploading "{self.save_name}": {type(e).__name__}, {e}'
+ )
+ raise
+
+ def progress(self, total_bytes: int) -> None:
+ self._stats.update_uploaded_file(self.save_name, total_bytes)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28ba82f6447c237870a5aa73f0c6be1fdf580ba6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/catboost/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccd732b7e26cead03e12f0d6ab00f6d3165c2ba4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__init__.py
@@ -0,0 +1,5 @@
+"""W&B callback for CatBoost."""
+
+from .catboost import WandbCallback, log_summary
+
+__all__ = ["log_summary", "WandbCallback"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4412d8debb88e9b3ba7e1dfbfa98fa6a0f4e1147
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/catboost.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/catboost.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e555c73036e11234b4144cddfe40127da4f0581
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/catboost/__pycache__/catboost.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/catboost/catboost.py b/venv/lib/python3.10/site-packages/wandb/integration/catboost/catboost.py
new file mode 100644
index 0000000000000000000000000000000000000000..09dc31b84ffaec7826d70536eb59ef56452a9062
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/catboost/catboost.py
@@ -0,0 +1,182 @@
+"""catboost init."""
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import List, Union
+
+from catboost import CatBoostClassifier, CatBoostRegressor # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+
+class WandbCallback:
+ """`WandbCallback` automatically integrates CatBoost with wandb.
+
+ Args:
+ - metric_period: (int) if you are passing `metric_period` to your CatBoost model please pass the same value here (default=1).
+
+ Passing `WandbCallback` to CatBoost will:
+ - log training and validation metrics at every `metric_period`
+ - log iteration at every `metric_period`
+
+ Example:
+ ```
+ train_pool = Pool(
+ train[features], label=train["label"], cat_features=cat_features
+ )
+ test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)
+
+ model = CatBoostRegressor(
+ iterations=100,
+ loss_function="Cox",
+ eval_metric="Cox",
+ )
+
+ model.fit(
+ train_pool,
+ eval_set=test_pool,
+ callbacks=[WandbCallback()],
+ )
+ ```
+ """
+
+ def __init__(self, metric_period: int = 1):
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before `WandbCallback()`")
+
+ with wb_telemetry.context() as tel:
+ tel.feature.catboost_wandb_callback = True
+
+ self.metric_period: int = metric_period
+
+ def after_iteration(self, info: SimpleNamespace) -> bool:
+ if info.iteration % self.metric_period == 0:
+ for data, metric in info.metrics.items():
+ for metric_name, log in metric.items():
+ # todo: replace with wandb.run._log once available
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+ # todo: replace with wandb.run._log once available
+ wandb.log({f"iteration@metric-period-{self.metric_period}": info.iteration})
+
+ return True
+
+
+def _checkpoint_artifact(
+ model: Union[CatBoostClassifier, CatBoostRegressor], aliases: List[str]
+) -> None:
+ """Upload model checkpoint as W&B artifact."""
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `_checkpoint_artifact()`"
+ )
+
+ model_name = f"model_{wandb.run.id}"
+ # save the model in the default `cbm` format
+ model_path = Path(wandb.run.dir) / "model"
+
+ model.save_model(model_path)
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact, aliases=aliases)
+
+
+def _log_feature_importance(
+ model: Union[CatBoostClassifier, CatBoostRegressor],
+) -> None:
+ """Log feature importance with default settings."""
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `_checkpoint_artifact()`"
+ )
+
+ feat_df = model.get_feature_importance(prettified=True)
+
+ fi_data = [
+ [feat, feat_imp]
+ for feat, feat_imp in zip(feat_df["Feature Id"], feat_df["Importances"])
+ ]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ # todo: replace with wandb.run._log once available
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ },
+ commit=False,
+ )
+
+
+def log_summary(
+ model: Union[CatBoostClassifier, CatBoostRegressor],
+ log_all_params: bool = True,
+ save_model_checkpoint: bool = False,
+ log_feature_importance: bool = True,
+) -> None:
+ """`log_summary` logs useful metrics about catboost model after training is done.
+
+ Args:
+ model: it can be CatBoostClassifier or CatBoostRegressor.
+ log_all_params: (boolean) if True (default) log the model hyperparameters as W&B config.
+ save_model_checkpoint: (boolean) if True saves the model upload as W&B artifacts.
+ log_feature_importance: (boolean) if True (default) logs feature importance as W&B bar chart using the default setting of `get_feature_importance`.
+
+ Using this along with `wandb_callback` will:
+
+ - save the hyperparameters as W&B config,
+ - log `best_iteration` and `best_score` as `wandb.summary`,
+ - save and upload your trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
+ - log feature importance plot.
+
+ Example:
+ ```python
+ train_pool = Pool(
+ train[features], label=train["label"], cat_features=cat_features
+ )
+ test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)
+
+ model = CatBoostRegressor(
+ iterations=100,
+ loss_function="Cox",
+ eval_metric="Cox",
+ )
+
+ model.fit(
+ train_pool,
+ eval_set=test_pool,
+ callbacks=[WandbCallback()],
+ )
+
+ log_summary(model)
+ ```
+ """
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before `log_summary()`")
+
+ if not (isinstance(model, (CatBoostClassifier, CatBoostRegressor))):
+ raise wandb.Error(
+ "Model should be an instance of CatBoostClassifier or CatBoostRegressor"
+ )
+
+ with wb_telemetry.context() as tel:
+ tel.feature.catboost_log_summary = True
+
+ # log configs
+ params = model.get_all_params()
+ if log_all_params:
+ wandb.config.update(params)
+
+ # log best score and iteration
+ wandb.run.summary["best_iteration"] = model.get_best_iteration()
+ wandb.run.summary["best_score"] = model.get_best_score()
+
+ # log model
+ if save_model_checkpoint:
+ aliases = ["best"] if params["use_best_model"] else ["last"]
+ _checkpoint_artifact(model, aliases=aliases)
+
+ # Feature importance
+ if log_feature_importance:
+ _log_feature_importance(model)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d367dc6988bda4251745dc6b3610a3e92b4c85e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog",)
+
+from .cohere import autolog
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05b1dbac6ced47bf60ad5f8c0dd7221464bc156e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc1fe872fd28af7ea38d7db4cb5ecdabbf041c9b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/resolver.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/resolver.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..699aef8cf2e404d4576f7075565dbc01e1abf74e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/cohere/__pycache__/resolver.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/cohere.py b/venv/lib/python3.10/site-packages/wandb/integration/cohere/cohere.py
new file mode 100644
index 0000000000000000000000000000000000000000..91f9a43e23150a6882dbb87512e6fbe657a7b8d4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/cohere/cohere.py
@@ -0,0 +1,21 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import CohereRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+
+autolog = AutologAPI(
+ name="Cohere",
+ symbols=(
+ "Client.generate",
+ "Client.chat",
+ "Client.classify",
+ "Client.summarize",
+ "Client.rerank",
+ ),
+ resolver=CohereRequestResponseResolver(),
+ telemetry_feature="cohere_autolog",
+)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py b/venv/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cfcdf020b87c8a5a3c15f164226ac50f8670d4d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/cohere/resolver.py
@@ -0,0 +1,347 @@
+import logging
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+from wandb.sdk.lib.runid import generate_id
+
+logger = logging.getLogger(__name__)
+
+
+def subset_dict(
+ original_dict: Dict[str, Any], keys_subset: Sequence[str]
+) -> Dict[str, Any]:
+ """Create a subset of a dictionary using a subset of keys.
+
+ :param original_dict: The original dictionary.
+ :param keys_subset: The subset of keys to extract.
+ :return: A dictionary containing only the specified keys.
+ """
+ return {key: original_dict[key] for key in keys_subset if key in original_dict}
+
+
+def reorder_and_convert_dict_list_to_table(
+ data: List[Dict[str, Any]], order: List[str]
+) -> Tuple[List[str], List[List[Any]]]:
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
+
+ :param data: A list of dictionaries.
+ :param order: A list of keys specifying the desired order for specific dictionaries. The remaining dictionaries will be ordered based on their original order.
+ :return: A pair of column names and corresponding values.
+ """
+ final_columns = []
+ keys_present = set()
+
+ # First, add all ordered keys to the final columns
+ for key in order:
+ if key not in keys_present:
+ final_columns.append(key)
+ keys_present.add(key)
+
+ # Then, add any keys present in the dictionaries but not in the order
+ for d in data:
+ for key in d:
+ if key not in keys_present:
+ final_columns.append(key)
+ keys_present.add(key)
+
+ # Then, construct the table of values
+ values = []
+ for d in data:
+ row = []
+ for key in final_columns:
+ row.append(d.get(key, None))
+ values.append(row)
+
+ return final_columns, values
+
+
+def flatten_dict(
+ dictionary: Dict[str, Any], parent_key: str = "", sep: str = "-"
+) -> Dict[str, Any]:
+ """Flatten a nested dictionary, joining keys using a specified separator.
+
+ :param dictionary: The dictionary to flatten.
+ :param parent_key: The base key to prepend to each key.
+ :param sep: The separator to use when joining keys.
+ :return: A flattened dictionary.
+ """
+ flattened_dict = {}
+ for key, value in dictionary.items():
+ new_key = f"{parent_key}{sep}{key}" if parent_key else key
+ if isinstance(value, dict):
+ flattened_dict.update(flatten_dict(value, new_key, sep=sep))
+ else:
+ flattened_dict[new_key] = value
+ return flattened_dict
+
+
+def collect_common_keys(list_of_dicts: List[Dict[str, Any]]) -> Dict[str, List[Any]]:
+ """Collect the common keys of a list of dictionaries. For each common key, put its values into a list in the order they appear in the original dictionaries.
+
+ :param list_of_dicts: The list of dictionaries to inspect.
+ :return: A dictionary with each common key and its corresponding list of values.
+ """
+ common_keys = set.intersection(*map(set, list_of_dicts))
+ common_dict = {key: [] for key in common_keys}
+ for d in list_of_dicts:
+ for key in common_keys:
+ common_dict[key].append(d[key])
+ return common_dict
+
+
+class CohereRequestResponseResolver:
+ """Class to resolve the request/response from the Cohere API and convert it to a dictionary that can be logged."""
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ """Process the response from the Cohere API and convert it to a dictionary that can be logged.
+
+ :param args: The arguments of the original function.
+ :param kwargs: The keyword arguments of the original function.
+ :param response: The response from the Cohere API.
+ :param start_time: The start time of the request.
+ :param time_elapsed: The time elapsed for the request.
+ :return: A dictionary containing the parsed response and timing information.
+ """
+ try:
+ # Each of the different endpoints map to one specific response type
+ # We want to 'type check' the response without directly importing the packages type
+ # It may make more sense to pass the invoked symbol from the AutologAPI instead
+ response_type = str(type(response)).split("'")[1].split(".")[-1]
+
+ # Initialize parsed_response to None to handle the case where the response type is unsupported
+ parsed_response = None
+ if response_type == "Generations":
+ parsed_response = self._resolve_generate_response(response)
+ # TODO: Remove hard-coded default model name
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "prompt",
+ "text",
+ "token_likelihoods",
+ "likelihood",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "command"
+ elif response_type == "Chat":
+ parsed_response = self._resolve_chat_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "conversation_id",
+ "response_id",
+ "query",
+ "text",
+ "prompt",
+ "preamble",
+ "chat_history",
+ "chatlog",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "command"
+ elif response_type == "Classifications":
+ parsed_response = self._resolve_classify_response(response)
+ kwargs = self._resolve_classify_kwargs(kwargs)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "id",
+ "input",
+ "prediction",
+ "confidence",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "embed-english-v2.0"
+ elif response_type == "SummarizeResponse":
+ parsed_response = self._resolve_summarize_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "response_id",
+ "text",
+ "additional_command",
+ "summary",
+ "time_elapsed_(seconds)",
+ "end_time",
+ "length",
+ "format",
+ ]
+ default_model = "summarize-xlarge"
+ elif response_type == "Reranking":
+ parsed_response = self._resolve_rerank_response(response)
+ table_column_order = [
+ "start_time",
+ "query_id",
+ "model",
+ "id",
+ "query",
+ "top_n",
+ # This is a nested dict key that got flattened
+ "document-text",
+ "relevance_score",
+ "index",
+ "time_elapsed_(seconds)",
+ "end_time",
+ ]
+ default_model = "rerank-english-v2.0"
+ else:
+ logger.info(f"Unsupported Cohere response object: {response}")
+
+ return self._resolve(
+ args,
+ kwargs,
+ parsed_response,
+ start_time,
+ time_elapsed,
+ response_type,
+ table_column_order,
+ default_model,
+ )
+ except Exception as e:
+ logger.warning(f"Failed to resolve request/response: {e}")
+ return None
+
+ # These helper functions process the response from different endpoints of the Cohere API.
+ # Since the response objects for different endpoints have different structures,
+ # we need different logic to process them.
+
+ def _resolve_generate_response(self, response: Response) -> List[Dict[str, Any]]:
+ return_list = []
+ for _response in response:
+ # Built in Cohere.*.Generations function to color token_likelihoods and return a dict of response data
+ _response_dict = _response._visualize_helper()
+ try:
+ _response_dict["token_likelihoods"] = wandb.Html(
+ _response_dict["token_likelihoods"]
+ )
+ except (KeyError, ValueError):
+ pass
+ return_list.append(_response_dict)
+
+ return return_list
+
+ def _resolve_chat_response(self, response: Response) -> List[Dict[str, Any]]:
+ return [
+ subset_dict(
+ response.__dict__,
+ [
+ "response_id",
+ "generation_id",
+ "query",
+ "text",
+ "conversation_id",
+ "prompt",
+ "chatlog",
+ "preamble",
+ ],
+ )
+ ]
+
+ def _resolve_classify_response(self, response: Response) -> List[Dict[str, Any]]:
+ # The labels key is a dict returning the scores for the classification probability for each label provided
+ # We flatten this nested dict for ease of consumption in the wandb UI
+ return [flatten_dict(_response.__dict__) for _response in response]
+
+ def _resolve_classify_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
+ # Example texts look strange when rendered in Wandb UI as it is a list of text and label
+ # We extract each value into its own column
+ example_texts = []
+ example_labels = []
+ for example in kwargs["examples"]:
+ example_texts.append(example.text)
+ example_labels.append(example.label)
+ kwargs.pop("examples")
+ kwargs["example_texts"] = example_texts
+ kwargs["example_labels"] = example_labels
+ return kwargs
+
+ def _resolve_summarize_response(self, response: Response) -> List[Dict[str, Any]]:
+ return [{"response_id": response.id, "summary": response.summary}]
+
+ def _resolve_rerank_response(self, response: Response) -> List[Dict[str, Any]]:
+ # The documents key contains a dict containing the content of the document which is at least "text"
+ # We flatten this nested dict for ease of consumption in the wandb UI
+ flattened_response_dicts = [
+ flatten_dict(_response.__dict__) for _response in response
+ ]
+ # ReRank returns each document provided a top_n value so we aggregate into one view so users can paginate a row
+ # As opposed to each row being one of the top_n responses
+ return_dict = collect_common_keys(flattened_response_dicts)
+ return_dict["id"] = response.id
+ return [return_dict]
+
+ def _resolve(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ parsed_response: List[Dict[str, Any]],
+ start_time: float,
+ time_elapsed: float,
+ response_type: str,
+ table_column_order: List[str],
+ default_model: str,
+ ) -> Dict[str, Any]:
+ """Convert a list of dictionaries to a pair of column names and corresponding values, with the option to order specific dictionaries.
+
+ :param args: The arguments passed to the API client.
+ :param kwargs: The keyword arguments passed to the API client.
+ :param parsed_response: The parsed response from the API.
+ :param start_time: The start time of the API request.
+ :param time_elapsed: The time elapsed during the API request.
+ :param response_type: The type of the API response.
+ :param table_column_order: The desired order of columns in the resulting table.
+ :param default_model: The default model to use if not specified in the response.
+ :return: A dictionary containing the formatted response.
+ """
+ # Args[0] is the client object where we can grab specific metadata about the underlying API status
+ query_id = generate_id(length=16)
+ parsed_args = subset_dict(
+ args[0].__dict__,
+ ["api_version", "batch_size", "max_retries", "num_workers", "timeout"],
+ )
+
+ start_time_dt = datetime.fromtimestamp(start_time)
+ end_time_dt = datetime.fromtimestamp(start_time + time_elapsed)
+
+ timings = {
+ "start_time": start_time_dt,
+ "end_time": end_time_dt,
+ "time_elapsed_(seconds)": time_elapsed,
+ }
+
+ packed_data = []
+ for _parsed_response in parsed_response:
+ _packed_dict = {
+ "query_id": query_id,
+ **kwargs,
+ **_parsed_response,
+ **timings,
+ **parsed_args,
+ }
+ if "model" not in _packed_dict:
+ _packed_dict["model"] = default_model
+ packed_data.append(_packed_dict)
+
+ columns, data = reorder_and_convert_dict_list_to_table(
+ packed_data, table_column_order
+ )
+
+ request_response_table = wandb.Table(data=data, columns=columns)
+
+ return {f"{response_type}": request_response_table}
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bcf7980133c41393fdc22db3bbff89be29be94e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__init__.py
@@ -0,0 +1,3 @@
+from .autologger import autolog
+
+__all__ = ["autolog"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ae22a1b5e9a9f0d618194ff858ffa315ee86678
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/autologger.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/autologger.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c253f93f97c69e0aa543d206d31c4b6a8ac16c1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/autologger.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/pipeline_resolver.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/pipeline_resolver.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d4a5debe6c5fcf57a5ffa9524904153e1dc684c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/__pycache__/pipeline_resolver.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/autologger.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/autologger.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad21a77edc6a1125f8d2f5621c046c6bbe1f0b9b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/autologger.py
@@ -0,0 +1,76 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .pipeline_resolver import DiffusersPipelineResolver
+
+logger = logging.getLogger(__name__)
+
+autolog = AutologAPI(
+ name="diffusers",
+ symbols=(
+ "DiffusionPipeline.__call__",
+ "AutoPipelineForText2Image.__call__",
+ "AutoPipelineForImage2Image.__call__",
+ "AutoPipelineForInpainting.__call__",
+ "StableDiffusionPipeline.__call__",
+ "KandinskyCombinedPipeline.__call__",
+ "KandinskyV22CombinedPipeline.__call__",
+ "LatentConsistencyModelPipeline.__call__",
+ "LDMTextToImagePipeline.__call__",
+ "StableDiffusionPanoramaPipeline.__call__",
+ "StableDiffusionParadigmsPipeline.__call__",
+ "PixArtAlphaPipeline.__call__",
+ "StableDiffusionSAGPipeline.__call__",
+ "SemanticStableDiffusionPipeline.__call__",
+ "WuerstchenCombinedPipeline.__call__",
+ "AltDiffusionPipeline.__call__",
+ "StableDiffusionAttendAndExcitePipeline.__call__",
+ "StableDiffusionXLPipeline.__call__",
+ "StableDiffusionXLImg2ImgPipeline.__call__",
+ "IFPipeline.__call__",
+ "BlipDiffusionPipeline.__call__",
+ "BlipDiffusionControlNetPipeline.__call__",
+ "StableDiffusionControlNetPipeline.__call__",
+ "StableDiffusionControlNetImg2ImgPipeline.__call__",
+ "StableDiffusionControlNetInpaintPipeline.__call__",
+ "CycleDiffusionPipeline.__call__",
+ "StableDiffusionInstructPix2PixPipeline.__call__",
+ "PaintByExamplePipeline.__call__",
+ "RePaintPipeline.__call__",
+ "KandinskyImg2ImgCombinedPipeline.__call__",
+ "KandinskyInpaintCombinedPipeline.__call__",
+ "KandinskyV22Img2ImgCombinedPipeline.__call__",
+ "KandinskyV22InpaintCombinedPipeline.__call__",
+ "Kandinsky3Pipeline.__call__",
+ "Kandinsky3Img2ImgPipeline.__call__",
+ "AnimateDiffPipeline.__call__",
+ "AudioLDMPipeline.__call__",
+ "AudioLDM2Pipeline.__call__",
+ "MusicLDMPipeline.__call__",
+ "StableDiffusionPix2PixZeroPipeline.__call__",
+ "PNDMPipeline.__call__",
+ "ShapEPipeline.__call__",
+ "StableDiffusionImg2ImgPipeline.__call__",
+ "StableDiffusionInpaintPipeline.__call__",
+ "StableDiffusionDepth2ImgPipeline.__call__",
+ "StableDiffusionImageVariationPipeline.__call__",
+ "StableDiffusionPipelineSafe.__call__",
+ "StableDiffusionUpscalePipeline.__call__",
+ "StableDiffusionAdapterPipeline.__call__",
+ "StableDiffusionGLIGENPipeline.__call__",
+ "StableDiffusionModelEditingPipeline.__call__",
+ "VersatileDiffusionTextToImagePipeline.__call__",
+ "VersatileDiffusionImageVariationPipeline.__call__",
+ "VersatileDiffusionDualGuidedPipeline.__call__",
+ "LDMPipeline.__call__",
+ "TextToVideoSDPipeline.__call__",
+ "TextToVideoZeroPipeline.__call__",
+ "StableVideoDiffusionPipeline.__call__",
+ "AmusedPipeline.__call__",
+ "StableDiffusionXLControlNetPipeline.__call__",
+ "StableDiffusionXLControlNetImg2ImgPipeline.__call__",
+ ),
+ resolver=DiffusersPipelineResolver(),
+ telemetry_feature="diffusers_autolog",
+)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5c4d73511c20f53e75f4b1cbf5a6cfc444c8875
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/pipeline_resolver.py
@@ -0,0 +1,50 @@
+from typing import Any, Dict, Sequence
+
+from wandb.sdk.integration_utils.auto_logging import Response
+
+from .resolvers import (
+ SUPPORTED_MULTIMODAL_PIPELINES,
+ DiffusersMultiModalPipelineResolver,
+)
+
+
+class DiffusersPipelineResolver:
+ """Resolver for `DiffusionPipeline` request and responses from [HuggingFace Diffusers](https://huggingface.co/docs/diffusers/index), providing necessary data transformations, formatting, and logging.
+
+ This is based off `wandb.sdk.integration_utils.auto_logging.RequestResponseResolver`.
+ """
+
+ def __init__(self) -> None:
+ self.wandb_table = None
+ self.pipeline_call_count = 1
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Any:
+ """Main call method for the `DiffusersPipelineResolver` class.
+
+ Args:
+ args: (Sequence[Any]) List of arguments.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ start_time: (float) Time when request started.
+ time_elapsed: (float) Time elapsed for the request.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ pipeline_name = args[0].__class__.__name__
+ resolver = None
+ if pipeline_name in SUPPORTED_MULTIMODAL_PIPELINES:
+ resolver = DiffusersMultiModalPipelineResolver(
+ pipeline_name, self.pipeline_call_count
+ )
+ self.pipeline_call_count += 1
+ loggable_dict = resolver(args, kwargs, response, start_time, time_elapsed)
+ return loggable_dict
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6211bd4bc2b9901593e477c1b5713bc074f8804
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__init__.py
@@ -0,0 +1,9 @@
+from .multimodal import (
+ SUPPORTED_MULTIMODAL_PIPELINES,
+ DiffusersMultiModalPipelineResolver,
+)
+
+__all__ = [
+ "SUPPORTED_MULTIMODAL_PIPELINES",
+ "DiffusersMultiModalPipelineResolver",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5b048af45ec183c3559bfdaad24473e3d539316
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2aefdb6fbfb59803b12fd916ceeedb4572cb0d41
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76d989811a4347fd6ab8120f52864a12c2dd9f08
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py
new file mode 100644
index 0000000000000000000000000000000000000000..34ef33e8639193b8f87a65434e6261ff112fbd7a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/multimodal.py
@@ -0,0 +1,881 @@
+import logging
+from typing import Any, Dict, List, Sequence
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+
+from .utils import (
+ chunkify,
+ decode_sdxl_t2i_latents,
+ get_updated_kwargs,
+ postprocess_np_arrays_for_video,
+ postprocess_pils_to_np,
+)
+
+logger = logging.getLogger(__name__)
+
+
+SUPPORTED_MULTIMODAL_PIPELINES = {
+ "BlipDiffusionPipeline": {
+ "table-schema": [
+ "Reference-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Source-Subject-Category",
+ "Target-Subject-Category",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "reference_image",
+ "prompt",
+ "neg_prompt",
+ "source_subject_category",
+ "target_subject_category",
+ ],
+ "kwarg-actions": [wandb.Image, None, None, None, None],
+ },
+ "BlipDiffusionControlNetPipeline": {
+ "table-schema": [
+ "Reference-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Source-Subject-Category",
+ "Target-Subject-Category",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "reference_image",
+ "condtioning_image",
+ "prompt",
+ "neg_prompt",
+ "source_subject_category",
+ "target_subject_category",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None, None, None],
+ },
+ "StableDiffusionControlNetPipeline": {
+ "table-schema": [
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionControlNetImg2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "control_image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None],
+ },
+ "StableDiffusionControlNetInpaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Image",
+ "Control-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "mask_image",
+ "control_image",
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image, None, None],
+ },
+ "CycleDiffusionPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Source-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "prompt",
+ "source_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionInstructPix2PixPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "PaintByExamplePipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Example-Image",
+ "Mask-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "example_image",
+ "mask_image",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image],
+ },
+ "RePaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ "mask_image",
+ ],
+ "kwarg-actions": [wandb.Image, wandb.Image],
+ },
+ "StableDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyCombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyV22CombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "LatentConsistencyModelPipeline": {
+ "table-schema": ["Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ },
+ "LDMTextToImagePipeline": {
+ "table-schema": ["Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ },
+ "StableDiffusionPanoramaPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "PixArtAlphaPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionSAGPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "SemanticStableDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "WuerstchenCombinedPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "IFPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "AltDiffusionPipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionAttendAndExcitePipeline": {
+ "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "KandinskyImg2ImgCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyInpaintCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyV22Img2ImgCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "KandinskyV22InpaintCombinedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "AnimateDiffPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "num_frames"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "video",
+ },
+ "StableVideoDiffusionPipeline": {
+ "table-schema": [
+ "Input-Image",
+ "Frames-Per-Second",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["image", "fps"],
+ "kwarg-actions": [wandb.Image, None],
+ "output-type": "video",
+ },
+ "AudioLDMPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "AudioLDM2Pipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "MusicLDMPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Audio-Length-in-Seconds",
+ "Generated-Audio",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"],
+ "kwarg-actions": [None, None, None],
+ "output-type": "audio",
+ },
+ "StableDiffusionPix2PixZeroPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "PNDMPipeline": {
+ "table-schema": [
+ "Batch-Size",
+ "Number-of-Inference-Steps",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["batch_size", "num_inference_steps"],
+ "kwarg-actions": [None, None],
+ },
+ "ShapEPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt"],
+ "kwarg-actions": [None],
+ "output-type": "video",
+ },
+ "StableDiffusionImg2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionInpaintPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Mask-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "mask_image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, wandb.Image, None, None],
+ },
+ "StableDiffusionDepth2ImgPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionImageVariationPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "image",
+ ],
+ "kwarg-actions": [wandb.Image],
+ },
+ "StableDiffusionPipelineSafe": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionUpscalePipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Upscaled-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionAdapterPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "StableDiffusionGLIGENPipeline": {
+ "table-schema": [
+ "Prompt",
+ "GLIGEN-Phrases",
+ "GLIGEN-Boxes",
+ "GLIGEN-Inpaint-Image",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "gligen_phrases",
+ "gligen_boxes",
+ "gligen_inpaint_image",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [None, None, None, wandb.Image, None],
+ },
+ "VersatileDiffusionTextToImagePipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt"],
+ "kwarg-actions": [None, None],
+ },
+ "VersatileDiffusionImageVariationPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None],
+ },
+ "VersatileDiffusionDualGuidedPipeline": {
+ "table-schema": [
+ "Source-Image",
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["image", "prompt", "negative_prompt"],
+ "kwarg-actions": [wandb.Image, None, None],
+ },
+ "LDMPipeline": {
+ "table-schema": [
+ "Batch-Size",
+ "Number-of-Inference-Steps",
+ "Generated-Image",
+ ],
+ "kwarg-logging": ["batch_size", "num_inference_steps"],
+ "kwarg-actions": [None, None],
+ },
+ "TextToVideoSDPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "num_frames"],
+ "output-type": "video",
+ },
+ "TextToVideoZeroPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Number-of-Frames",
+ "Generated-Video",
+ ],
+ "kwarg-logging": ["prompt", "negative_prompt", "video_length"],
+ },
+ "AmusedPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Guidance Scale",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "guidance_scale",
+ ],
+ "kwarg-actions": [None, None],
+ },
+ "StableDiffusionXLControlNetPipeline": {
+ "table-schema": [
+ "Prompt-1",
+ "Prompt-2",
+ "Control-Image",
+ "Negative-Prompt-1",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "prompt_2",
+ "image",
+ "negative_prompt",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, wandb.Image, None, None],
+ },
+ "StableDiffusionXLControlNetImg2ImgPipeline": {
+ "table-schema": [
+ "Prompt-1",
+ "Prompt-2",
+ "Input-Image",
+ "Control-Image",
+ "Negative-Prompt-1",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "prompt_2",
+ "image",
+ "control_image",
+ "negative_prompt",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, wandb.Image, wandb.Image, None, None],
+ },
+ "Kandinsky3Pipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ ],
+ "kwarg-actions": [None, None],
+ },
+ "Kandinsky3Img2ImgPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Input-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "image",
+ ],
+ "kwarg-actions": [None, None, wandb.Image],
+ },
+ "StableDiffusionXLPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Prompt-2",
+ "Negative-Prompt-2",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "prompt_2",
+ "negative_prompt_2",
+ ],
+ "kwarg-actions": [None, None, None, None],
+ },
+ "StableDiffusionXLImg2ImgPipeline": {
+ "table-schema": [
+ "Prompt",
+ "Negative-Prompt",
+ "Prompt-2",
+ "Negative-Prompt-2",
+ "Input-Image",
+ "Generated-Image",
+ ],
+ "kwarg-logging": [
+ "prompt",
+ "negative_prompt",
+ "prompt_2",
+ "negative_prompt_2",
+ "image",
+ ],
+ "kwarg-actions": [None, None, None, None, wandb.Image],
+ },
+}
+
+
+class DiffusersMultiModalPipelineResolver:
+ """Resolver for request and responses from [HuggingFace Diffusers](https://huggingface.co/docs/diffusers/index) multi-modal Diffusion Pipelines, providing necessary data transformations, formatting, and logging.
+
+ This resolver is internally involved in the
+ `__call__` for `wandb.integration.diffusers.pipeline_resolver.DiffusersPipelineResolver`.
+ This is based on `wandb.sdk.integration_utils.auto_logging.RequestResponseResolver`.
+
+ Args:
+ pipeline_name: (str) The name of the Diffusion Pipeline.
+ """
+
+ def __init__(self, pipeline_name: str, pipeline_call_count: int) -> None:
+ self.pipeline_name = pipeline_name
+ self.pipeline_call_count = pipeline_call_count
+ columns = []
+ if pipeline_name in SUPPORTED_MULTIMODAL_PIPELINES:
+ columns += SUPPORTED_MULTIMODAL_PIPELINES[pipeline_name]["table-schema"]
+ else:
+ wandb.Error("Pipeline not supported for logging")
+ self.wandb_table = wandb.Table(columns=columns)
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Any:
+ """Main call method for the `DiffusersPipelineResolver` class.
+
+ Args:
+ args: (Sequence[Any]) List of arguments.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ start_time: (float) Time when request started.
+ time_elapsed: (float) Time elapsed for the request.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ try:
+ # Get the pipeline and the args
+ pipeline, args = args[0], args[1:]
+
+ # Update the Kwargs so that they can be logged easily
+ kwargs = get_updated_kwargs(pipeline, args, kwargs)
+
+ # Get the pipeline configs
+ pipeline_configs = dict(pipeline.config)
+ pipeline_configs["pipeline-name"] = self.pipeline_name
+
+ if "workflow" not in wandb.config:
+ wandb.config.update(
+ {
+ "workflow": [
+ {
+ "pipeline": pipeline_configs,
+ "params": kwargs,
+ "stage": f"Pipeline-Call-{self.pipeline_call_count}",
+ }
+ ]
+ }
+ )
+ else:
+ existing_workflow = wandb.config.workflow
+ updated_workflow = existing_workflow + [
+ {
+ "pipeline": pipeline_configs,
+ "params": kwargs,
+ "stage": f"Pipeline-Call-{self.pipeline_call_count}",
+ }
+ ]
+ wandb.config.update(
+ {"workflow": updated_workflow}, allow_val_change=True
+ )
+
+ # Return the WandB loggable dict
+ return self.prepare_loggable_dict(pipeline, response, kwargs)
+ except Exception as e:
+ logger.warning(e)
+ return None
+
+ def get_output_images(self, response: Response) -> List:
+ """Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response.
+
+ Args:
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+
+ Returns:
+ List of generated images, audio, video, etc.
+ """
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ return response.images
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ if self.pipeline_name in ["ShapEPipeline"]:
+ return response.images
+ return response.frames
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ return response.audios
+
+ def log_media(self, image: Any, loggable_kwarg_chunks: List, idx: int) -> None:
+ """Log the generated images, audio, video, etc. from the Diffusion Pipeline's response along with an optional caption to a media panel in the run.
+
+ Args:
+ image: (Any) The generated images, audio, video, etc. from the Diffusion
+ Pipeline's response.
+ loggable_kwarg_chunks: (List) Loggable chunks of kwargs.
+ """
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ try:
+ caption = ""
+ if self.pipeline_name in [
+ "StableDiffusionXLPipeline",
+ "StableDiffusionXLImg2ImgPipeline",
+ ]:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ prompt2_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt_2")
+ caption = f"Prompt-1: {loggable_kwarg_chunks[prompt_index][idx]}\nPrompt-2: {loggable_kwarg_chunks[prompt2_index][idx]}"
+ else:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Image/Pipeline-Call-{self.pipeline_call_count}": wandb.Image(
+ image, caption=caption
+ )
+ }
+ )
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ try:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video(
+ postprocess_pils_to_np(image), fps=4, caption=caption
+ )
+ }
+ )
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ try:
+ prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ].index("prompt")
+ caption = loggable_kwarg_chunks[prompt_index][idx]
+ except ValueError:
+ caption = None
+ wandb.log(
+ {
+ f"Generated-Audio/Pipeline-Call-{self.pipeline_call_count}": wandb.Audio(
+ image, sample_rate=16000, caption=caption
+ )
+ }
+ )
+
+ def add_data_to_table(
+ self, image: Any, loggable_kwarg_chunks: List, idx: int
+ ) -> None:
+ """Populate the row of the `wandb.Table`.
+
+ Args:
+ image: (Any) The generated images, audio, video, etc. from the Diffusion
+ Pipeline's response.
+ loggable_kwarg_chunks: (List) Loggable chunks of kwargs.
+ idx: (int) Chunk index.
+ """
+ table_row = []
+ kwarg_actions = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-actions"
+ ]
+ for column_idx, loggable_kwarg_chunk in enumerate(loggable_kwarg_chunks):
+ if kwarg_actions[column_idx] is None:
+ table_row.append(
+ loggable_kwarg_chunk[idx]
+ if loggable_kwarg_chunk[idx] is not None
+ else ""
+ )
+ else:
+ table_row.append(kwarg_actions[column_idx](loggable_kwarg_chunk[idx]))
+ if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]:
+ table_row.append(wandb.Image(image))
+ else:
+ if (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "video"
+ ):
+ table_row.append(wandb.Video(postprocess_pils_to_np(image), fps=4))
+ elif (
+ SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"]
+ == "audio"
+ ):
+ table_row.append(wandb.Audio(image, sample_rate=16000))
+ self.wandb_table.add_data(*table_row)
+
+ def prepare_loggable_dict(
+ self, pipeline: Any, response: Response, kwargs: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ """Prepare the loggable dictionary, which is the packed data as a dictionary for logging to wandb, None if an exception occurred.
+
+ Args:
+ pipeline: (Any) The Diffusion Pipeline.
+ response: (wandb.sdk.integration_utils.auto_logging.Response) The response from
+ the request.
+ kwargs: (Dict[str, Any]) Dictionary of keyword arguments.
+
+ Returns:
+ Packed data as a dictionary for logging to wandb, None if an exception occurred.
+ """
+ # Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response.
+ images = self.get_output_images(response)
+ if (
+ self.pipeline_name == "StableDiffusionXLPipeline"
+ and kwargs["output_type"] == "latent"
+ ):
+ images = decode_sdxl_t2i_latents(pipeline, response.images)
+
+ # Account for exception pipelines for text-to-video
+ if self.pipeline_name in ["TextToVideoSDPipeline", "TextToVideoZeroPipeline"]:
+ video = postprocess_np_arrays_for_video(
+ images, normalize=self.pipeline_name == "TextToVideoZeroPipeline"
+ )
+ wandb.log(
+ {
+ f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video(
+ video, fps=4, caption=kwargs["prompt"]
+ )
+ }
+ )
+ loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ]
+ table_row = [
+ kwargs[loggable_kwarg_ids[idx]]
+ for idx in range(len(loggable_kwarg_ids))
+ ]
+ table_row.append(wandb.Video(video, fps=4))
+ self.wandb_table.add_data(*table_row)
+ else:
+ loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][
+ "kwarg-logging"
+ ]
+ # chunkify loggable kwargs
+ loggable_kwarg_chunks = []
+ for loggable_kwarg_id in loggable_kwarg_ids:
+ loggable_kwarg_chunks.append(
+ kwargs[loggable_kwarg_id]
+ if isinstance(kwargs[loggable_kwarg_id], list)
+ else [kwargs[loggable_kwarg_id]]
+ )
+ # chunkify the generated media
+ images = chunkify(images, len(loggable_kwarg_chunks[0]))
+ for idx in range(len(loggable_kwarg_chunks[0])):
+ for image in images[idx]:
+ # Log media to media panel
+ self.log_media(image, loggable_kwarg_chunks, idx)
+ # Populate the row of the wandb_table
+ self.add_data_to_table(image, loggable_kwarg_chunks, idx)
+ return {
+ f"Result-Table/Pipeline-Call-{self.pipeline_call_count}": self.wandb_table
+ }
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6aac045ba9739af9d0ab342a63e33252b63e0
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/diffusers/resolvers/utils.py
@@ -0,0 +1,102 @@
+import inspect
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence
+
+import wandb
+from wandb.util import get_module
+
+if TYPE_CHECKING:
+ np_array = get_module("numpy.array")
+ torch_float_tensor = get_module("torch.FloatTensor")
+
+
+def chunkify(input_list, chunk_size) -> List:
+ chunk_size = max(1, chunk_size)
+ return [
+ input_list[i : i + chunk_size] for i in range(0, len(input_list), chunk_size)
+ ]
+
+
+def get_updated_kwargs(
+ pipeline: Any, args: Sequence[Any], kwargs: Dict[str, Any]
+) -> Dict[str, Any]:
+ pipeline_call_parameters = list(
+ inspect.signature(pipeline.__call__).parameters.items()
+ )
+ for idx, arg in enumerate(args):
+ kwargs[pipeline_call_parameters[idx][0]] = arg
+ for pipeline_parameter in pipeline_call_parameters:
+ if pipeline_parameter[0] not in kwargs:
+ kwargs[pipeline_parameter[0]] = pipeline_parameter[1].default
+ if "generator" in kwargs:
+ generator = kwargs["generator"]
+ kwargs["generator"] = (
+ {
+ "seed": generator.initial_seed(),
+ "device": generator.device,
+ "random_state": generator.get_state().cpu().numpy().tolist(),
+ }
+ if generator is not None
+ else None
+ )
+ if "ip_adapter_image" in kwargs:
+ if kwargs["ip_adapter_image"] is not None:
+ wandb.log({"IP-Adapter-Image": wandb.Image(kwargs["ip_adapter_image"])})
+ return kwargs
+
+
+def postprocess_pils_to_np(image: List) -> "np_array":
+ np = get_module(
+ "numpy",
+ required="Please ensure NumPy is installed. You can run `pip install numpy` to install it.",
+ )
+ return np.stack(
+ [np.transpose(np.array(img).astype("uint8"), axes=(2, 0, 1)) for img in image],
+ axis=0,
+ )
+
+
+def postprocess_np_arrays_for_video(
+ images: List["np_array"], normalize: Optional[bool] = False
+) -> "np_array":
+ np = get_module(
+ "numpy",
+ required="Please ensure NumPy is installed. You can run `pip install numpy` to install it.",
+ )
+ images = [(img * 255).astype("uint8") for img in images] if normalize else images
+ return np.transpose(np.stack((images), axis=0), axes=(0, 3, 1, 2))
+
+
+def decode_sdxl_t2i_latents(pipeline: Any, latents: "torch_float_tensor") -> List:
+ """Decode latents generated by [`diffusers.StableDiffusionXLPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#stable-diffusion-xl).
+
+ Args:
+ pipeline: (diffusers.DiffusionPipeline) The Diffusion Pipeline from
+ [`diffusers`](https://huggingface.co/docs/diffusers).
+ latents (torch.FloatTensor): The generated latents.
+
+ Returns:
+ List of `PIL` images corresponding to the generated latents.
+ """
+ torch = get_module(
+ "torch",
+ required="Please ensure PyTorch is installed. You can check out https://pytorch.org/get-started/locally/#start-locally for installation instructions.",
+ )
+ with torch.no_grad():
+ needs_upcasting = (
+ pipeline.vae.dtype == torch.float16 and pipeline.vae.config.force_upcast
+ )
+ if needs_upcasting:
+ pipeline.upcast_vae()
+ latents = latents.to(
+ next(iter(pipeline.vae.post_quant_conv.parameters())).dtype
+ )
+ images = pipeline.vae.decode(
+ latents / pipeline.vae.config.scaling_factor, return_dict=False
+ )[0]
+ if needs_upcasting:
+ pipeline.vae.to(dtype=torch.float16)
+ if pipeline.watermark is not None:
+ images = pipeline.watermark.apply_watermark(images)
+ images = pipeline.image_processor.postprocess(images, output_type="pil")
+ pipeline.maybe_free_model_hooks()
+ return images
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/fastai/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/fastai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d12d71d58183b0ce679c2bbb0e4e917fed791e2c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/fastai/__init__.py
@@ -0,0 +1,243 @@
+"""Hooks that add fast.ai v1 Learners to Weights & Biases through a callback.
+
+Requested logged data can be configured through the callback constructor.
+
+Examples:
+ WandbCallback can be used when initializing the Learner::
+
+ ```
+ from wandb.fastai import WandbCallback
+ [...]
+ learn = Learner(data, ..., callback_fns=WandbCallback)
+ learn.fit(epochs)
+ ```
+
+ Custom parameters can be given using functools.partial::
+
+ ```
+ from wandb.fastai import WandbCallback
+ from functools import partial
+ [...]
+ learn = Learner(data, ..., callback_fns=partial(WandbCallback, ...))
+ learn.fit(epochs)
+ ```
+
+ Finally, it is possible to use WandbCallback only when starting
+ training. In this case it must be instantiated::
+
+ ```
+ learn.fit(..., callbacks=WandbCallback(learn))
+ ```
+
+ or, with custom parameters::
+
+ ```
+ learn.fit(..., callbacks=WandbCallback(learn, ...))
+ ```
+"""
+
+import random
+import sys
+from pathlib import Path
+from typing import Any, Literal, Optional
+
+import fastai
+from fastai.callbacks import TrackerCallback
+
+import wandb
+from wandb.sdk.lib import ipython
+
+try:
+ import matplotlib
+
+ if not ipython.in_jupyter():
+ matplotlib.use("Agg") # non-interactive backend (avoid tkinter issues)
+ import matplotlib.pyplot as plt
+except ImportError:
+ wandb.termwarn("matplotlib required if logging sample image predictions")
+
+
+class WandbCallback(TrackerCallback):
+ """Callback for saving model topology, losses & metrics.
+
+ Optionally logs weights, gradients, sample predictions and best trained model.
+
+ Args:
+ learn (fastai.basic_train.Learner): the fast.ai learner to hook.
+ log (str): "gradients", "parameters", "all", or None. Losses & metrics are always logged.
+ save_model (bool): save model at the end of each epoch. It will also load best model at the end of training.
+ monitor (str): metric to monitor for saving best model. None uses default TrackerCallback monitor value.
+ mode (str): "auto", "min" or "max" to compare "monitor" values and define best model.
+ input_type (str): "images" or None. Used to display sample predictions.
+ validation_data (list): data used for sample predictions if input_type is set.
+ predictions (int): number of predictions to make if input_type is set and validation_data is None.
+ seed (int): initialize random generator for sample predictions if input_type is set and validation_data is None.
+ """
+
+ # Record if watch has been called previously (even in another instance)
+ _watch_called = False
+
+ def __init__(
+ self,
+ learn: "fastai.basic_train.Learner",
+ log: Optional[Literal["gradients", "parameters", "all"]] = "gradients",
+ save_model: bool = True,
+ monitor: Optional[str] = None,
+ mode: Literal["auto", "min", "max"] = "auto",
+ input_type: Optional[Literal["images"]] = None,
+ validation_data: Optional[list] = None,
+ predictions: int = 36,
+ seed: int = 12345,
+ ) -> None:
+ # Check if wandb.init has been called
+ if wandb.run is None:
+ raise ValueError("You must call wandb.init() before WandbCallback()")
+
+ # Adapted from fast.ai "SaveModelCallback"
+ if monitor is None:
+ # use default TrackerCallback monitor value
+ super().__init__(learn, mode=mode)
+ else:
+ super().__init__(learn, monitor=monitor, mode=mode)
+ self.save_model = save_model
+ self.model_path = Path(wandb.run.dir) / "bestmodel.pth"
+
+ self.log = log
+ self.input_type = input_type
+ self.best = None
+
+ # Select items for sample predictions to see evolution along training
+ self.validation_data = validation_data
+ if input_type and not self.validation_data:
+ wandb_random = random.Random(seed) # For repeatability
+ predictions = min(predictions, len(learn.data.valid_ds))
+ indices = wandb_random.sample(range(len(learn.data.valid_ds)), predictions)
+ self.validation_data = [learn.data.valid_ds[i] for i in indices]
+
+ def on_train_begin(self, **kwargs: Any) -> None:
+ """Call watch method to log model topology, gradients & weights."""
+ # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
+ super().on_train_begin()
+
+ # Ensure we don't call "watch" multiple times
+ if not WandbCallback._watch_called:
+ WandbCallback._watch_called = True
+
+ # Logs model topology and optionally gradients and weights
+ wandb.watch(self.learn.model, log=self.log)
+
+ def on_epoch_end(
+ self, epoch: int, smooth_loss: float, last_metrics: list, **kwargs: Any
+ ) -> None:
+ """Log training loss, validation loss and custom metrics & log prediction samples & save model."""
+ if self.save_model:
+ # Adapted from fast.ai "SaveModelCallback"
+ current = self.get_monitor_value()
+ if current is not None and self.operator(current, self.best):
+ wandb.termlog(
+ f"Better model found at epoch {epoch} with {self.monitor} value: {current}."
+ )
+ self.best = current
+
+ # Save within wandb folder
+ with self.model_path.open("wb") as model_file:
+ self.learn.save(model_file)
+
+ # Log sample predictions if learn.predict is available
+ if self.validation_data:
+ try:
+ self._wandb_log_predictions()
+ except FastaiError as e:
+ wandb.termwarn(e.message)
+ self.validation_data = None # prevent from trying again on next loop
+ except Exception as e:
+ wandb.termwarn(f"Unable to log prediction samples.\n{e}")
+ self.validation_data = None # prevent from trying again on next loop
+
+ # Log losses & metrics
+ # Adapted from fast.ai "CSVLogger"
+ logs = {
+ name: stat
+ for name, stat in list(
+ zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics)
+ )
+ }
+ wandb.log(logs)
+
+ def on_train_end(self, **kwargs: Any) -> None:
+ """Load the best model."""
+ if self.save_model:
+ # Adapted from fast.ai "SaveModelCallback"
+ if self.model_path.is_file():
+ with self.model_path.open("rb") as model_file:
+ self.learn.load(model_file, purge=False)
+ wandb.termlog(f"Loaded best saved model from {self.model_path}")
+
+ def _wandb_log_predictions(self) -> None:
+ """Log prediction samples."""
+ pred_log = []
+
+ if self.validation_data is None:
+ return
+
+ for x, y in self.validation_data:
+ try:
+ pred = self.learn.predict(x)
+ except Exception:
+ raise FastaiError(
+ 'Unable to run "predict" method from Learner to log prediction samples.'
+ )
+
+ # scalar -> likely to be a category
+ # tensor of dim 1 -> likely to be multicategory
+ if not pred[1].shape or pred[1].dim() == 1:
+ pred_log.append(
+ wandb.Image(
+ x.data,
+ caption=f"Ground Truth: {y}\nPrediction: {pred[0]}",
+ )
+ )
+
+ # most vision datasets have a "show" function we can use
+ elif hasattr(x, "show"):
+ # log input data
+ pred_log.append(wandb.Image(x.data, caption="Input data", grouping=3))
+
+ # log label and prediction
+ for im, capt in ((pred[0], "Prediction"), (y, "Ground Truth")):
+ # Resize plot to image resolution
+ # from https://stackoverflow.com/a/13714915
+ my_dpi = 100
+ fig = plt.figure(frameon=False, dpi=my_dpi)
+ h, w = x.size
+ fig.set_size_inches(w / my_dpi, h / my_dpi)
+ ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
+ ax.set_axis_off()
+ fig.add_axes(ax)
+
+ # Superpose label or prediction to input image
+ x.show(ax=ax, y=im)
+ pred_log.append(wandb.Image(fig, caption=capt))
+ plt.close(fig)
+
+ # likely to be an image
+ elif hasattr(y, "shape") and (
+ (len(y.shape) == 2) or (len(y.shape) == 3 and y.shape[0] in [1, 3, 4])
+ ):
+ pred_log.extend(
+ [
+ wandb.Image(x.data, caption="Input data", grouping=3),
+ wandb.Image(pred[0].data, caption="Prediction"),
+ wandb.Image(y.data, caption="Ground Truth"),
+ ]
+ )
+
+ # we just log input data
+ else:
+ pred_log.append(wandb.Image(x.data, caption="Input data"))
+
+ wandb.log({"Prediction Samples": pred_log}, commit=False)
+
+
+class FastaiError(wandb.Error):
+ pass
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/fastai/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/fastai/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80e04676fca55026ec3bfcfae8e9182f17a33dfb
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/fastai/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/gym/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/gym/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0624e4def25ab1e51044221f577066c7939108b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/gym/__init__.py
@@ -0,0 +1,98 @@
+import re
+import sys
+from typing import Literal, Optional
+
+import wandb
+import wandb.util
+
+_gym_version_lt_0_26: Optional[bool] = None
+_gymnasium_version_lt_1_0_0: Optional[bool] = None
+
+_required_error_msg = (
+ "Couldn't import the gymnasium python package, install with `pip install gymnasium`"
+)
+GymLib = Literal["gym", "gymnasium"]
+
+
+def monitor():
+ """Monitor a gym environment.
+
+ Supports both gym and gymnasium.
+ """
+ gym_lib: Optional[GymLib] = None
+
+ # gym is not maintained anymore, gymnasium is the drop-in replacement - prefer it
+ if wandb.util.get_module("gymnasium") is not None:
+ gym_lib = "gymnasium"
+ elif wandb.util.get_module("gym") is not None:
+ gym_lib = "gym"
+
+ if gym_lib is None:
+ raise wandb.Error(_required_error_msg)
+
+ global _gym_version_lt_0_26
+ global _gymnasium_version_lt_1_0_0
+
+ if _gym_version_lt_0_26 is None or _gymnasium_version_lt_1_0_0 is None:
+ if gym_lib == "gym":
+ import gym
+ else:
+ import gymnasium as gym # type: ignore
+
+ from packaging.version import parse
+
+ gym_lib_version = parse(gym.__version__)
+ _gym_version_lt_0_26 = gym_lib_version < parse("0.26.0")
+ _gymnasium_version_lt_1_0_0 = gym_lib_version < parse("1.0.0a1")
+
+ path = "path" # Default path
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
+ vcr_recorder_attribute = "RecordVideo"
+ wrappers = wandb.util.get_module(
+ f"{gym_lib}.wrappers",
+ required=_required_error_msg,
+ )
+ recorder = getattr(wrappers, vcr_recorder_attribute)
+ else:
+ vcr = wandb.util.get_module(
+ f"{gym_lib}.wrappers.monitoring.video_recorder",
+ required=_required_error_msg,
+ )
+ # Breaking change in gym 0.26.0
+ if _gym_version_lt_0_26:
+ vcr_recorder_attribute = "ImageEncoder"
+ recorder = getattr(vcr, vcr_recorder_attribute)
+ path = "output_path" # Override path for older gym versions
+ else:
+ vcr_recorder_attribute = "VideoRecorder"
+ recorder = getattr(vcr, vcr_recorder_attribute)
+
+ recorder.orig_close = recorder.close
+
+ def close(self):
+ recorder.orig_close(self)
+ if not self.enabled:
+ return
+ if wandb.run:
+ m = re.match(r".+(video\.\d+).+", getattr(self, path))
+ key = m.group(1) if m else "videos"
+ wandb.log({key: wandb.Video(getattr(self, path))})
+
+ def del_(self):
+ self.orig_close()
+
+ if not _gym_version_lt_0_26:
+ recorder.__del__ = del_
+ recorder.close = close
+
+ if gym_lib == "gymnasium" and not _gymnasium_version_lt_1_0_0:
+ wrapper_name = vcr_recorder_attribute
+ else:
+ wrapper_name = f"monitoring.video_recorder.{vcr_recorder_attribute}"
+
+ wandb.patched["gym"].append(
+ [
+ f"{gym_lib}.wrappers.{wrapper_name}",
+ "close",
+ ]
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f42f0a5a60cda67b225f60dca87a5f507cbc819
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..943249ebe22686fcbdfaa6708c33e15ec875bccc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog",)
+
+from .huggingface import autolog
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec75e65b13f747d3ef043cdf7643c9998606fa7e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/huggingface.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/huggingface.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5799545f574afbafeeeb1656705ae938705c178
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/huggingface.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffc2c0dcc140cf6f803cfa09a1754bbc2a1d097c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/huggingface.py b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/huggingface.py
new file mode 100644
index 0000000000000000000000000000000000000000..d44cf2cbb51d009821e26924ab944a953a1ff866
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/huggingface.py
@@ -0,0 +1,18 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import HuggingFacePipelineRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+resolver = HuggingFacePipelineRequestResponseResolver()
+
+autolog = AutologAPI(
+ name="transformers",
+ symbols=("Pipeline.__call__",),
+ resolver=resolver,
+ telemetry_feature="hf_pipeline_autolog",
+)
+
+autolog.get_latest_id = resolver.get_latest_id
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/huggingface/resolver.py b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..2acbdabe56e5e86c1d4442c99b7e9232d5621a48
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/huggingface/resolver.py
@@ -0,0 +1,213 @@
+import logging
+import os
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
+
+import pytz
+
+import wandb
+from wandb.sdk.integration_utils.auto_logging import Response
+from wandb.sdk.lib.runid import generate_id
+
+logger = logging.getLogger(__name__)
+
+SUPPORTED_PIPELINE_TASKS = [
+ "text-classification",
+ "sentiment-analysis",
+ "question-answering",
+ "summarization",
+ "translation",
+ "text2text-generation",
+ "text-generation",
+ # "conversational",
+]
+
+PIPELINES_WITH_TOP_K = [
+ "text-classification",
+ "sentiment-analysis",
+ "question-answering",
+]
+
+
+class HuggingFacePipelineRequestResponseResolver:
+ """Resolver for HuggingFace's pipeline request and responses, providing necessary data transformations and formatting.
+
+ This is based off (from wandb.sdk.integration_utils.auto_logging import RequestResponseResolver)
+ """
+
+ autolog_id = None
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float,
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ """Main call method for this class.
+
+ :param args: list of arguments
+ :param kwargs: dictionary of keyword arguments
+ :param response: the response from the request
+ :param start_time: time when request started
+ :param time_elapsed: time elapsed for the request
+ :returns: packed data as a dictionary for logging to wandb, None if an exception occurred
+ """
+ try:
+ pipe, input_data = args[:2]
+ task = pipe.task
+
+ # Translation tasks are in the form of `translation_x_to_y`
+ if task in SUPPORTED_PIPELINE_TASKS or task.startswith("translation"):
+ model = self._get_model(pipe)
+ if model is None:
+ return None
+ model_alias = model.name_or_path
+ timestamp = datetime.now(pytz.utc)
+
+ input_data, response = self._transform_task_specific_data(
+ task, input_data, response
+ )
+ formatted_data = self._format_data(task, input_data, response, kwargs)
+ packed_data = self._create_table(
+ formatted_data, model_alias, timestamp, time_elapsed
+ )
+ table_name = os.environ.get("WANDB_AUTOLOG_TABLE_NAME", f"{task}")
+ # TODO: Let users decide the name in a way that does not use an environment variable
+
+ return {
+ table_name: wandb.Table(
+ columns=packed_data[0], data=packed_data[1:]
+ )
+ }
+
+ logger.warning(
+ f"The task: `{task}` is not yet supported.\nPlease contact `wandb` to notify us if you would like support for this task"
+ )
+ except Exception as e:
+ logger.warning(e)
+ return None
+
+ # TODO: This should have a dependency on PreTrainedModel. i.e. isinstance(PreTrainedModel)
+ # from transformers.modeling_utils import PreTrainedModel
+ # We do not want this dependency explicitly in our codebase so we make a very general
+ # assumption about the structure of the pipeline which may have unintended consequences
+ def _get_model(self, pipe) -> Optional[Any]:
+ """Extracts model from the pipeline.
+
+ :param pipe: the HuggingFace pipeline
+ :returns: Model if available, None otherwise
+ """
+ model = pipe.model
+ try:
+ return model.model
+ except AttributeError:
+ logger.info(
+ "Model does not have a `.model` attribute. Assuming `pipe.model` is the correct model."
+ )
+ return model
+
+ @staticmethod
+ def _transform_task_specific_data(
+ task: str, input_data: Union[List[Any], Any], response: Union[List[Any], Any]
+ ) -> Tuple[Union[List[Any], Any], Union[List[Any], Any]]:
+ """Transform input and response data based on specific tasks.
+
+ :param task: the task name
+ :param input_data: the input data
+ :param response: the response data
+ :returns: tuple of transformed input_data and response
+ """
+ if task == "question-answering":
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ input_data = [data.__dict__ for data in input_data]
+ elif task == "conversational":
+ # We only grab the latest input/output pair from the conversation
+ # Logging the whole conversation renders strangely.
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ input_data = [data.__dict__["past_user_inputs"][-1] for data in input_data]
+
+ response = response if isinstance(response, list) else [response]
+ response = [data.__dict__["generated_responses"][-1] for data in response]
+ return input_data, response
+
+ def _format_data(
+ self,
+ task: str,
+ input_data: Union[List[Any], Any],
+ response: Union[List[Any], Any],
+ kwargs: Dict[str, Any],
+ ) -> List[Dict[str, Any]]:
+ """Formats input data, response, and kwargs into a list of dictionaries.
+
+ :param task: the task name
+ :param input_data: the input data
+ :param response: the response data
+ :param kwargs: dictionary of keyword arguments
+ :returns: list of dictionaries containing formatted data
+ """
+ input_data = input_data if isinstance(input_data, list) else [input_data]
+ response = response if isinstance(response, list) else [response]
+
+ formatted_data = []
+ for i_text, r_text in zip(input_data, response):
+ # Unpack single element responses for better rendering in wandb UI when it is a task without top_k
+ # top_k = 1 would unpack the response into a single element while top_k > 1 would be a list
+ # this would cause the UI to not properly concatenate the tables of the same task by omitting the elements past the first
+ if (
+ (isinstance(r_text, list))
+ and (len(r_text) == 1)
+ and task not in PIPELINES_WITH_TOP_K
+ ):
+ r_text = r_text[0]
+ formatted_data.append(
+ {"input": i_text, "response": r_text, "kwargs": kwargs}
+ )
+ return formatted_data
+
+ def _create_table(
+ self,
+ formatted_data: List[Dict[str, Any]],
+ model_alias: str,
+ timestamp: float,
+ time_elapsed: float,
+ ) -> List[List[Any]]:
+ """Creates a table from formatted data, model alias, timestamp, and elapsed time.
+
+ :param formatted_data: list of dictionaries containing formatted data
+ :param model_alias: alias of the model
+ :param timestamp: timestamp of the data
+ :param time_elapsed: time elapsed from the beginning
+ :returns: list of lists, representing a table of data. [0]th element = columns. [1]st element = data
+ """
+ header = [
+ "ID",
+ "Model Alias",
+ "Timestamp",
+ "Elapsed Time",
+ "Input",
+ "Response",
+ "Kwargs",
+ ]
+ table = [header]
+ autolog_id = generate_id(length=16)
+
+ for data in formatted_data:
+ row = [
+ autolog_id,
+ model_alias,
+ timestamp,
+ time_elapsed,
+ data["input"],
+ data["response"],
+ data["kwargs"],
+ ]
+ table.append(row)
+
+ self.autolog_id = autolog_id
+
+ return table
+
+ def get_latest_id(self):
+ return self.autolog_id
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8699d6805b92dab3381456270a6449b2078d983b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/__init__.py
@@ -0,0 +1,11 @@
+"""Tools for integrating `wandb` with [`Keras`](https://keras.io/)."""
+
+__all__ = (
+ "WandbCallback",
+ "WandbMetricsLogger",
+ "WandbModelCheckpoint",
+ "WandbEvalCallback",
+)
+
+from .callbacks import WandbEvalCallback, WandbMetricsLogger, WandbModelCheckpoint
+from .keras import WandbCallback # TODO: legacy callback to be deprecated
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4354ba0cd207366c34b58ea3f8bfc237394343cf
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/keras.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/keras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b5359893aa74e7388b6272a451870e3590eb6e1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/__pycache__/keras.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6035bd4c9c5067e553404a5a4bb818ef582a36a8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__init__.py
@@ -0,0 +1,5 @@
+__all__ = ("WandbMetricsLogger", "WandbModelCheckpoint", "WandbEvalCallback")
+
+from .metrics_logger import WandbMetricsLogger
+from .model_checkpoint import WandbModelCheckpoint
+from .tables_builder import WandbEvalCallback
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8687abc18c74fdf09f39d4cd55be5d8c7881ed53
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df31d0c3a3ccbedbe916ec6a27944907d8bebbf7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a532cd6d9c261c0707466c5b0065cf01c510d1f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbecff42764b092c2acd112b3cd6e7bec2ed5cf4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..b51f5bfd7af7a134268529d617fd68daf5adcce9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/metrics_logger.py
@@ -0,0 +1,129 @@
+from typing import Any, Dict, Literal, Optional, Union
+
+import tensorflow as tf # type: ignore
+from tensorflow.keras import callbacks
+
+import wandb
+from wandb.integration.keras.keras import patch_tf_keras
+from wandb.sdk.lib import telemetry
+
+LogStrategy = Literal["epoch", "batch"]
+
+
+patch_tf_keras()
+
+
+class WandbMetricsLogger(callbacks.Callback):
+ """Logger that sends system metrics to W&B.
+
+ `WandbMetricsLogger` automatically logs the `logs` dictionary that callback methods
+ take as argument to wandb.
+
+ This callback automatically logs the following to a W&B run page:
+ * system (CPU/GPU/TPU) metrics,
+ * train and validation metrics defined in `model.compile`,
+ * learning rate (both for a fixed value or a learning rate scheduler)
+
+ Notes:
+ If you resume training by passing `initial_epoch` to `model.fit` and you are using a
+ learning rate scheduler, make sure to pass `initial_global_step` to
+ `WandbMetricsLogger`. The `initial_global_step` is `step_size * initial_step`, where
+ `step_size` is number of training steps per epoch. `step_size` can be calculated as
+ the product of the cardinality of the training dataset and the batch size.
+
+ Args:
+ log_freq: ("epoch", "batch", or int) if "epoch", logs metrics
+ at the end of each epoch. If "batch", logs metrics at the end
+ of each batch. If an integer, logs metrics at the end of that
+ many batches. Defaults to "epoch".
+ initial_global_step: (int) Use this argument to correctly log the
+ learning rate when you resume training from some `initial_epoch`,
+ and a learning rate scheduler is used. This can be computed as
+ `step_size * initial_step`. Defaults to 0.
+ """
+
+ def __init__(
+ self,
+ log_freq: Union[LogStrategy, int] = "epoch",
+ initial_global_step: int = 0,
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before WandbMetricsLogger()"
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_metrics_logger = True
+
+ if log_freq == "batch":
+ log_freq = 1
+
+ self.logging_batch_wise = isinstance(log_freq, int)
+ self.log_freq: Any = log_freq if self.logging_batch_wise else None
+ self.global_batch = 0
+ self.global_step = initial_global_step
+
+ if self.logging_batch_wise:
+ # define custom x-axis for batch logging.
+ wandb.define_metric("batch/batch_step")
+ # set all batch metrics to be logged against batch_step.
+ wandb.define_metric("batch/*", step_metric="batch/batch_step")
+ else:
+ # define custom x-axis for epoch-wise logging.
+ wandb.define_metric("epoch/epoch")
+ # set all epoch-wise metrics to be logged against epoch.
+ wandb.define_metric("epoch/*", step_metric="epoch/epoch")
+
+ def _get_lr(self) -> Union[float, None]:
+ if isinstance(
+ self.model.optimizer.learning_rate,
+ (tf.Variable, tf.Tensor),
+ ) or (
+ hasattr(self.model.optimizer.learning_rate, "shape")
+ and self.model.optimizer.learning_rate.shape == ()
+ ):
+ return float(self.model.optimizer.learning_rate.numpy().item())
+ try:
+ return float(
+ self.model.optimizer.learning_rate(step=self.global_step).numpy().item()
+ )
+ except Exception as e:
+ wandb.termerror(f"Unable to log learning rate: {e}", repeat=False)
+ return None
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, Any]] = None) -> None:
+ """Called at the end of an epoch."""
+ logs = dict() if logs is None else {f"epoch/{k}": v for k, v in logs.items()}
+
+ logs["epoch/epoch"] = epoch
+
+ lr = self._get_lr()
+ if lr is not None:
+ logs["epoch/learning_rate"] = lr
+
+ wandb.log(logs)
+
+ def on_batch_end(self, batch: int, logs: Optional[Dict[str, Any]] = None) -> None:
+ self.global_step += 1
+ """An alias for `on_train_batch_end` for backwards compatibility."""
+ if self.logging_batch_wise and batch % self.log_freq == 0:
+ logs = {f"batch/{k}": v for k, v in logs.items()} if logs else {}
+ logs["batch/batch_step"] = self.global_batch
+
+ lr = self._get_lr()
+ if lr is not None:
+ logs["batch/learning_rate"] = lr
+
+ wandb.log(logs)
+
+ self.global_batch += self.log_freq
+
+ def on_train_batch_end(
+ self, batch: int, logs: Optional[Dict[str, Any]] = None
+ ) -> None:
+ """Called at the end of a training batch in `fit` methods."""
+ self.on_batch_end(batch, logs if logs else {})
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..9990b4ffd19ad40d4f1204d5c6bc133c352c0835
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/model_checkpoint.py
@@ -0,0 +1,188 @@
+import os
+import string
+from typing import Any, Dict, List, Literal, Optional, Union
+
+import tensorflow as tf # type: ignore
+from tensorflow.keras import callbacks # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry
+from wandb.sdk.lib.paths import StrPath
+
+from ..keras import patch_tf_keras
+
+Mode = Literal["auto", "min", "max"]
+SaveStrategy = Literal["epoch"]
+
+patch_tf_keras()
+
+
+class WandbModelCheckpoint(callbacks.ModelCheckpoint):
+ """A checkpoint that periodically saves a Keras model or model weights.
+
+ Saved weights are uploaded to W&B as a `wandb.Artifact`.
+
+ Since this callback is subclassed from `tf.keras.callbacks.ModelCheckpoint`, the
+ checkpointing logic is taken care of by the parent callback. You can learn more
+ here: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint
+
+ This callback is to be used in conjunction with training using `model.fit()` to save
+ a model or weights (in a checkpoint file) at some interval. The model checkpoints
+ will be logged as W&B Artifacts. You can learn more here:
+ https://docs.wandb.ai/guides/artifacts
+
+ This callback provides the following features:
+ - Save the model that has achieved "best performance" based on "monitor".
+ - Save the model at the end of every epoch regardless of the performance.
+ - Save the model at the end of epoch or after a fixed number of training batches.
+ - Save only model weights, or save the whole model.
+ - Save the model either in SavedModel format or in `.h5` format.
+
+ Args:
+ filepath: (Union[str, os.PathLike]) path to save the model file. `filepath`
+ can contain named formatting options, which will be filled by the value
+ of `epoch` and keys in `logs` (passed in `on_epoch_end`). For example:
+ if `filepath` is `model-{epoch:02d}-{val_loss:.2f}`, then the
+ model checkpoints will be saved with the epoch number and the
+ validation loss in the filename.
+ monitor: (str) The metric name to monitor. Default to "val_loss".
+ verbose: (int) Verbosity mode, 0 or 1. Mode 0 is silent, and mode 1
+ displays messages when the callback takes an action.
+ save_best_only: (bool) if `save_best_only=True`, it only saves when the model
+ is considered the "best" and the latest best model according to the
+ quantity monitored will not be overwritten. If `filepath` doesn't contain
+ formatting options like `{epoch}` then `filepath` will be overwritten by
+ each new better model locally. The model logged as an artifact will still be
+ associated with the correct `monitor`. Artifacts will be uploaded
+ continuously and versioned separately as a new best model is found.
+ save_weights_only: (bool) if True, then only the model's weights will be saved.
+ mode: (Mode) one of {'auto', 'min', 'max'}. For `val_acc`, this should be `max`,
+ for `val_loss` this should be `min`, etc.
+ save_freq: (Union[SaveStrategy, int]) `epoch` or integer. When using `'epoch'`,
+ the callback saves the model after each epoch. When using an integer, the
+ callback saves the model at end of this many batches.
+ Note that when monitoring validation metrics such as `val_acc` or `val_loss`,
+ save_freq must be set to "epoch" as those metrics are only available at the
+ end of an epoch.
+ initial_value_threshold: (Optional[float]) Floating point initial "best" value of the metric
+ to be monitored.
+ """
+
+ def __init__(
+ self,
+ filepath: StrPath,
+ monitor: str = "val_loss",
+ verbose: int = 0,
+ save_best_only: bool = False,
+ save_weights_only: bool = False,
+ mode: Mode = "auto",
+ save_freq: Union[SaveStrategy, int] = "epoch",
+ initial_value_threshold: Optional[float] = None,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(
+ filepath=filepath,
+ monitor=monitor,
+ verbose=verbose,
+ save_best_only=save_best_only,
+ save_weights_only=save_weights_only,
+ mode=mode,
+ save_freq=save_freq,
+ initial_value_threshold=initial_value_threshold,
+ **kwargs,
+ )
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before `WandbModelCheckpoint()`"
+ )
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_model_checkpoint = True
+
+ self.save_weights_only = save_weights_only
+
+ # User-friendly warning when trying to save the best model.
+ if self.save_best_only:
+ self._check_filepath()
+
+ self._is_old_tf_keras_version: Optional[bool] = None
+
+ def on_train_batch_end(
+ self, batch: int, logs: Optional[Dict[str, float]] = None
+ ) -> None:
+ if self._should_save_on_batch(batch):
+ if self.is_old_tf_keras_version:
+ # Save the model and get filepath
+ self._save_model(epoch=self._current_epoch, logs=logs)
+ filepath = self._get_file_path(epoch=self._current_epoch, logs=logs)
+ else:
+ # Save the model and get filepath
+ self._save_model(epoch=self._current_epoch, batch=batch, logs=logs)
+ filepath = self._get_file_path(
+ epoch=self._current_epoch, batch=batch, logs=logs
+ )
+ # Log the model as artifact
+ aliases = ["latest", f"epoch_{self._current_epoch}_batch_{batch}"]
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, float]] = None) -> None:
+ super().on_epoch_end(epoch, logs)
+ # Check if model checkpoint is created at the end of epoch.
+ if self.save_freq == "epoch":
+ # Get filepath where the model checkpoint is saved.
+ if self.is_old_tf_keras_version:
+ filepath = self._get_file_path(epoch=epoch, logs=logs)
+ else:
+ filepath = self._get_file_path(epoch=epoch, batch=None, logs=logs)
+ # Log the model as artifact
+ aliases = ["latest", f"epoch_{epoch}"]
+ self._log_ckpt_as_artifact(filepath, aliases=aliases)
+
+ def _log_ckpt_as_artifact(
+ self, filepath: str, aliases: Optional[List[str]] = None
+ ) -> None:
+ """Log model checkpoint as W&B Artifact."""
+ try:
+ assert wandb.run is not None
+ model_checkpoint_artifact = wandb.Artifact(
+ f"run_{wandb.run.id}_model", type="model"
+ )
+ if os.path.isfile(filepath):
+ model_checkpoint_artifact.add_file(filepath)
+ elif os.path.isdir(filepath):
+ model_checkpoint_artifact.add_dir(filepath)
+ else:
+ raise FileNotFoundError(f"No such file or directory {filepath}")
+ wandb.log_artifact(model_checkpoint_artifact, aliases=aliases or [])
+ except ValueError:
+ # This error occurs when `save_best_only=True` and the model
+ # checkpoint is not saved for that epoch/batch. Since TF/Keras
+ # is giving friendly log, we can avoid clustering the stdout.
+ pass
+
+ def _check_filepath(self) -> None:
+ placeholders = []
+ for tup in string.Formatter().parse(self.filepath):
+ if tup[1] is not None:
+ placeholders.append(tup[1])
+ if len(placeholders) == 0:
+ wandb.termwarn(
+ "When using `save_best_only`, ensure that the `filepath` argument "
+ "contains formatting placeholders like `{epoch:02d}` or `{batch:02d}`. "
+ "This ensures correct interpretation of the logged artifacts.",
+ repeat=False,
+ )
+
+ @property
+ def is_old_tf_keras_version(self) -> Optional[bool]:
+ if self._is_old_tf_keras_version is None:
+ from packaging.version import parse
+
+ try:
+ if parse(tf.keras.__version__) < parse("2.6.0"):
+ self._is_old_tf_keras_version = True
+ else:
+ self._is_old_tf_keras_version = False
+ except AttributeError:
+ self._is_old_tf_keras_version = False
+
+ return self._is_old_tf_keras_version
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd19bfb314f4c06c703858aed6fe47ca12bbcefc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/callbacks/tables_builder.py
@@ -0,0 +1,228 @@
+import abc
+from typing import Any, Dict, List, Optional
+
+from tensorflow.keras.callbacks import Callback # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+
+class WandbEvalCallback(Callback, abc.ABC):
+ """Abstract base class to build Keras callbacks for model prediction visualization.
+
+ You can build callbacks for visualizing model predictions `on_epoch_end`
+ that can be passed to `model.fit()` for classification, object detection,
+ segmentation, etc. tasks.
+
+ To use this, inherit from this base callback class and implement the
+ `add_ground_truth` and `add_model_prediction` methods.
+
+ The base class will take care of the following:
+ - Initialize `data_table` for logging the ground truth and
+ `pred_table` for predictions.
+ - The data uploaded to `data_table` is used as a reference for the
+ `pred_table`. This is to reduce the memory footprint. The `data_table_ref`
+ is a list that can be used to access the referenced data.
+ Check out the example below to see how it's done.
+ - Log the tables to W&B as W&B Artifacts.
+ - Each new `pred_table` is logged as a new version with aliases.
+
+ Example:
+ ```python
+ class WandbClfEvalCallback(WandbEvalCallback):
+ def __init__(self, validation_data, data_table_columns, pred_table_columns):
+ super().__init__(data_table_columns, pred_table_columns)
+
+ self.x = validation_data[0]
+ self.y = validation_data[1]
+
+ def add_ground_truth(self):
+ for idx, (image, label) in enumerate(zip(self.x, self.y)):
+ self.data_table.add_data(idx, wandb.Image(image), label)
+
+ def add_model_predictions(self, epoch):
+ preds = self.model.predict(self.x, verbose=0)
+ preds = tf.argmax(preds, axis=-1)
+
+ data_table_ref = self.data_table_ref
+ table_idxs = data_table_ref.get_index()
+
+ for idx in table_idxs:
+ pred = preds[idx]
+ self.pred_table.add_data(
+ epoch,
+ data_table_ref.data[idx][0],
+ data_table_ref.data[idx][1],
+ data_table_ref.data[idx][2],
+ pred,
+ )
+
+
+ model.fit(
+ x,
+ y,
+ epochs=2,
+ validation_data=(x, y),
+ callbacks=[
+ WandbClfEvalCallback(
+ validation_data=(x, y),
+ data_table_columns=["idx", "image", "label"],
+ pred_table_columns=["epoch", "idx", "image", "label", "pred"],
+ )
+ ],
+ )
+ ```
+
+ To have more fine-grained control, you can override the `on_train_begin` and
+ `on_epoch_end` methods. If you want to log the samples after N batched, you
+ can implement `on_train_batch_end` method.
+ """
+
+ def __init__(
+ self,
+ data_table_columns: List[str],
+ pred_table_columns: List[str],
+ *args: Any,
+ **kwargs: Any,
+ ) -> None:
+ super().__init__(*args, **kwargs)
+
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` first before using this callback."
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras_wandb_eval_callback = True
+
+ self.data_table_columns = data_table_columns
+ self.pred_table_columns = pred_table_columns
+
+ def on_train_begin(self, logs: Optional[Dict[str, float]] = None) -> None:
+ # Initialize the data_table
+ self.init_data_table(column_names=self.data_table_columns)
+ # Log the ground truth data
+ self.add_ground_truth(logs)
+ # Log the data_table as W&B Artifacts
+ self.log_data_table()
+
+ def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, float]] = None) -> None:
+ # Initialize the pred_table
+ self.init_pred_table(column_names=self.pred_table_columns)
+ # Log the model prediction
+ self.add_model_predictions(epoch, logs)
+ # Log the pred_table as W&B Artifacts
+ self.log_pred_table()
+
+ @abc.abstractmethod
+ def add_ground_truth(self, logs: Optional[Dict[str, float]] = None) -> None:
+ """Add ground truth data to `data_table`.
+
+ Use this method to write the logic for adding validation/training data to
+ `data_table` initialized using `init_data_table` method.
+
+ Example:
+ ```python
+ for idx, data in enumerate(dataloader):
+ self.data_table.add_data(idx, data)
+ ```
+ This method is called once `on_train_begin` or equivalent hook.
+ """
+ raise NotImplementedError(f"{self.__class__.__name__}.add_ground_truth")
+
+ @abc.abstractmethod
+ def add_model_predictions(
+ self, epoch: int, logs: Optional[Dict[str, float]] = None
+ ) -> None:
+ """Add a prediction from a model to `pred_table`.
+
+ Use this method to write the logic for adding model prediction for validation/
+ training data to `pred_table` initialized using `init_pred_table` method.
+
+ Example:
+ ```python
+ # Assuming the dataloader is not shuffling the samples.
+ for idx, data in enumerate(dataloader):
+ preds = model.predict(data)
+ self.pred_table.add_data(
+ self.data_table_ref.data[idx][0],
+ self.data_table_ref.data[idx][1],
+ preds,
+ )
+ ```
+ This method is called `on_epoch_end` or equivalent hook.
+ """
+ raise NotImplementedError(f"{self.__class__.__name__}.add_model_predictions")
+
+ def init_data_table(self, column_names: List[str]) -> None:
+ """Initialize the W&B Tables for validation data.
+
+ Call this method `on_train_begin` or equivalent hook. This is followed by adding
+ data to the table row or column wise.
+
+ Args:
+ column_names: (list) Column names for W&B Tables.
+ """
+ self.data_table = wandb.Table(columns=column_names, allow_mixed_types=True)
+
+ def init_pred_table(self, column_names: List[str]) -> None:
+ """Initialize the W&B Tables for model evaluation.
+
+ Call this method `on_epoch_end` or equivalent hook. This is followed by adding
+ data to the table row or column wise.
+
+ Args:
+ column_names: (list) Column names for W&B Tables.
+ """
+ self.pred_table = wandb.Table(columns=column_names)
+
+ def log_data_table(
+ self, name: str = "val", type: str = "dataset", table_name: str = "val_data"
+ ) -> None:
+ """Log the `data_table` as W&B artifact and call `use_artifact` on it.
+
+ This lets the evaluation table use the reference of already uploaded data
+ (images, text, scalar, etc.) without re-uploading.
+
+ Args:
+ name: (str) A human-readable name for this artifact, which is how you can
+ identify this artifact in the UI or reference it in use_artifact calls.
+ (default is 'val')
+ type: (str) The type of the artifact, which is used to organize and
+ differentiate artifacts. (default is 'dataset')
+ table_name: (str) The name of the table as will be displayed in the UI.
+ (default is 'val_data').
+ """
+ data_artifact = wandb.Artifact(name, type=type)
+ data_artifact.add(self.data_table, table_name)
+
+ # Calling `use_artifact` uploads the data to W&B.
+ assert wandb.run is not None
+ wandb.run.use_artifact(data_artifact)
+ data_artifact.wait()
+
+ # We get the reference table.
+ self.data_table_ref = data_artifact.get(table_name)
+
+ def log_pred_table(
+ self,
+ type: str = "evaluation",
+ table_name: str = "eval_data",
+ aliases: Optional[List[str]] = None,
+ ) -> None:
+ """Log the W&B Tables for model evaluation.
+
+ The table will be logged multiple times creating new version. Use this
+ to compare models at different intervals interactively.
+
+ Args:
+ type: (str) The type of the artifact, which is used to organize and
+ differentiate artifacts. (default is 'evaluation')
+ table_name: (str) The name of the table as will be displayed in the UI.
+ (default is 'eval_data')
+ aliases: (List[str]) List of aliases for the prediction table.
+ """
+ assert wandb.run is not None
+ pred_artifact = wandb.Artifact(f"run_{wandb.run.id}_pred", type=type)
+ pred_artifact.add(self.pred_table, table_name)
+ wandb.run.log_artifact(pred_artifact, aliases=aliases or ["latest"])
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/keras/keras.py b/venv/lib/python3.10/site-packages/wandb/integration/keras/keras.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dde8f71ed6a64c24790704ad4f3bf97e83ddd83
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/keras/keras.py
@@ -0,0 +1,1086 @@
+"""keras init."""
+
+import logging
+import operator
+import os
+import shutil
+import sys
+from itertools import chain
+
+import numpy as np
+import tensorflow as tf
+import tensorflow.keras.backend as K # noqa: N812
+
+import wandb
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.integration_utils.data_logging import ValidationDataLogger
+from wandb.sdk.lib.deprecate import deprecate
+from wandb.util import add_import_hook
+
+
+def _check_keras_version():
+ from keras import __version__ as keras_version
+ from packaging.version import parse
+
+ if parse(keras_version) < parse("2.4.0"):
+ wandb.termwarn(
+ f"Keras version {keras_version} is not fully supported. Required keras >= 2.4.0"
+ )
+
+
+def _can_compute_flops() -> bool:
+ """FLOPS computation is restricted to TF 2.x as it requires tf.compat.v1."""
+ from packaging.version import parse
+
+ if parse(tf.__version__) >= parse("2.0.0"):
+ return True
+
+ return False
+
+
+if "keras" in sys.modules:
+ _check_keras_version()
+else:
+ add_import_hook("keras", _check_keras_version)
+
+
+logger = logging.getLogger(__name__)
+
+
+def is_dataset(data):
+ dataset_ops = wandb.util.get_module("tensorflow.python.data.ops.dataset_ops")
+ if dataset_ops and hasattr(dataset_ops, "DatasetV2"):
+ dataset_types = (dataset_ops.DatasetV2,)
+ if hasattr(dataset_ops, "DatasetV1"):
+ dataset_types = dataset_types + (dataset_ops.DatasetV1,)
+ return isinstance(data, dataset_types)
+ else:
+ return False
+
+
+def is_generator_like(data):
+ # Checks if data is a generator, Sequence, or Iterator.
+
+ types = (tf.keras.utils.Sequence,)
+ iterator_ops = wandb.util.get_module("tensorflow.python.data.ops.iterator_ops")
+ if iterator_ops:
+ types = types + (iterator_ops.Iterator,)
+ # EagerIterator was in tensorflow < 2
+ if hasattr(iterator_ops, "EagerIterator"):
+ types = types + (iterator_ops.EagerIterator,)
+ elif hasattr(iterator_ops, "IteratorV2"):
+ types = types + (iterator_ops.IteratorV2,)
+ return hasattr(data, "next") or hasattr(data, "__next__") or isinstance(data, types)
+
+
+def patch_tf_keras(): # noqa: C901
+ from packaging.version import parse
+ from tensorflow.python.eager import context
+
+ if parse("2.6.0") <= parse(tf.__version__) < parse("2.13.0"):
+ keras_engine = "keras.engine"
+ try:
+ from keras.engine import training
+ from keras.engine import training_arrays_v1 as training_arrays
+ from keras.engine import training_generator_v1 as training_generator
+ except (ImportError, AttributeError):
+ wandb.termerror("Unable to patch Tensorflow/Keras")
+ logger.exception("exception while trying to patch_tf_keras")
+ return
+ else:
+ keras_engine = "tensorflow.python.keras.engine"
+
+ from tensorflow.python.keras.engine import training
+
+ try:
+ from tensorflow.python.keras.engine import (
+ training_arrays_v1 as training_arrays,
+ )
+ from tensorflow.python.keras.engine import (
+ training_generator_v1 as training_generator,
+ )
+ except (ImportError, AttributeError):
+ try:
+ from tensorflow.python.keras.engine import (
+ training_arrays,
+ training_generator,
+ )
+ except (ImportError, AttributeError):
+ wandb.termerror("Unable to patch Tensorflow/Keras")
+ logger.exception("exception while trying to patch_tf_keras")
+ return
+
+ # Tensorflow 2.1
+ training_v2_1 = wandb.util.get_module("tensorflow.python.keras.engine.training_v2")
+ # Tensorflow 2.2
+ training_v2_2 = wandb.util.get_module(f"{keras_engine}.training_v1")
+
+ if training_v2_1:
+ old_v2 = training_v2_1.Loop.fit
+ elif training_v2_2:
+ old_v2 = training.Model.fit
+
+ old_arrays = training_arrays.fit_loop
+ old_generator = training_generator.fit_generator
+
+ def set_wandb_attrs(cbk, val_data):
+ if isinstance(cbk, WandbCallback):
+ if is_generator_like(val_data):
+ cbk.generator = val_data
+ elif is_dataset(val_data):
+ if context.executing_eagerly():
+ cbk.generator = iter(val_data)
+ else:
+ wandb.termwarn(
+ "Found a validation dataset in graph mode, can't patch Keras."
+ )
+ elif isinstance(val_data, tuple) and isinstance(val_data[0], tf.Tensor):
+ # Graph mode dataset generator
+ def gen():
+ while True:
+ yield K.get_session().run(val_data)
+
+ cbk.generator = gen()
+ else:
+ cbk.validation_data = val_data
+
+ def new_arrays(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_inputs = kwargs.get("val_inputs")
+ val_targets = kwargs.get("val_targets")
+ # TODO: these could be generators, why index 0?
+ if val_inputs and val_targets:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, (val_inputs[0], val_targets[0]))
+ return old_arrays(*args, **kwargs)
+
+ def new_generator(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_data = kwargs.get("validation_data")
+ if val_data:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, val_data)
+ return old_generator(*args, **kwargs)
+
+ def new_v2(*args, **kwargs):
+ cbks = kwargs.get("callbacks", [])
+ val_data = kwargs.get("validation_data")
+ if val_data:
+ for cbk in cbks:
+ set_wandb_attrs(cbk, val_data)
+ return old_v2(*args, **kwargs)
+
+ training_arrays.orig_fit_loop = old_arrays
+ training_arrays.fit_loop = new_arrays
+ training_generator.orig_fit_generator = old_generator
+ training_generator.fit_generator = new_generator
+ wandb.patched["keras"].append([f"{keras_engine}.training_arrays", "fit_loop"])
+ wandb.patched["keras"].append(
+ [f"{keras_engine}.training_generator", "fit_generator"]
+ )
+
+ if training_v2_1:
+ training_v2_1.Loop.fit = new_v2
+ wandb.patched["keras"].append(
+ ["tensorflow.python.keras.engine.training_v2.Loop", "fit"]
+ )
+ elif training_v2_2:
+ training.Model.fit = new_v2
+ wandb.patched["keras"].append([f"{keras_engine}.training.Model", "fit"])
+
+
+def _array_has_dtype(array):
+ return hasattr(array, "dtype")
+
+
+def _update_if_numeric(metrics, key, values):
+ if not _array_has_dtype(values):
+ _warn_not_logging(key)
+ return
+
+ if not is_numeric_array(values):
+ _warn_not_logging_non_numeric(key)
+ return
+
+ metrics[key] = wandb.Histogram(values)
+
+
+def is_numeric_array(array):
+ return np.issubdtype(array.dtype, np.number)
+
+
+def _warn_not_logging_non_numeric(name):
+ wandb.termwarn(
+ f"Non-numeric values found in layer: {name}, not logging this layer",
+ repeat=False,
+ )
+
+
+def _warn_not_logging(name):
+ wandb.termwarn(
+ f"Layer {name} has undetermined datatype not logging this layer",
+ repeat=False,
+ )
+
+
+tf_logger = tf.get_logger()
+
+patch_tf_keras()
+
+
+### For gradient logging ###
+
+
+def _get_custom_optimizer_parent_class():
+ from packaging.version import parse
+
+ if parse(tf.__version__) >= parse("2.9.0"):
+ custom_optimizer_parent_class = tf.keras.optimizers.legacy.Optimizer
+ else:
+ custom_optimizer_parent_class = tf.keras.optimizers.Optimizer
+
+ return custom_optimizer_parent_class
+
+
+_custom_optimizer_parent_class = _get_custom_optimizer_parent_class()
+
+
+class _CustomOptimizer(_custom_optimizer_parent_class):
+ def __init__(self):
+ super().__init__(name="CustomOptimizer")
+ self._resource_apply_dense = tf.function(self._resource_apply_dense)
+ self._resource_apply_sparse = tf.function(self._resource_apply_sparse)
+
+ def _resource_apply_dense(self, grad, var):
+ var.assign(grad)
+
+ # this needs to be implemented to prevent a NotImplementedError when
+ # using Lookup layers.
+ def _resource_apply_sparse(self, grad, var, indices):
+ pass
+
+ def get_config(self):
+ return super().get_config()
+
+
+class _GradAccumulatorCallback(tf.keras.callbacks.Callback):
+ """Accumulates gradients during a fit() call when used in conjunction with the CustomOptimizer above."""
+
+ def set_model(self, model):
+ super().set_model(model)
+ self.og_weights = model.get_weights()
+ self.grads = [np.zeros(tuple(w.shape)) for w in model.trainable_weights]
+
+ def on_batch_end(self, batch, logs=None):
+ for g, w in zip(self.grads, self.model.trainable_weights):
+ g += w.numpy()
+ self.model.set_weights(self.og_weights)
+
+ def get_grads(self):
+ return [g.copy() for g in self.grads]
+
+
+###
+
+
+class WandbCallback(tf.keras.callbacks.Callback):
+ """`WandbCallback` automatically integrates keras with wandb.
+
+ Example:
+ ```python
+ model.fit(
+ X_train,
+ y_train,
+ validation_data=(X_test, y_test),
+ callbacks=[WandbCallback()],
+ )
+ ```
+
+ `WandbCallback` will automatically log history data from any
+ metrics collected by keras: loss and anything passed into `keras_model.compile()`.
+
+ `WandbCallback` will set summary metrics for the run associated with the "best" training
+ step, where "best" is defined by the `monitor` and `mode` attributes. This defaults
+ to the epoch with the minimum `val_loss`. `WandbCallback` will by default save the model
+ associated with the best `epoch`.
+
+ `WandbCallback` can optionally log gradient and parameter histograms.
+
+ `WandbCallback` can optionally save training and validation data for wandb to visualize.
+
+ Args:
+ monitor: (str) name of metric to monitor. Defaults to `val_loss`.
+ mode: (str) one of {`auto`, `min`, `max`}.
+ `min` - save model when monitor is minimized
+ `max` - save model when monitor is maximized
+ `auto` - try to guess when to save the model (default).
+ save_model:
+ True - save a model when monitor beats all previous epochs
+ False - don't save models
+ save_graph: (boolean) if True save model graph to wandb (default to True).
+ save_weights_only: (boolean) if True, then only the model's weights will be
+ saved (`model.save_weights(filepath)`), else the full model
+ is saved (`model.save(filepath)`).
+ log_weights: (boolean) if True save histograms of the model's layer's weights.
+ log_gradients: (boolean) if True log histograms of the training gradients
+ training_data: (tuple) Same format `(X,y)` as passed to `model.fit`. This is needed
+ for calculating gradients - this is mandatory if `log_gradients` is `True`.
+ validation_data: (tuple) Same format `(X,y)` as passed to `model.fit`. A set of data
+ for wandb to visualize. If this is set, every epoch, wandb will
+ make a small number of predictions and save the results for later visualization. In case
+ you are working with image data, please also set `input_type` and `output_type` in order
+ to log correctly.
+ generator: (generator) a generator that returns validation data for wandb to visualize. This
+ generator should return tuples `(X,y)`. Either `validate_data` or generator should
+ be set for wandb to visualize specific data examples. In case you are working with image data,
+ please also set `input_type` and `output_type` in order to log correctly.
+ validation_steps: (int) if `validation_data` is a generator, how many
+ steps to run the generator for the full validation set.
+ labels: (list) If you are visualizing your data with wandb this list of labels
+ will convert numeric output to understandable string if you are building a
+ multiclass classifier. If you are making a binary classifier you can pass in
+ a list of two labels ["label for false", "label for true"]. If `validate_data`
+ and generator are both false, this won't do anything.
+ predictions: (int) the number of predictions to make for visualization each epoch, max
+ is 100.
+ input_type: (string) type of the model input to help visualization. can be one of:
+ (`image`, `images`, `segmentation_mask`, `auto`).
+ output_type: (string) type of the model output to help visualization. can be one of:
+ (`image`, `images`, `segmentation_mask`, `label`).
+ log_evaluation: (boolean) if True, save a Table containing validation data and the
+ model's predictions at each epoch. See `validation_indexes`,
+ `validation_row_processor`, and `output_row_processor` for additional details.
+ class_colors: ([float, float, float]) if the input or output is a segmentation mask,
+ an array containing an rgb tuple (range 0-1) for each class.
+ log_batch_frequency: (integer) if None, callback will log every epoch.
+ If set to integer, callback will log training metrics every `log_batch_frequency`
+ batches.
+ log_best_prefix: (string) if None, no extra summary metrics will be saved.
+ If set to a string, the monitored metric and epoch will be prepended with this value
+ and stored as summary metrics.
+ validation_indexes: ([wandb.data_types._TableLinkMixin]) an ordered list of index keys to associate
+ with each validation example. If log_evaluation is True and `validation_indexes` is provided,
+ then a Table of validation data will not be created and instead each prediction will
+ be associated with the row represented by the `TableLinkMixin`. The most common way to obtain
+ such keys are is use `Table.get_index()` which will return a list of row keys.
+ validation_row_processor: (Callable) a function to apply to the validation data, commonly used to visualize the data.
+ The function will receive an `ndx` (int) and a `row` (dict). If your model has a single input,
+ then `row["input"]` will be the input data for the row. Else, it will be keyed based on the name of the
+ input slot. If your fit function takes a single target, then `row["target"]` will be the target data for the row. Else,
+ it will be keyed based on the name of the output slots. For example, if your input data is a single ndarray,
+ but you wish to visualize the data as an Image, then you can provide `lambda ndx, row: {"img": wandb.Image(row["input"])}`
+ as the processor. Ignored if log_evaluation is False or `validation_indexes` are present.
+ output_row_processor: (Callable) same as `validation_row_processor`, but applied to the model's output. `row["output"]` will contain
+ the results of the model output.
+ infer_missing_processors: (bool) Determines if `validation_row_processor` and `output_row_processor`
+ should be inferred if missing. Defaults to True. If `labels` are provided, we will attempt to infer classification-type
+ processors where appropriate.
+ log_evaluation_frequency: (int) Determines the frequency which evaluation results will be logged. Default 0 (only at the end of training).
+ Set to 1 to log every epoch, 2 to log every other epoch, and so on. Has no effect when log_evaluation is False.
+ compute_flops: (bool) Compute the FLOPs of your Keras Sequential or Functional model in GigaFLOPs unit.
+ """
+
+ def __init__(
+ self,
+ monitor="val_loss",
+ verbose=0,
+ mode="auto",
+ save_weights_only=False,
+ log_weights=False,
+ log_gradients=False,
+ save_model=True,
+ training_data=None,
+ validation_data=None,
+ labels=None,
+ predictions=36,
+ generator=None,
+ input_type=None,
+ output_type=None,
+ log_evaluation=False,
+ validation_steps=None,
+ class_colors=None,
+ log_batch_frequency=None,
+ log_best_prefix="best_",
+ save_graph=True,
+ validation_indexes=None,
+ validation_row_processor=None,
+ prediction_row_processor=None,
+ infer_missing_processors=True,
+ log_evaluation_frequency=0,
+ compute_flops=False,
+ **kwargs,
+ ):
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ deprecate(
+ field_name=Deprecated.keras_callback,
+ warning_message=(
+ "WandbCallback is deprecated and will be removed in a future release. "
+ "Please use the WandbMetricsLogger, WandbModelCheckpoint, and WandbEvalCallback "
+ "callbacks instead. "
+ "See https://docs.wandb.ai/guides/integrations/keras for more information."
+ ),
+ )
+
+ with wandb.wandb_lib.telemetry.context(run=wandb.run) as tel:
+ tel.feature.keras = True
+ self.validation_data = None
+ # This is kept around for legacy reasons
+ if validation_data is not None:
+ if is_generator_like(validation_data):
+ generator = validation_data
+ else:
+ self.validation_data = validation_data
+ if labels is None:
+ labels = []
+ self.labels = labels
+ self.predictions = min(predictions, 100)
+
+ self.monitor = monitor
+ self.verbose = verbose
+ self.save_weights_only = save_weights_only
+ self.save_graph = save_graph
+
+ wandb.save("model-best.h5")
+ self.filepath = os.path.join(wandb.run.dir, "model-best.h5")
+ self.save_model = save_model
+ if save_model:
+ deprecate(
+ field_name=Deprecated.keras_callback__save_model,
+ warning_message=(
+ "The save_model argument by default saves the model in the HDF5 format that cannot save "
+ "custom objects like subclassed models and custom layers. This behavior will be deprecated "
+ "in a future release in favor of the SavedModel format. Meanwhile, the HDF5 model is saved "
+ "as W&B files and the SavedModel as W&B Artifacts."
+ ),
+ )
+
+ self.save_model_as_artifact = True
+ self.log_weights = log_weights
+ self.log_gradients = log_gradients
+ self.training_data = training_data
+ self.generator = generator
+ self._graph_rendered = False
+
+ data_type = kwargs.get("data_type", None)
+ if data_type is not None:
+ deprecate(
+ field_name=Deprecated.keras_callback__data_type,
+ warning_message=(
+ "The data_type argument of wandb.keras.WandbCallback is deprecated "
+ "and will be removed in a future release. Please use input_type instead.\n"
+ "Setting input_type = data_type."
+ ),
+ )
+ input_type = data_type
+ self.input_type = input_type
+ self.output_type = output_type
+ self.log_evaluation = log_evaluation
+ self.validation_steps = validation_steps
+ self.class_colors = np.array(class_colors) if class_colors is not None else None
+ self.log_batch_frequency = log_batch_frequency
+ self.log_best_prefix = log_best_prefix
+ self.compute_flops = compute_flops
+
+ self._prediction_batch_size = None
+
+ if self.log_gradients:
+ if int(tf.__version__.split(".")[0]) < 2:
+ raise Exception("Gradient logging requires tensorflow 2.0 or higher.")
+ if self.training_data is None:
+ raise ValueError(
+ "training_data argument is required for gradient logging."
+ )
+ if isinstance(self.training_data, (list, tuple)):
+ if len(self.training_data) != 2:
+ raise ValueError("training data must be a tuple of length two")
+ self._training_data_x, self._training_data_y = self.training_data
+ else:
+ self._training_data_x = (
+ self.training_data
+ ) # generator, tf.data.Dataset etc
+ self._training_data_y = None
+
+ # From Keras
+ if mode not in ["auto", "min", "max"]:
+ wandb.termwarn(
+ f"WandbCallback mode {mode} is unknown, fallback to auto mode."
+ )
+ mode = "auto"
+
+ if mode == "min":
+ self.monitor_op = operator.lt
+ self.best = float("inf")
+ elif mode == "max":
+ self.monitor_op = operator.gt
+ self.best = float("-inf")
+ else:
+ if "acc" in self.monitor or self.monitor.startswith("fmeasure"):
+ self.monitor_op = operator.gt
+ self.best = float("-inf")
+ else:
+ self.monitor_op = operator.lt
+ self.best = float("inf")
+ # Get the previous best metric for resumed runs
+ previous_best = wandb.run.summary.get(f"{self.log_best_prefix}{self.monitor}")
+ if previous_best is not None:
+ self.best = previous_best
+
+ self._validation_data_logger = None
+ self._validation_indexes = validation_indexes
+ self._validation_row_processor = validation_row_processor
+ self._prediction_row_processor = prediction_row_processor
+ self._infer_missing_processors = infer_missing_processors
+ self._log_evaluation_frequency = log_evaluation_frequency
+ self._model_trained_since_last_eval = False
+
+ def _build_grad_accumulator_model(self):
+ inputs = self.model.inputs
+ outputs = self.model(inputs)
+ grad_acc_model = tf.keras.models.Model(inputs, outputs)
+ grad_acc_model.compile(loss=self.model.loss, optimizer=_CustomOptimizer())
+
+ # make sure magic doesn't think this is a user model
+ grad_acc_model._wandb_internal_model = True
+
+ self._grad_accumulator_model = grad_acc_model
+ self._grad_accumulator_callback = _GradAccumulatorCallback()
+
+ def _implements_train_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def _implements_test_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def _implements_predict_batch_hooks(self):
+ return self.log_batch_frequency is not None
+
+ def set_params(self, params):
+ self.params = params
+
+ def set_model(self, model):
+ super().set_model(model)
+ if self.input_type == "auto" and len(model.inputs) == 1:
+ self.input_type = wandb.util.guess_data_type(
+ model.inputs[0].shape, risky=True
+ )
+ if self.input_type and self.output_type is None and len(model.outputs) == 1:
+ self.output_type = wandb.util.guess_data_type(model.outputs[0].shape)
+ if self.log_gradients:
+ self._build_grad_accumulator_model()
+
+ def _attempt_evaluation_log(self, commit=True):
+ if self.log_evaluation and self._validation_data_logger:
+ try:
+ if not self.model:
+ wandb.termwarn("WandbCallback unable to read model from trainer")
+ else:
+ self._validation_data_logger.log_predictions(
+ predictions=self._validation_data_logger.make_predictions(
+ self.model.predict
+ ),
+ commit=commit,
+ )
+ self._model_trained_since_last_eval = False
+ except Exception as e:
+ wandb.termwarn("Error during prediction logging for epoch: " + str(e))
+
+ def on_epoch_end(self, epoch, logs=None):
+ if logs is None:
+ logs = {}
+ if self.log_weights:
+ wandb.log(self._log_weights(), commit=False)
+
+ if self.log_gradients:
+ wandb.log(self._log_gradients(), commit=False)
+
+ if self.input_type in (
+ "image",
+ "images",
+ "segmentation_mask",
+ ) or self.output_type in ("image", "images", "segmentation_mask"):
+ if self.generator:
+ self.validation_data = next(self.generator)
+ if self.validation_data is None:
+ wandb.termwarn(
+ "No validation_data set, pass a generator to the callback."
+ )
+ elif self.validation_data and len(self.validation_data) > 0:
+ wandb.log(
+ {"examples": self._log_images(num_images=self.predictions)},
+ commit=False,
+ )
+
+ if (
+ self._log_evaluation_frequency > 0
+ and epoch % self._log_evaluation_frequency == 0
+ ):
+ self._attempt_evaluation_log(commit=False)
+
+ wandb.log({"epoch": epoch}, commit=False)
+ wandb.log(logs, commit=True)
+
+ self.current = logs.get(self.monitor)
+ if self.current and self.monitor_op(self.current, self.best):
+ if self.log_best_prefix:
+ wandb.run.summary[f"{self.log_best_prefix}{self.monitor}"] = (
+ self.current
+ )
+ wandb.run.summary["{}{}".format(self.log_best_prefix, "epoch")] = epoch
+ if self.verbose and not self.save_model:
+ wandb.termlog(
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}"
+ )
+ if self.save_model:
+ self._save_model(epoch)
+
+ if self.save_model and self.save_model_as_artifact:
+ self._save_model_as_artifact(epoch)
+
+ self.best = self.current
+
+ # This is what keras used pre tensorflow.keras
+ def on_batch_begin(self, batch, logs=None):
+ pass
+
+ # This is what keras used pre tensorflow.keras
+ def on_batch_end(self, batch, logs=None):
+ if self.save_graph and not self._graph_rendered:
+ # Couldn't do this in train_begin because keras may still not be built
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
+ self._graph_rendered = True
+
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
+ wandb.log(logs, commit=True)
+
+ def on_train_batch_begin(self, batch, logs=None):
+ self._model_trained_since_last_eval = True
+
+ def on_train_batch_end(self, batch, logs=None):
+ if self.save_graph and not self._graph_rendered:
+ # Couldn't do this in train_begin because keras may still not be built
+ wandb.run.summary["graph"] = wandb.Graph.from_keras(self.model)
+ self._graph_rendered = True
+
+ if self.log_batch_frequency and batch % self.log_batch_frequency == 0:
+ wandb.log(logs, commit=True)
+
+ def on_test_begin(self, logs=None):
+ pass
+
+ def on_test_end(self, logs=None):
+ pass
+
+ def on_test_batch_begin(self, batch, logs=None):
+ pass
+
+ def on_test_batch_end(self, batch, logs=None):
+ pass
+
+ def on_train_begin(self, logs=None):
+ if self.log_evaluation:
+ try:
+ validation_data = None
+ if self.validation_data:
+ validation_data = self.validation_data
+ elif self.generator:
+ if not self.validation_steps:
+ wandb.termwarn(
+ "WandbCallback is unable to log validation data. "
+ "When using a generator for validation_data, you must pass validation_steps"
+ )
+ else:
+ x = None
+ y_true = None
+ for _ in range(self.validation_steps):
+ bx, by_true = next(self.generator)
+ if x is None:
+ x, y_true = bx, by_true
+ else:
+ x, y_true = (
+ np.append(x, bx, axis=0),
+ np.append(y_true, by_true, axis=0),
+ )
+ validation_data = (x, y_true)
+ else:
+ wandb.termwarn(
+ "WandbCallback is unable to read validation_data from trainer "
+ "and therefore cannot log validation data. Ensure Keras is properly "
+ "patched by calling `from wandb.keras import WandbCallback` at the top of your script."
+ )
+ if validation_data:
+ self._validation_data_logger = ValidationDataLogger(
+ inputs=validation_data[0],
+ targets=validation_data[1],
+ indexes=self._validation_indexes,
+ validation_row_processor=self._validation_row_processor,
+ prediction_row_processor=self._prediction_row_processor,
+ class_labels=self.labels,
+ infer_missing_processors=self._infer_missing_processors,
+ )
+ except Exception as e:
+ wandb.termwarn(
+ "Error initializing ValidationDataLogger in WandbCallback. "
+ f"Skipping logging validation data. Error: {str(e)}"
+ )
+
+ if self.compute_flops and _can_compute_flops():
+ try:
+ wandb.summary["GFLOPs"] = self.get_flops()
+ except Exception:
+ logger.exception("Error computing FLOPs")
+ wandb.termwarn("Unable to compute FLOPs for this model.")
+
+ def on_train_end(self, logs=None):
+ if self._model_trained_since_last_eval:
+ self._attempt_evaluation_log()
+
+ def on_predict_begin(self, logs=None):
+ pass
+
+ def on_predict_end(self, logs=None):
+ pass
+
+ def on_predict_batch_begin(self, batch, logs=None):
+ pass
+
+ def on_predict_batch_end(self, batch, logs=None):
+ pass
+
+ def _logits_to_captions(self, logits):
+ if logits[0].shape[-1] == 1:
+ # Scalar output from the model
+ # TODO: handle validation_y
+ if len(self.labels) == 2:
+ # User has named true and false
+ captions = [
+ self.labels[1] if logits[0] > 0.5 else self.labels[0]
+ for logit in logits
+ ]
+ else:
+ if len(self.labels) != 0:
+ wandb.termwarn(
+ "keras model is producing a single output, "
+ 'so labels should be a length two array: ["False label", "True label"].'
+ )
+ captions = [logit[0] for logit in logits]
+ else:
+ # Vector output from the model
+ # TODO: handle validation_y
+ labels = np.argmax(np.stack(logits), axis=1)
+
+ if len(self.labels) > 0:
+ # User has named the categories in self.labels
+ captions = []
+ for label in labels:
+ try:
+ captions.append(self.labels[label])
+ except IndexError:
+ captions.append(label)
+ else:
+ captions = labels
+ return captions
+
+ def _masks_to_pixels(self, masks):
+ # if its a binary mask, just return it as grayscale instead of picking the argmax
+ if len(masks[0].shape) == 2 or masks[0].shape[-1] == 1:
+ return masks
+ class_colors = (
+ self.class_colors
+ if self.class_colors is not None
+ else np.array(wandb.util.class_colors(masks[0].shape[2]))
+ )
+ imgs = class_colors[np.argmax(masks, axis=-1)]
+ return imgs
+
+ def _log_images(self, num_images=36):
+ validation_X = self.validation_data[0] # noqa: N806
+ validation_y = self.validation_data[1]
+
+ validation_length = len(validation_X)
+
+ if validation_length > num_images:
+ # pick some data at random
+ indices = np.random.choice(validation_length, num_images, replace=False)
+ else:
+ indices = range(validation_length)
+
+ test_data = []
+ test_output = []
+ for i in indices:
+ test_example = validation_X[i]
+ test_data.append(test_example)
+ test_output.append(validation_y[i])
+
+ if self.model.stateful:
+ predictions = self.model.predict(np.stack(test_data), batch_size=1)
+ self.model.reset_states()
+ else:
+ predictions = self.model.predict(
+ np.stack(test_data), batch_size=self._prediction_batch_size
+ )
+ if len(predictions) != len(test_data):
+ self._prediction_batch_size = 1
+ predictions = self.model.predict(
+ np.stack(test_data), batch_size=self._prediction_batch_size
+ )
+
+ if self.input_type == "label":
+ if self.output_type in ("image", "images", "segmentation_mask"):
+ captions = self._logits_to_captions(test_data)
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ output_images = [
+ wandb.Image(data, caption=captions[i], grouping=2)
+ for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data, caption=captions[i])
+ for i, data in enumerate(reference_image_data)
+ ]
+ return list(chain.from_iterable(zip(output_images, reference_images)))
+ elif self.input_type in ("image", "images", "segmentation_mask"):
+ input_image_data = (
+ self._masks_to_pixels(test_data)
+ if self.input_type == "segmentation_mask"
+ else test_data
+ )
+ if self.output_type == "label":
+ # we just use the predicted label as the caption for now
+ captions = self._logits_to_captions(predictions)
+ return [
+ wandb.Image(data, caption=captions[i])
+ for i, data in enumerate(test_data)
+ ]
+ elif self.output_type in ("image", "images", "segmentation_mask"):
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ input_images = [
+ wandb.Image(data, grouping=3)
+ for i, data in enumerate(input_image_data)
+ ]
+ output_images = [
+ wandb.Image(data) for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
+ ]
+ return list(
+ chain.from_iterable(
+ zip(input_images, output_images, reference_images)
+ )
+ )
+ else:
+ # unknown output, just log the input images
+ return [wandb.Image(img) for img in test_data]
+ elif self.output_type in ("image", "images", "segmentation_mask"):
+ # unknown input, just log the predicted and reference outputs without captions
+ output_image_data = (
+ self._masks_to_pixels(predictions)
+ if self.output_type == "segmentation_mask"
+ else predictions
+ )
+ reference_image_data = (
+ self._masks_to_pixels(test_output)
+ if self.output_type == "segmentation_mask"
+ else test_output
+ )
+ output_images = [
+ wandb.Image(data, grouping=2)
+ for i, data in enumerate(output_image_data)
+ ]
+ reference_images = [
+ wandb.Image(data) for i, data in enumerate(reference_image_data)
+ ]
+ return list(chain.from_iterable(zip(output_images, reference_images)))
+
+ def _log_weights(self):
+ metrics = {}
+ for layer in self.model.layers:
+ weights = layer.get_weights()
+ if len(weights) == 1:
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
+ )
+ elif len(weights) == 2:
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".weights", weights[0]
+ )
+ _update_if_numeric(
+ metrics, "parameters/" + layer.name + ".bias", weights[1]
+ )
+ return metrics
+
+ def _log_gradients(self):
+ # Suppress callback warnings grad accumulator
+ og_level = tf_logger.level
+ tf_logger.setLevel("ERROR")
+
+ self._grad_accumulator_model.fit(
+ self._training_data_x,
+ self._training_data_y,
+ verbose=0,
+ callbacks=[self._grad_accumulator_callback],
+ )
+ tf_logger.setLevel(og_level)
+ weights = self.model.trainable_weights
+ grads = self._grad_accumulator_callback.grads
+ metrics = {}
+ for weight, grad in zip(weights, grads):
+ metrics["gradients/" + weight.name.split(":")[0] + ".gradient"] = (
+ wandb.Histogram(grad)
+ )
+ return metrics
+
+ def _log_dataframe(self):
+ x, y_true, y_pred = None, None, None
+
+ if self.validation_data:
+ x, y_true = self.validation_data[0], self.validation_data[1]
+ y_pred = self.model.predict(x)
+ elif self.generator:
+ if not self.validation_steps:
+ wandb.termwarn(
+ "when using a generator for validation data with dataframes, "
+ "you must pass validation_steps. skipping"
+ )
+ return None
+
+ for _ in range(self.validation_steps):
+ bx, by_true = next(self.generator)
+ by_pred = self.model.predict(bx)
+ if x is None:
+ x, y_true, y_pred = bx, by_true, by_pred
+ else:
+ x, y_true, y_pred = (
+ np.append(x, bx, axis=0),
+ np.append(y_true, by_true, axis=0),
+ np.append(y_pred, by_pred, axis=0),
+ )
+
+ if self.input_type in ("image", "images") and self.output_type == "label":
+ return wandb.image_categorizer_dataframe(
+ x=x, y_true=y_true, y_pred=y_pred, labels=self.labels
+ )
+ elif (
+ self.input_type in ("image", "images")
+ and self.output_type == "segmentation_mask"
+ ):
+ return wandb.image_segmentation_dataframe(
+ x=x,
+ y_true=y_true,
+ y_pred=y_pred,
+ labels=self.labels,
+ class_colors=self.class_colors,
+ )
+ else:
+ wandb.termwarn(
+ f"unknown dataframe type for input_type={self.input_type} and output_type={self.output_type}"
+ )
+ return None
+
+ def _save_model(self, epoch):
+ if wandb.run.disabled:
+ return
+ if self.verbose > 0:
+ wandb.termlog(
+ f"Epoch {epoch:05d}: {self.monitor} improved from {self.best:.5f} to {self.current:.5f}, "
+ f"saving model to {self.filepath}"
+ )
+
+ try:
+ if self.save_weights_only:
+ self.model.save_weights(self.filepath, overwrite=True)
+ else:
+ self.model.save(self.filepath, overwrite=True)
+ # Was getting `RuntimeError: Unable to create link` in TF 1.13.1
+ # also saw `TypeError: can't pickle _thread.RLock objects`
+ except (ImportError, RuntimeError, TypeError, AttributeError):
+ logger.exception("Error saving model in the h5py format")
+ wandb.termerror(
+ "Can't save model in the h5py format. The model will be saved as "
+ "as an W&B Artifact in the 'tf' format."
+ )
+
+ def _save_model_as_artifact(self, epoch):
+ if wandb.run.disabled:
+ return
+
+ # Save the model in the SavedModel format.
+ # TODO: Replace this manual artifact creation with the `log_model` method
+ # after `log_model` is released from beta.
+ self.model.save(self.filepath[:-3], overwrite=True, save_format="tf")
+
+ # Log the model as artifact.
+ name = wandb.util.make_artifact_name_safe(f"model-{wandb.run.name}")
+ model_artifact = wandb.Artifact(name, type="model")
+ model_artifact.add_dir(self.filepath[:-3])
+ wandb.run.log_artifact(model_artifact, aliases=["latest", f"epoch_{epoch}"])
+
+ # Remove the SavedModel from wandb dir as we don't want to log it to save memory.
+ shutil.rmtree(self.filepath[:-3])
+
+ def get_flops(self) -> float:
+ """Calculate FLOPS [GFLOPs] for a tf.keras.Model or tf.keras.Sequential model in inference mode.
+
+ It uses tf.compat.v1.profiler under the hood.
+ """
+ if not hasattr(self, "model"):
+ raise wandb.Error("self.model must be set before using this method.")
+
+ if not isinstance(
+ self.model, (tf.keras.models.Sequential, tf.keras.models.Model)
+ ):
+ raise TypeError(
+ "Calculating FLOPS is only supported for "
+ "`tf.keras.Model` and `tf.keras.Sequential` instances."
+ )
+
+ from tensorflow.python.framework.convert_to_constants import (
+ convert_variables_to_constants_v2_as_graph,
+ )
+
+ # Compute FLOPs for one sample
+ batch_size = 1
+ inputs = [
+ tf.TensorSpec([batch_size] + inp.shape[1:], inp.dtype)
+ for inp in self.model.inputs
+ ]
+
+ # convert tf.keras model into frozen graph to count FLOPs about operations used at inference
+ real_model = tf.function(self.model).get_concrete_function(inputs)
+ frozen_func, _ = convert_variables_to_constants_v2_as_graph(real_model)
+
+ # Calculate FLOPs with tf.profiler
+ run_meta = tf.compat.v1.RunMetadata()
+ opts = (
+ tf.compat.v1.profiler.ProfileOptionBuilder(
+ tf.compat.v1.profiler.ProfileOptionBuilder().float_operation()
+ )
+ .with_empty_output()
+ .build()
+ )
+
+ flops = tf.compat.v1.profiler.profile(
+ graph=frozen_func.graph, run_meta=run_meta, cmd="scope", options=opts
+ )
+
+ # convert to GFLOPs
+ return (flops.total_float_ops / 1e9) / 2
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f3a362ca0fc895bce03dccdfeaa3274a9b5963d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__init__.py
@@ -0,0 +1,6 @@
+__all__ = ["wandb_log", "unpatch_kfp"]
+
+from .kfp_patch import patch_kfp, unpatch_kfp
+from .wandb_logging import wandb_log
+
+patch_kfp()
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ed592f268c110eaa2d0ba1b1b41aba304acc020
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddd52f04d8b1bc2e80eae751d441b81108ab6cca
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/kfp_patch.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/kfp_patch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be006acfeb0584e3ad7160ab7bf0869caffacf99
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/kfp_patch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/wandb_logging.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/wandb_logging.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a70ab554acf91a47a30d2ecba7d06aa4ef423b0b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/kfp/__pycache__/wandb_logging.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/helpers.py b/venv/lib/python3.10/site-packages/wandb/integration/kfp/helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..feebcc62ea3688a2a93818adb445f6454a6d9dc2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/kfp/helpers.py
@@ -0,0 +1,28 @@
+import json
+
+
+def add_wandb_visualization(run, mlpipeline_ui_metadata_path):
+ """NOTE: To use this, you must modify your component to have an output called `mlpipeline_ui_metadata_path` AND call `wandb.init` yourself inside that component.
+
+ Example usage:
+
+ def my_component(..., mlpipeline_ui_metadata_path: OutputPath()):
+ import wandb
+ from wandb.integration.kfp.helpers import add_wandb_visualization
+
+ with wandb.init() as run:
+ add_wandb_visualization(run, mlpipeline_ui_metadata_path)
+
+ ... # the rest of your code here
+ """
+
+ def get_iframe_html(run):
+ return f''
+
+ iframe_html = get_iframe_html(run)
+ metadata = {
+ "outputs": [{"type": "markdown", "storage": "inline", "source": iframe_html}]
+ }
+
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
+ json.dump(metadata, metadata_file)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py b/venv/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py
new file mode 100644
index 0000000000000000000000000000000000000000..367b03afd0fd673250328fe3882fb8c2fef0550c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/kfp/kfp_patch.py
@@ -0,0 +1,335 @@
+import inspect
+import itertools
+import textwrap
+from typing import Callable, List, Mapping, Optional
+
+import wandb
+
+try:
+ from kfp import __version__ as kfp_version
+ from kfp.components import structures
+ from kfp.components._components import _create_task_factory_from_component_spec
+ from kfp.components._python_op import _func_to_component_spec
+ from packaging.version import parse
+
+ MIN_KFP_VERSION = "1.6.1"
+
+ if parse(kfp_version) < parse(MIN_KFP_VERSION):
+ wandb.termwarn(
+ f"Your version of kfp {kfp_version} may not work. This integration requires kfp>={MIN_KFP_VERSION}"
+ )
+
+except ImportError:
+ wandb.termerror("kfp not found! Please `pip install kfp`")
+
+from .wandb_logging import wandb_log
+
+decorator_code = inspect.getsource(wandb_log)
+wandb_logging_extras = f"""
+import typing
+from typing import NamedTuple
+
+import collections
+from collections import namedtuple
+
+import kfp
+from kfp import components
+from kfp.components import InputPath, OutputPath
+
+import wandb
+
+{decorator_code}
+"""
+
+
+def full_path_exists(full_func):
+ def get_parent_child_pairs(full_func):
+ components = full_func.split(".")
+ parents, children = [], []
+ for i, _ in enumerate(components[:-1], 1):
+ parent = ".".join(components[:i])
+ child = components[i]
+ parents.append(parent)
+ children.append(child)
+ return zip(parents, children)
+
+ for parent, child in get_parent_child_pairs(full_func):
+ module = wandb.util.get_module(parent)
+ if not module or not hasattr(module, child) or getattr(module, child) is None:
+ return False
+ return True
+
+
+def patch(module_name, func):
+ module = wandb.util.get_module(module_name)
+ success = False
+
+ full_func = f"{module_name}.{func.__name__}"
+ if not full_path_exists(full_func):
+ wandb.termerror(
+ f"Failed to patch {module_name}.{func.__name__}! Please check if this package/module is installed!"
+ )
+ else:
+ wandb.patched.setdefault(module.__name__, [])
+ # if already patched, do not patch again
+ if [module, func.__name__] not in wandb.patched[module.__name__]:
+ setattr(module, f"orig_{func.__name__}", getattr(module, func.__name__))
+ setattr(module, func.__name__, func)
+ wandb.patched[module.__name__].append([module, func.__name__])
+ success = True
+
+ return success
+
+
+def unpatch(module_name):
+ if module_name in wandb.patched:
+ for module, func in wandb.patched[module_name]:
+ setattr(module, func, getattr(module, f"orig_{func}"))
+ wandb.patched[module_name] = []
+
+
+def unpatch_kfp():
+ unpatch("kfp.components")
+ unpatch("kfp.components._python_op")
+ unpatch("wandb.integration.kfp")
+
+
+def patch_kfp():
+ to_patch = [
+ (
+ "kfp.components",
+ create_component_from_func,
+ ),
+ (
+ "kfp.components._python_op",
+ create_component_from_func,
+ ),
+ (
+ "kfp.components._python_op",
+ _get_function_source_definition,
+ ),
+ ("kfp.components._python_op", strip_type_hints),
+ ]
+
+ successes = []
+ for module_name, func in to_patch:
+ success = patch(module_name, func)
+ successes.append(success)
+ if not all(successes):
+ wandb.termerror(
+ "Failed to patch one or more kfp functions. Patching @wandb_log decorator to no-op."
+ )
+ patch("wandb.integration.kfp", wandb_log)
+
+
+def wandb_log(
+ func=None,
+ # /, # py38 only
+ log_component_file=True,
+):
+ """Wrap a standard python function and log to W&B.
+
+ NOTE: Because patching failed, this decorator is a no-op.
+ """
+ from functools import wraps
+
+ def decorator(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
+
+
+def _get_function_source_definition(func: Callable) -> str:
+ """Get the source code of a function.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L300-L319.
+ """
+ func_code = inspect.getsource(func)
+
+ # Function might be defined in some indented scope (e.g. in another
+ # function). We need to handle this and properly dedent the function source
+ # code
+ func_code = textwrap.dedent(func_code)
+ func_code_lines = func_code.split("\n")
+
+ # For wandb, allow decorators (so we can use the @wandb_log decorator)
+ func_code_lines = itertools.dropwhile(
+ lambda x: not (x.startswith(("def", "@wandb_log"))),
+ func_code_lines,
+ )
+
+ if not func_code_lines:
+ raise ValueError(
+ f'Failed to dedent and clean up the source of function "{func.__name__}". '
+ "It is probably not properly indented."
+ )
+
+ return "\n".join(func_code_lines)
+
+
+def create_component_from_func(
+ func: Callable,
+ output_component_file: Optional[str] = None,
+ base_image: Optional[str] = None,
+ packages_to_install: Optional[List[str]] = None,
+ annotations: Optional[Mapping[str, str]] = None,
+):
+ '''Convert a Python function to a component and returns a task factory.
+
+ The returned task factory accepts arguments and returns a task object.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L998-L1110.
+
+ Args:
+ func: The python function to convert
+ base_image: Optional. Specify a custom Docker container image to use in the component. For lightweight components, the image needs to have python 3.5+. Default is the python image corresponding to the current python environment.
+ output_component_file: Optional. Write a component definition to a local file. The produced component file can be loaded back by calling :code:`load_component_from_file` or :code:`load_component_from_uri`.
+ packages_to_install: Optional. List of [versioned] python packages to pip install before executing the user function.
+ annotations: Optional. Allows adding arbitrary key-value data to the component specification.
+
+ Returns:
+ A factory function with a strongly-typed signature taken from the python function.
+ Once called with the required arguments, the factory constructs a task instance that can run the original function in a container.
+
+ Examples:
+ The function name and docstring are used as component name and description. Argument and return annotations are used as component input/output types::
+
+ def add(a: float, b: float) -> float:
+ """Return sum of two arguments"""
+ return a + b
+
+
+ # add_op is a task factory function that creates a task object when given arguments
+ add_op = create_component_from_func(
+ func=add,
+ base_image="python:3.7", # Optional
+ output_component_file="add.component.yaml", # Optional
+ packages_to_install=["pandas==0.24"], # Optional
+ )
+
+ # The component spec can be accessed through the .component_spec attribute:
+ add_op.component_spec.save("add.component.yaml")
+
+ # The component function can be called with arguments to create a task:
+ add_task = add_op(1, 3)
+
+ # The resulting task has output references, corresponding to the component outputs.
+ # When the function only has a single anonymous return value, the output name is "Output":
+ sum_output_ref = add_task.outputs["Output"]
+
+ # These task output references can be passed to other component functions, constructing a computation graph:
+ task2 = add_op(sum_output_ref, 5)
+
+
+ :code:`create_component_from_func` function can also be used as decorator::
+
+ @create_component_from_func
+ def add_op(a: float, b: float) -> float:
+ """Return sum of two arguments"""
+ return a + b
+
+ To declare a function with multiple return values, use the :code:`NamedTuple` return annotation syntax::
+
+ from typing import NamedTuple
+
+
+ def add_multiply_two_numbers(a: float, b: float) -> NamedTuple(
+ "Outputs", [("sum", float), ("product", float)]
+ ):
+ """Return sum and product of two arguments"""
+ return (a + b, a * b)
+
+
+ add_multiply_op = create_component_from_func(add_multiply_two_numbers)
+
+ # The component function can be called with arguments to create a task:
+ add_multiply_task = add_multiply_op(1, 3)
+
+ # The resulting task has output references, corresponding to the component outputs:
+ sum_output_ref = add_multiply_task.outputs["sum"]
+
+ # These task output references can be passed to other component functions, constructing a computation graph:
+ task2 = add_multiply_op(sum_output_ref, 5)
+
+ Bigger data should be read from files and written to files.
+ Use the :py:class:`kfp.components.InputPath` parameter annotation to tell the system that the function wants to consume the corresponding input data as a file. The system will download the data, write it to a local file and then pass the **path** of that file to the function.
+ Use the :py:class:`kfp.components.OutputPath` parameter annotation to tell the system that the function wants to produce the corresponding output data as a file. The system will prepare and pass the **path** of a file where the function should write the output data. After the function exits, the system will upload the data to the storage system so that it can be passed to downstream components.
+
+ You can specify the type of the consumed/produced data by specifying the type argument to :py:class:`kfp.components.InputPath` and :py:class:`kfp.components.OutputPath`. The type can be a python type or an arbitrary type name string. :code:`OutputPath('CatBoostModel')` means that the function states that the data it has written to a file has type :code:`CatBoostModel`. :code:`InputPath('CatBoostModel')` means that the function states that it expect the data it reads from a file to have type 'CatBoostModel'. When the pipeline author connects inputs to outputs the system checks whether the types match.
+ Every kind of data can be consumed as a file input. Conversely, bigger data should not be consumed by value as all value inputs pass through the command line.
+
+ Example of a component function declaring file input and output::
+
+ def catboost_train_classifier(
+ training_data_path: InputPath(
+ "CSV"
+ ), # Path to input data file of type "CSV"
+ trained_model_path: OutputPath(
+ "CatBoostModel"
+ ), # Path to output data file of type "CatBoostModel"
+ number_of_trees: int = 100, # Small output of type "Integer"
+ ) -> NamedTuple(
+ "Outputs",
+ [
+ ("Accuracy", float), # Small output of type "Float"
+ ("Precision", float), # Small output of type "Float"
+ ("JobUri", "URI"), # Small output of type "URI"
+ ],
+ ):
+ """Train CatBoost classification model"""
+ ...
+
+ return (accuracy, precision, recall)
+ '''
+ core_packages = ["wandb", "kfp"]
+
+ if not packages_to_install:
+ packages_to_install = core_packages
+ else:
+ packages_to_install += core_packages
+
+ component_spec = _func_to_component_spec(
+ func=func,
+ extra_code=wandb_logging_extras,
+ base_image=base_image,
+ packages_to_install=packages_to_install,
+ )
+ if annotations:
+ component_spec.metadata = structures.MetadataSpec(
+ annotations=annotations,
+ )
+
+ if output_component_file:
+ component_spec.save(output_component_file)
+
+ return _create_task_factory_from_component_spec(component_spec)
+
+
+def strip_type_hints(source_code: str) -> str:
+ """Strip type hints from source code.
+
+ This function is modified from KFP. The original source is below:
+ https://github.com/kubeflow/pipelines/blob/b6406b02f45cdb195c7b99e2f6d22bf85b12268b/sdk/python/kfp/components/_python_op.py#L237-L248.
+ """
+ # For wandb, do not strip type hints
+
+ # try:
+ # return _strip_type_hints_using_lib2to3(source_code)
+ # except Exception as ex:
+ # print('Error when stripping type annotations: ' + str(ex))
+
+ # try:
+ # return _strip_type_hints_using_strip_hints(source_code)
+ # except Exception as ex:
+ # print('Error when stripping type annotations: ' + str(ex))
+
+ return source_code
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py b/venv/lib/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d0edf3eac211b59908bc3aa4849a459c2da2148
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/kfp/wandb_logging.py
@@ -0,0 +1,182 @@
+def wandb_log( # noqa: C901
+ func=None,
+ # /, # py38 only
+ log_component_file=True,
+):
+ """Wrap a standard python function and log to W&B."""
+ import json
+ import os
+ from functools import wraps
+ from inspect import Parameter, signature
+
+ from kfp import components
+ from kfp.components import (
+ InputArtifact,
+ InputBinaryFile,
+ InputPath,
+ InputTextFile,
+ OutputArtifact,
+ OutputBinaryFile,
+ OutputPath,
+ OutputTextFile,
+ )
+
+ import wandb
+ from wandb.sdk.lib import telemetry as wb_telemetry
+
+ output_types = (OutputArtifact, OutputBinaryFile, OutputPath, OutputTextFile)
+ input_types = (InputArtifact, InputBinaryFile, InputPath, InputTextFile)
+
+ def isinstance_namedtuple(x):
+ t = type(x)
+ b = t.__bases__
+ if len(b) != 1 or b[0] is not tuple:
+ return False
+ f = getattr(t, "_fields", None)
+ if not isinstance(f, tuple):
+ return False
+ return all(isinstance(n, str) for n in f)
+
+ def get_iframe_html(run):
+ return f''
+
+ def get_link_back_to_kubeflow():
+ wandb_kubeflow_url = os.getenv("WANDB_KUBEFLOW_URL")
+ return f"{wandb_kubeflow_url}/#/runs/details/{{workflow.uid}}"
+
+ def log_input_scalar(name, data, run=None):
+ run.config[name] = data
+ wandb.termlog(f"Setting config: {name} to {data}")
+
+ def log_input_artifact(name, data, type, run=None):
+ artifact = wandb.Artifact(name, type=type)
+ artifact.add_file(data)
+ run.use_artifact(artifact)
+ wandb.termlog(f"Using artifact: {name}")
+
+ def log_output_scalar(name, data, run=None):
+ if isinstance_namedtuple(data):
+ for k, v in zip(data._fields, data):
+ run.log({f"{func.__name__}.{k}": v})
+ else:
+ run.log({name: data})
+
+ def log_output_artifact(name, data, type, run=None):
+ artifact = wandb.Artifact(name, type=type)
+ artifact.add_file(data)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name}")
+
+ def _log_component_file(func, run=None):
+ name = func.__name__
+ output_component_file = f"{name}.yml"
+ components._python_op.func_to_component_file(func, output_component_file)
+ artifact = wandb.Artifact(name, type="kubeflow_component_file")
+ artifact.add_file(output_component_file)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging component file: {output_component_file}")
+
+ # Add `mlpipeline_ui_metadata_path` to signature to show W&B run in "ML Visualizations tab"
+ sig = signature(func)
+ no_default = []
+ has_default = []
+
+ for param in sig.parameters.values():
+ if param.default is param.empty:
+ no_default.append(param)
+ else:
+ has_default.append(param)
+
+ new_params = tuple(
+ (
+ *no_default,
+ Parameter(
+ "mlpipeline_ui_metadata_path",
+ annotation=OutputPath(),
+ kind=Parameter.POSITIONAL_OR_KEYWORD,
+ ),
+ *has_default,
+ )
+ )
+ new_sig = sig.replace(parameters=new_params)
+ new_anns = {param.name: param.annotation for param in new_params}
+ if "return" in func.__annotations__:
+ new_anns["return"] = func.__annotations__["return"]
+
+ def decorator(func):
+ input_scalars = {}
+ input_artifacts = {}
+ output_scalars = {}
+ output_artifacts = {}
+
+ for name, ann in func.__annotations__.items():
+ if name == "return":
+ output_scalars[name] = ann
+ elif isinstance(ann, output_types):
+ output_artifacts[name] = ann
+ elif isinstance(ann, input_types):
+ input_artifacts[name] = ann
+ else:
+ input_scalars[name] = ann
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ bound = new_sig.bind(*args, **kwargs)
+ bound.apply_defaults()
+
+ mlpipeline_ui_metadata_path = bound.arguments["mlpipeline_ui_metadata_path"]
+ del bound.arguments["mlpipeline_ui_metadata_path"]
+
+ with wandb.init(
+ job_type=func.__name__,
+ group="{{workflow.annotations.pipelines.kubeflow.org/run_name}}",
+ ) as run:
+ # Link back to the kfp UI
+ kubeflow_url = get_link_back_to_kubeflow()
+ run.notes = kubeflow_url
+ run.config["LINK_TO_KUBEFLOW_RUN"] = kubeflow_url
+
+ iframe_html = get_iframe_html(run)
+ metadata = {
+ "outputs": [
+ {
+ "type": "markdown",
+ "storage": "inline",
+ "source": iframe_html,
+ }
+ ]
+ }
+
+ with open(mlpipeline_ui_metadata_path, "w") as metadata_file:
+ json.dump(metadata, metadata_file)
+
+ if log_component_file:
+ _log_component_file(func, run=run)
+
+ for name, _ in input_scalars.items():
+ log_input_scalar(name, kwargs[name], run)
+
+ for name, ann in input_artifacts.items():
+ log_input_artifact(name, kwargs[name], ann.type, run)
+
+ with wb_telemetry.context(run=run) as tel:
+ tel.feature.kfp_wandb_log = True
+
+ result = func(*bound.args, **bound.kwargs)
+
+ for name, _ in output_scalars.items():
+ log_output_scalar(name, result, run)
+
+ for name, ann in output_artifacts.items():
+ log_output_artifact(name, kwargs[name], ann.type, run)
+
+ return result
+
+ wrapper.__signature__ = new_sig
+ wrapper.__annotations__ = new_anns
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/langchain/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaec971a312e9369e1740f0b31e31782bb9b9e3f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("WandbTracer",)
+
+from .wandb_tracer import WandbTracer
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13ff83d9dddf0e1ee515023ce8b604e020ae8ff5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70b1359bb0afbbbd0df43e811c874feb4f7ca051
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py b/venv/lib/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c9a5ff31ce4d1effd6f2d28101b328257f0c577
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/langchain/wandb_tracer.py
@@ -0,0 +1,49 @@
+"""This module contains an integration with the LangChain library.
+
+Specifically, it exposes a `WandbTracer` class that can be used to stream
+LangChain activity to W&B. The intended usage pattern is to call
+`tracer = WandbTracer()` at the top of the script/notebook, and call
+`tracer.finish()` at the end of the script/notebook.
+ This will stream all LangChain activity to W&B.
+
+Technical Note:
+LangChain is in very rapid development - meaning their APIs and schemas are actively changing.
+As a matter of precaution, any call to LangChain apis, or use of their returned data is wrapped
+in a try/except block. This is to ensure that if a breaking change is introduced, the W&B
+integration will not break user code. The one exception to the rule is at import time. If
+LangChain is not installed, or the symbols are not in the same place, the appropriate error
+will be raised when importing this module.
+"""
+
+from packaging import version
+
+import wandb.util
+from wandb.proto.wandb_deprecated import Deprecated
+from wandb.sdk.lib import deprecate
+
+langchain = wandb.util.get_module(
+ name="langchain",
+ required="To use the LangChain WandbTracer you need to have the `langchain` python "
+ "package installed. Please install it with `pip install langchain`.",
+)
+
+if version.parse(langchain.__version__) < version.parse("0.0.188"):
+ raise ValueError(
+ "The Weights & Biases Langchain integration does not support versions 0.0.187 and lower. "
+ "To ensure proper functionality, please use version 0.0.188 or higher."
+ )
+
+# isort: off
+from langchain.callbacks.tracers import WandbTracer # noqa: E402
+
+
+class WandbTracer(WandbTracer):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ deprecate.deprecate(
+ field_name=Deprecated.langchain_tracer,
+ warning_message="This feature is deprecated and has been moved to `langchain`. Enable tracing by setting "
+ "LANGCHAIN_WANDB_TRACING=true in your environment. See the documentation at "
+ "https://python.langchain.com/docs/ecosystem/integrations/agent_with_wandb_tracing for guidance. "
+ "Replace your current import with `from langchain.callbacks.tracers import WandbTracer`.",
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc1029563baa721fbdbc2c2809974b59203008ee
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__init__.py
@@ -0,0 +1,239 @@
+"""W&B callback for lightgbm.
+
+Really simple callback to get logging for each tree
+
+Example usage:
+
+param_list = [("eta", 0.08), ("max_depth", 6), ("subsample", 0.8), ("colsample_bytree", 0.8), ("alpha", 8), ("num_class", 10)]
+config.update(dict(param_list))
+lgb = lgb.train(param_list, d_train, callbacks=[wandb_callback()])
+"""
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Callable
+
+import lightgbm # type: ignore
+from lightgbm import Booster
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+MINIMIZE_METRICS = [
+ "l1",
+ "l2",
+ "rmse",
+ "mape",
+ "huber",
+ "fair",
+ "poisson",
+ "gamma",
+ "binary_logloss",
+]
+
+MAXIMIZE_METRICS = ["map", "auc", "average_precision"]
+
+
+if TYPE_CHECKING:
+ from typing import Any, Dict, List, NamedTuple, Tuple, Union
+
+ # Note: upstream lightgbm has this defined incorrectly
+ _EvalResultTuple = Union[
+ Tuple[str, str, float, bool], Tuple[str, str, float, bool, float]
+ ]
+
+ class CallbackEnv(NamedTuple):
+ model: Any
+ params: Dict
+ iteration: int
+ begin_interation: int
+ end_iteration: int
+ evaluation_result_list: List[_EvalResultTuple]
+
+
+def _define_metric(data: str, metric_name: str) -> None:
+ """Capture model performance at the best step.
+
+ instead of the last step, of training in your `wandb.summary`
+ """
+ if "loss" in str.lower(metric_name):
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
+ elif str.lower(metric_name) in MINIMIZE_METRICS:
+ wandb.define_metric(f"{data}_{metric_name}", summary="min")
+ elif str.lower(metric_name) in MAXIMIZE_METRICS:
+ wandb.define_metric(f"{data}_{metric_name}", summary="max")
+
+
+def _checkpoint_artifact(
+ model: "Booster", iteration: int, aliases: "List[str]"
+) -> None:
+ """Upload model checkpoint as W&B artifact."""
+ # NOTE: type ignore required because wandb.run is improperly inferred as None type
+ model_name = f"model_{wandb.run.id}" # type: ignore
+ model_path = Path(wandb.run.dir) / f"model_ckpt_{iteration}.txt" # type: ignore
+
+ model.save_model(model_path, num_iteration=iteration)
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact, aliases=aliases)
+
+
+def _log_feature_importance(model: "Booster") -> None:
+ """Log feature importance."""
+ feat_imps = model.feature_importance()
+ feats = model.feature_name()
+ fi_data = [[feat, feat_imp] for feat, feat_imp in zip(feats, feat_imps)]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ },
+ commit=False,
+ )
+
+
+class _WandbCallback:
+ """Internal class to handle `wandb_callback` logic.
+
+ This callback is adapted form the LightGBM's `_RecordEvaluationCallback`.
+ """
+
+ def __init__(self, log_params: bool = True, define_metric: bool = True) -> None:
+ self.order = 20
+ self.before_iteration = False
+ self.log_params = log_params
+ self.define_metric_bool = define_metric
+
+ def _init(self, env: "CallbackEnv") -> None:
+ with wb_telemetry.context() as tel:
+ tel.feature.lightgbm_wandb_callback = True
+
+ # log the params as W&B config.
+ if self.log_params:
+ wandb.config.update(env.params)
+
+ # use `define_metric` to set the wandb summary to the best metric value.
+ for item in env.evaluation_result_list:
+ if self.define_metric_bool:
+ if len(item) == 4:
+ data_name, eval_name = item[:2]
+ _define_metric(data_name, eval_name)
+ else:
+ data_name, eval_name = item[1].split()
+ _define_metric(data_name, f"{eval_name}-mean")
+ _define_metric(data_name, f"{eval_name}-stdv")
+
+ def __call__(self, env: "CallbackEnv") -> None:
+ if env.iteration == env.begin_iteration: # type: ignore
+ self._init(env)
+
+ for item in env.evaluation_result_list:
+ if len(item) == 4:
+ data_name, eval_name, result = item[:3]
+ wandb.log(
+ {data_name + "_" + eval_name: result},
+ commit=False,
+ )
+ else:
+ data_name, eval_name = item[1].split()
+ res_mean = item[2]
+ res_stdv = item[4]
+ wandb.log(
+ {
+ data_name + "_" + eval_name + "-mean": res_mean,
+ data_name + "_" + eval_name + "-stdv": res_stdv,
+ },
+ commit=False,
+ )
+
+ # call `commit=True` to log the data as a single W&B step.
+ wandb.log({"iteration": env.iteration}, commit=True)
+
+
+def wandb_callback(log_params: bool = True, define_metric: bool = True) -> Callable:
+ """Automatically integrates LightGBM with wandb.
+
+ Args:
+ log_params: (boolean) if True (default) logs params passed to lightgbm.train as W&B config
+ define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`
+
+ Passing `wandb_callback` to LightGBM will:
+ - log params passed to lightgbm.train as W&B config (default).
+ - log evaluation metrics collected by LightGBM, such as rmse, accuracy etc to Weights & Biases
+ - Capture the best metric in `wandb.summary` when `define_metric=True` (default).
+
+ Use `log_summary` as an extension of this callback.
+
+ Example:
+ ```python
+ params = {
+ "boosting_type": "gbdt",
+ "objective": "regression",
+ }
+ gbm = lgb.train(
+ params,
+ lgb_train,
+ num_boost_round=10,
+ valid_sets=lgb_eval,
+ valid_names=("validation"),
+ callbacks=[wandb_callback()],
+ )
+ ```
+ """
+ return _WandbCallback(log_params, define_metric)
+
+
+def log_summary(
+ model: Booster, feature_importance: bool = True, save_model_checkpoint: bool = False
+) -> None:
+ """Log useful metrics about lightgbm model after training is done.
+
+ Args:
+ model: (Booster) is an instance of lightgbm.basic.Booster.
+ feature_importance: (boolean) if True (default), logs the feature importance plot.
+ save_model_checkpoint: (boolean) if True saves the best model and upload as W&B artifacts.
+
+ Using this along with `wandb_callback` will:
+
+ - log `best_iteration` and `best_score` as `wandb.summary`.
+ - log feature importance plot.
+ - save and upload your best trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
+
+ Example:
+ ```python
+ params = {
+ "boosting_type": "gbdt",
+ "objective": "regression",
+ }
+ gbm = lgb.train(
+ params,
+ lgb_train,
+ num_boost_round=10,
+ valid_sets=lgb_eval,
+ valid_names=("validation"),
+ callbacks=[wandb_callback()],
+ )
+
+ log_summary(gbm)
+ ```
+ """
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ if not isinstance(model, Booster):
+ raise wandb.Error("Model should be an instance of lightgbm.basic.Booster")
+
+ wandb.run.summary["best_iteration"] = model.best_iteration
+ wandb.run.summary["best_score"] = model.best_score
+
+ # Log feature importance
+ if feature_importance:
+ _log_feature_importance(model)
+
+ if save_model_checkpoint:
+ _checkpoint_artifact(model, model.best_iteration, aliases=["best"])
+
+ with wb_telemetry.context() as tel:
+ tel.feature.lightgbm_log_summary = True
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3969329218059cc9b862cf59fcfc6c2b94dcfbb5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/lightning/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/lightning/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..742e9025a826bdad898bb7f8bb82558eb3c6305b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/lightning/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..eff7554e1131034c637c8cfef591756211b8a898
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__init__.py
@@ -0,0 +1,3 @@
+from wandb.integration.lightning.fabric.logger import WandbLogger
+
+__all__ = ("WandbLogger",)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27a39226ec27bbc28feb990f64f0cb9087e35b96
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/logger.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/logger.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a654a424159dcf1d05c2fda57bb4e62ecc0ca32c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/__pycache__/logger.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..21e326241c75ecfedb2ceb5cd8e39b0bc1c0b0f2
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/lightning/fabric/logger.py
@@ -0,0 +1,763 @@
+import os
+from argparse import Namespace
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, Optional, Union
+
+from packaging import version
+from typing_extensions import override
+
+import wandb
+from wandb import Artifact
+from wandb.sdk.lib import telemetry
+
+try:
+ import lightning
+ import torch.nn as nn
+ from lightning.fabric.loggers.logger import Logger, rank_zero_experiment
+ from lightning.fabric.utilities.exceptions import MisconfigurationException
+ from lightning.fabric.utilities.logger import (
+ _add_prefix,
+ _convert_params,
+ _sanitize_callable_params,
+ )
+ from lightning.fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn
+ from lightning.fabric.utilities.types import _PATH
+ from torch import Tensor
+ from torch.nn import Module
+
+ if version.parse(lightning.__version__) > version.parse("2.1.3"):
+ wandb.termwarn(
+ """This integration is tested and supported for lightning Fabric 2.1.3.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `lightning-fabric`.""",
+ repeat=False,
+ )
+
+ if TYPE_CHECKING:
+ from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint
+
+except ImportError as e:
+ wandb.Error(e)
+
+
+class WandbLogger(Logger):
+ r"""Log using `Weights and Biases `_.
+
+ **Installation and set-up**
+
+ Install with pip:
+
+ .. code-block:: bash
+
+ pip install wandb
+
+ Create a `WandbLogger` instance:
+
+ .. code-block:: python
+
+ from lightning.fabric.loggers import WandbLogger
+
+ wandb_logger = WandbLogger(project="MNIST")
+
+ Pass the logger instance to the `Trainer`:
+
+ .. code-block:: python
+
+ trainer = Trainer(logger=wandb_logger)
+
+ A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`.
+
+ **Log metrics**
+
+ Log from :class:`~lightning.pytorch.core.LightningModule`:
+
+ .. code-block:: python
+
+ class LitModule(LightningModule):
+ def training_step(self, batch, batch_idx):
+ self.log("train/loss", loss)
+
+ Use directly wandb module:
+
+ .. code-block:: python
+
+ wandb.log({"train/loss": loss})
+
+ **Log hyper-parameters**
+
+ Save :class:`~lightning.pytorch.core.LightningModule` parameters:
+
+ .. code-block:: python
+
+ class LitModule(LightningModule):
+ def __init__(self, *args, **kwarg):
+ self.save_hyperparameters()
+
+ Add other config parameters:
+
+ .. code-block:: python
+
+ # add one parameter
+ wandb_logger.experiment.config["key"] = value
+
+ # add multiple parameters
+ wandb_logger.experiment.config.update({key1: val1, key2: val2})
+
+ # use directly wandb module
+ wandb.config["key"] = value
+ wandb.config.update()
+
+ **Log gradients, parameters and model topology**
+
+ Call the `watch` method for automatically tracking gradients:
+
+ .. code-block:: python
+
+ # log gradients and model topology
+ wandb_logger.watch(model)
+
+ # log gradients, parameter histogram and model topology
+ wandb_logger.watch(model, log="all")
+
+ # change log frequency of gradients and parameters (100 steps by default)
+ wandb_logger.watch(model, log_freq=500)
+
+ # do not log graph (in case of errors)
+ wandb_logger.watch(model, log_graph=False)
+
+ The `watch` method adds hooks to the model which can be removed at the end of training:
+
+ .. code-block:: python
+
+ wandb_logger.experiment.unwatch(model)
+
+ **Log model checkpoints**
+
+ Log model checkpoints at the end of training:
+
+ .. code-block:: python
+
+ wandb_logger = WandbLogger(log_model=True)
+
+ Log model checkpoints as they get created during training:
+
+ .. code-block:: python
+
+ wandb_logger = WandbLogger(log_model="all")
+
+ Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`:
+
+ .. code-block:: python
+
+ # log model only if `val_accuracy` increases
+ wandb_logger = WandbLogger(log_model="all")
+ checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
+ trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])
+
+ `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint:
+
+ .. code-block:: python
+
+ # reference can be retrieved in artifacts panel
+ # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
+ checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"
+
+ # download checkpoint locally (if not already cached)
+ run = wandb.init(project="MNIST")
+ artifact = run.use_artifact(checkpoint_reference, type="model")
+ artifact_dir = artifact.download()
+
+ # load checkpoint
+ model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")
+
+ **Log media**
+
+ Log text with:
+
+ .. code-block:: python
+
+ # using columns and data
+ columns = ["input", "label", "prediction"]
+ data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
+ wandb_logger.log_text(key="samples", columns=columns, data=data)
+
+ # using a pandas DataFrame
+ wandb_logger.log_text(key="samples", dataframe=my_dataframe)
+
+ Log images with:
+
+ .. code-block:: python
+
+ # using tensors, numpy arrays or PIL images
+ wandb_logger.log_image(key="samples", images=[img1, img2])
+
+ # adding captions
+ wandb_logger.log_image(
+ key="samples", images=[img1, img2], caption=["tree", "person"]
+ )
+
+ # using file path
+ wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])
+
+ More arguments can be passed for logging segmentation masks and bounding boxes. Refer to
+ `Image Overlays documentation `_.
+
+ **Log Tables**
+
+ `W&B Tables `_ can be used to log,
+ query and analyze tabular data.
+
+ They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing,
+ understanding and sharing any form of data, from datasets to model predictions.
+
+ .. code-block:: python
+
+ columns = ["caption", "image", "sound"]
+ data = [
+ ["cheese", wandb.Image(img_1), wandb.Audio(snd_1)],
+ ["wine", wandb.Image(img_2), wandb.Audio(snd_2)],
+ ]
+ wandb_logger.log_table(key="samples", columns=columns, data=data)
+
+
+ **Downloading and Using Artifacts**
+
+ To download an artifact without starting a run, call the ``download_artifact``
+ function on the class:
+
+ .. code-block:: python
+
+ artifact_dir = wandb_logger.download_artifact(artifact="path/to/artifact")
+
+ To download an artifact and link it to an ongoing run call the ``download_artifact``
+ function on the logger instance:
+
+ .. code-block:: python
+
+ class MyModule(LightningModule):
+ def any_lightning_module_function_or_hook(self):
+ self.logger.download_artifact(artifact="path/to/artifact")
+
+ To link an artifact from a previous run you can use ``use_artifact`` function:
+
+ .. code-block:: python
+
+ wandb_logger.use_artifact(artifact="path/to/artifact")
+
+ See Also:
+ - `Demo in Google Colab `__ with hyperparameter search and model logging
+ - `W&B Documentation `__
+
+ Args:
+ name: Display name for the run.
+ save_dir: Path where data is saved.
+ version: Sets the version, mainly used to resume a previous run.
+ offline: Run offline (data can be streamed later to wandb servers).
+ dir: Same as save_dir.
+ id: Same as version.
+ anonymous: Enables or explicitly disables anonymous logging.
+ project: The name of the project to which this run will belong. If not set, the environment variable
+ `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``.
+ log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint`
+ as W&B artifacts. `latest` and `best` aliases are automatically set.
+
+ * if ``log_model == 'all'``, checkpoints are logged during training.
+ * if ``log_model == True``, checkpoints are logged at the end of training, except when
+ `~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1``
+ which also logs every checkpoint during training.
+ * if ``log_model == False`` (default), no checkpoint is logged.
+
+ prefix: A string to put at the beginning of metric keys.
+ experiment: WandB experiment object. Automatically set when creating a run.
+ checkpoint_name: Name of the model checkpoint artifact being logged.
+ log_checkpoint_on: When to log model checkpoints as W&B artifacts. Only used if ``log_model`` is ``True``.
+ Options: ``"success"``, ``"all"``. Default: ``"success"``.
+ \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc.
+
+ Raises:
+ ModuleNotFoundError:
+ If required WandB package is not installed on the device.
+ MisconfigurationException:
+ If both ``log_model`` and ``offline`` is set to ``True``.
+
+ """
+
+ LOGGER_JOIN_CHAR = "-"
+
+ def __init__(
+ self,
+ name: Optional[str] = None,
+ save_dir: _PATH = ".",
+ version: Optional[str] = None,
+ offline: bool = False,
+ dir: Optional[_PATH] = None,
+ id: Optional[str] = None,
+ anonymous: Optional[bool] = None,
+ project: Optional[str] = None,
+ log_model: Union[Literal["all"], bool] = False,
+ experiment: Optional["wandb.Run"] = None,
+ prefix: str = "",
+ checkpoint_name: Optional[str] = None,
+ log_checkpoint_on: Union[Literal["success"], Literal["all"]] = "success",
+ **kwargs: Any,
+ ) -> None:
+ if offline and log_model:
+ raise MisconfigurationException(
+ f"Providing log_model={log_model} and offline={offline} is an invalid configuration"
+ " since model checkpoints cannot be uploaded in offline mode.\n"
+ "Hint: Set `offline=False` to log your model."
+ )
+
+ super().__init__()
+ self._offline = offline
+ self._log_model = log_model
+ self._prefix = prefix
+ self._experiment = experiment
+ self._logged_model_time: Dict[str, float] = {}
+ self._checkpoint_callback: Optional[ModelCheckpoint] = None
+
+ # paths are processed as strings
+ if save_dir is not None:
+ save_dir = os.fspath(save_dir)
+ elif dir is not None:
+ dir = os.fspath(dir)
+
+ project = project or os.environ.get("WANDB_PROJECT", "lightning_fabric_logs")
+
+ # set wandb init arguments
+ self._wandb_init: Dict[str, Any] = {
+ "name": name,
+ "project": project,
+ "dir": save_dir or dir,
+ "id": version or id,
+ "resume": "allow",
+ "anonymous": ("allow" if anonymous else None),
+ }
+ self._wandb_init.update(**kwargs)
+ # extract parameters
+ self._project = self._wandb_init.get("project")
+ self._save_dir = self._wandb_init.get("dir")
+ self._name = self._wandb_init.get("name")
+ self._id = self._wandb_init.get("id")
+ self._checkpoint_name = checkpoint_name
+ self._log_checkpoint_on = log_checkpoint_on
+
+ def __getstate__(self) -> Dict[str, Any]:
+ # Hack: If the 'spawn' launch method is used, the logger will get pickled and this `__getstate__` gets called.
+ # We create an experiment here in the main process, and attach to it in the worker process.
+ # Using wandb-service, we persist the same experiment even if multiple `Trainer.fit/test/validate` calls
+ # are made.
+ _ = self.experiment
+
+ state = self.__dict__.copy()
+ # args needed to reload correct experiment
+ if self._experiment is not None:
+ state["_id"] = getattr(self._experiment, "id", None)
+ state["_attach_id"] = getattr(self._experiment, "_attach_id", None)
+ state["_name"] = self._experiment.name
+
+ # cannot be pickled
+ state["_experiment"] = None
+ return state
+
+ @property
+ @rank_zero_experiment
+ def experiment(self) -> "wandb.Run":
+ r"""Actual wandb object.
+
+ To use wandb features in your :class:`~lightning.pytorch.core.LightningModule`, do the
+ following.
+
+ Example::
+
+ .. code-block:: python
+
+ self.logger.experiment.some_wandb_function()
+
+ """
+ if self._experiment is None:
+ if self._offline:
+ os.environ["WANDB_MODE"] = "dryrun"
+
+ attach_id = getattr(self, "_attach_id", None)
+ if wandb.run is not None:
+ # wandb process already created in this instance
+ rank_zero_warn(
+ "There is a wandb run already in progress and newly created instances of `WandbLogger` will reuse"
+ " this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`."
+ )
+ self._experiment = wandb.run
+ elif attach_id is not None and hasattr(wandb, "_attach"):
+ # attach to wandb process referenced
+ self._experiment = wandb._attach(attach_id)
+ else:
+ # create new wandb process
+ self._experiment = wandb.init(**self._wandb_init)
+
+ # define default x-axis
+ if isinstance(self._experiment, wandb.Run) and getattr(
+ self._experiment, "define_metric", None
+ ):
+ self._experiment.define_metric("trainer/global_step")
+ self._experiment.define_metric(
+ "*", step_metric="trainer/global_step", step_sync=True
+ )
+
+ self._experiment._label(repo="lightning_fabric_logger") # pylint: disable=protected-access
+ with telemetry.context(run=self._experiment) as tel:
+ tel.feature.lightning_fabric_logger = True
+ return self._experiment
+
+ def watch(
+ self,
+ model: nn.Module,
+ log: str = "gradients",
+ log_freq: int = 100,
+ log_graph: bool = True,
+ ) -> None:
+ self.experiment.watch(model, log=log, log_freq=log_freq, log_graph=log_graph)
+
+ @override
+ @rank_zero_only
+ def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: # type: ignore[override]
+ params = _convert_params(params)
+ params = _sanitize_callable_params(params)
+ self.experiment.config.update(params, allow_val_change=True)
+
+ @override
+ @rank_zero_only
+ def log_metrics(
+ self, metrics: Mapping[str, float], step: Optional[int] = None
+ ) -> None:
+ assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0"
+
+ metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR)
+ if step is not None:
+ self.experiment.log(dict(metrics, **{"trainer/global_step": step}))
+ else:
+ self.experiment.log(metrics)
+
+ @rank_zero_only
+ def log_table(
+ self,
+ key: str,
+ columns: Optional[List[str]] = None,
+ data: Optional[List[List[Any]]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ ) -> None:
+ """Log a Table containing any object type (text, image, audio, video, molecule, html, etc).
+
+ Can be defined either with `columns` and `data` or with `dataframe`.
+
+ """
+ metrics = {key: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
+ self.log_metrics(metrics, step)
+
+ @rank_zero_only
+ def log_text(
+ self,
+ key: str,
+ columns: Optional[List[str]] = None,
+ data: Optional[List[List[str]]] = None,
+ dataframe: Any = None,
+ step: Optional[int] = None,
+ ) -> None:
+ """Log text as a Table.
+
+ Can be defined either with `columns` and `data` or with `dataframe`.
+
+ """
+ self.log_table(key, columns, data, dataframe, step)
+
+ @rank_zero_only
+ def log_html(
+ self, key: str, htmls: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log html files.
+
+ Optional kwargs are lists passed to each html (ex: inject).
+
+ """
+ if not isinstance(htmls, list):
+ raise TypeError(f'Expected a list as "htmls", found {type(htmls)}')
+ n = len(htmls)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [wandb.Html(html, **kwarg) for html, kwarg in zip(htmls, kwarg_list)]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_image(
+ self, key: str, images: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log images (tensors, numpy arrays, PIL Images or file paths).
+
+ Optional kwargs are lists passed to each image (ex: caption, masks, boxes).
+
+ """
+ if not isinstance(images, list):
+ raise TypeError(f'Expected a list as "images", found {type(images)}')
+ n = len(images)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_audio(
+ self, key: str, audios: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ r"""Log audios (numpy arrays, or file paths).
+
+ Args:
+ key: The key to be used for logging the audio files
+ audios: The list of audio file paths, or numpy arrays to be logged
+ step: The step number to be used for logging the audio files
+ \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).
+
+ Optional kwargs are lists passed to each audio (ex: caption, sample_rate).
+
+ """
+ if not isinstance(audios, list):
+ raise TypeError(f'Expected a list as "audios", found {type(audios)}')
+ n = len(audios)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [
+ wandb.Audio(audio, **kwarg) for audio, kwarg in zip(audios, kwarg_list)
+ ]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @rank_zero_only
+ def log_video(
+ self, key: str, videos: List[Any], step: Optional[int] = None, **kwargs: Any
+ ) -> None:
+ """Log videos (numpy arrays, or file paths).
+
+ Args:
+ key: The key to be used for logging the video files
+ videos: The list of video file paths, or numpy arrays to be logged
+ step: The step number to be used for logging the video files
+ **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).
+
+ Optional kwargs are lists passed to each video (ex: caption, fps, format).
+
+ """
+ if not isinstance(videos, list):
+ raise TypeError(f'Expected a list as "videos", found {type(videos)}')
+ n = len(videos)
+ for k, v in kwargs.items():
+ if len(v) != n:
+ raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
+ kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
+
+ metrics = {
+ key: [
+ wandb.Video(video, **kwarg) for video, kwarg in zip(videos, kwarg_list)
+ ]
+ }
+ self.log_metrics(metrics, step) # type: ignore[arg-type]
+
+ @property
+ @override
+ def save_dir(self) -> Optional[str]:
+ """Gets the save directory.
+
+ Returns:
+ The path to the save directory.
+
+ """
+ return self._save_dir
+
+ @property
+ @override
+ def name(self) -> Optional[str]:
+ """The project name of this experiment.
+
+ Returns:
+ The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s
+ name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead.
+
+ """
+ return self._project
+
+ @property
+ @override
+ def version(self) -> Optional[str]:
+ """Gets the id of the experiment.
+
+ Returns:
+ The id of the experiment if the experiment exists else the id given to the constructor.
+
+ """
+ # don't create an experiment if we don't have one
+ return self._experiment.id if self._experiment else self._id
+
+ @property
+ def log_dir(self) -> Optional[str]:
+ """Gets the save directory.
+
+ Returns:
+ The path to the save directory.
+
+ """
+ return self.save_dir
+
+ @property
+ def group_separator(self) -> str:
+ """Return the default separator used by the logger to group the data into subfolders."""
+ return self.LOGGER_JOIN_CHAR
+
+ @property
+ def root_dir(self) -> Optional[str]:
+ """Return the root directory.
+
+ Return the root directory where all versions of an experiment get saved, or `None` if the logger does not
+ save data locally.
+ """
+ return self.save_dir.parent if self.save_dir else None
+
+ def log_graph(self, model: Module, input_array: Optional[Tensor] = None) -> None:
+ """Record model graph.
+
+ Args:
+ model: the model with an implementation of ``forward``.
+ input_array: input passes to `model.forward`
+
+ This is a noop function and does not perform any operation.
+ """
+ return
+
+ @override
+ def after_save_checkpoint(self, checkpoint_callback: "ModelCheckpoint") -> None:
+ # log checkpoints as artifacts
+ if (
+ self._log_model == "all"
+ or self._log_model is True
+ and checkpoint_callback.save_top_k == -1
+ ):
+ # TODO: Replace with new Fabric Checkpoints system
+ self._scan_and_log_pytorch_checkpoints(checkpoint_callback)
+ elif self._log_model is True:
+ self._checkpoint_callback = checkpoint_callback
+
+ @staticmethod
+ @rank_zero_only
+ def download_artifact(
+ artifact: str,
+ save_dir: Optional[_PATH] = None,
+ artifact_type: Optional[str] = None,
+ use_artifact: Optional[bool] = True,
+ ) -> str:
+ """Downloads an artifact from the wandb server.
+
+ Args:
+ artifact: The path of the artifact to download.
+ save_dir: The directory to save the artifact to.
+ artifact_type: The type of artifact to download.
+ use_artifact: Whether to add an edge between the artifact graph.
+
+ Returns:
+ The path to the downloaded artifact.
+
+ """
+ if wandb.run is not None and use_artifact:
+ artifact = wandb.run.use_artifact(artifact)
+ else:
+ api = wandb.Api()
+ artifact = api.artifact(artifact, type=artifact_type)
+
+ save_dir = None if save_dir is None else os.fspath(save_dir)
+ return artifact.download(root=save_dir)
+
+ def use_artifact(
+ self, artifact: str, artifact_type: Optional[str] = None
+ ) -> "Artifact":
+ """Logs to the wandb dashboard that the mentioned artifact is used by the run.
+
+ Args:
+ artifact: The path of the artifact.
+ artifact_type: The type of artifact being used.
+
+ Returns:
+ wandb Artifact object for the artifact.
+
+ """
+ return self.experiment.use_artifact(artifact, type=artifact_type)
+
+ @override
+ @rank_zero_only
+ def save(self) -> None:
+ """Save log data."""
+ self.experiment.log({}, commit=True)
+
+ @override
+ @rank_zero_only
+ def finalize(self, status: str) -> None:
+ if self._log_checkpoint_on == "success" and status != "success":
+ # Currently, checkpoints only get logged on success
+ return
+ # log checkpoints as artifacts
+ if (
+ self._checkpoint_callback
+ and self._experiment is not None
+ and self._log_checkpoint_on in ["success", "all"]
+ ):
+ self._scan_and_log_pytorch_checkpoints(self._checkpoint_callback)
+
+ def _scan_and_log_pytorch_checkpoints(
+ self, checkpoint_callback: "ModelCheckpoint"
+ ) -> None:
+ from lightning.pytorch.loggers.utilities import _scan_checkpoints
+
+ # get checkpoints to be saved with associated score
+ checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time)
+
+ # log iteratively all new checkpoints
+ for t, p, s, _ in checkpoints:
+ metadata = {
+ "score": s.item() if isinstance(s, Tensor) else s,
+ "original_filename": Path(p).name,
+ checkpoint_callback.__class__.__name__: {
+ k: getattr(checkpoint_callback, k)
+ for k in [
+ "monitor",
+ "mode",
+ "save_last",
+ "save_top_k",
+ "save_weights_only",
+ "_every_n_train_steps",
+ ]
+ # ensure it does not break if `ModelCheckpoint` args change
+ if hasattr(checkpoint_callback, k)
+ },
+ }
+ if not self._checkpoint_name:
+ self._checkpoint_name = f"model-{self.experiment.id}"
+ artifact = wandb.Artifact(
+ name=self._checkpoint_name, type="model", metadata=metadata
+ )
+ artifact.add_file(p, name="model.ckpt")
+ aliases = (
+ ["latest", "best"]
+ if p == checkpoint_callback.best_model_path
+ else ["latest"]
+ )
+ self.experiment.log_model(artifact, aliases=aliases)
+ # remember logged models - timestamp needed in case filename didn't change (lastkckpt or custom name)
+ self._logged_model_time[p] = t
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7dc33daec78edbe8e6c91dc5f1f0b468acabbb7
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__init__.py
@@ -0,0 +1,9 @@
+"""W&B Integration for Metaflow.
+
+Defines a custom step and flow decorator `wandb_log` that automatically logs
+flow parameters and artifacts to W&B.
+"""
+
+from .metaflow import wandb_log, wandb_track, wandb_use
+
+__all__ = ["wandb_log", "wandb_track", "wandb_use"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..567b73ad01d3e4968e987aaf6fa044600102d5ba
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/data_pandas.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/data_pandas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a0e03977760a8f38515753fcfd387e5cf8b11b7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/data_pandas.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..373085e046c542e9fb0a2d155ff6fd94e67dc33b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0237bd8bea14080368378d4b8ff8cc45ca204c7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py
new file mode 100644
index 0000000000000000000000000000000000000000..4653fb1e345f03716f7fd012d4c1fce0d7503767
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/data_pandas.py
@@ -0,0 +1,74 @@
+"""Support for Pandas datatypes.
+
+May raise MissingDependencyError on import.
+"""
+
+from __future__ import annotations
+
+from typing_extensions import Any, TypeGuard
+
+import wandb
+
+from . import errors
+
+try:
+ import pandas as pd
+except ImportError as e:
+ warning = (
+ "`pandas` not installed >>"
+ " @wandb_log(datasets=True) may not auto log your dataset!"
+ )
+ raise errors.MissingDependencyError(warning=warning) from e
+
+
+def is_dataframe(data: Any) -> TypeGuard[pd.DataFrame]:
+ """Returns whether the data is a Pandas DataFrame."""
+ return isinstance(data, pd.DataFrame)
+
+
+def use_dataframe(
+ name: str,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a dependency on a DataFrame input.
+
+ Args:
+ name: Name of the input.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "datasets"
+ assert run
+
+ wandb.termlog(f"Using artifact: {name} (Pandas DataFrame)")
+ run.use_artifact(f"{name}:latest")
+ return None
+
+
+def track_dataframe(
+ name: str,
+ data: pd.DataFrame,
+ run: wandb.Run | None,
+ testing: bool = False,
+) -> str | None:
+ """Log a DataFrame output as an artifact.
+
+ Args:
+ name: The output's name.
+ data: The output's value.
+ run: The run to update.
+ testing: True in unit tests.
+ """
+ if testing:
+ return "pd.DataFrame"
+ assert run
+
+ artifact = wandb.Artifact(name, type="dataset")
+ with artifact.new_file(f"{name}.parquet", "wb") as f:
+ data.to_parquet(f, engine="pyarrow")
+
+ wandb.termlog(f"Logging artifact: {name} (Pandas DataFrame)")
+ run.log_artifact(artifact)
+ return None
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/errors.py b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b0a3ae962cdadde195fa31c6efb4f3d0cc07d5b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/errors.py
@@ -0,0 +1,13 @@
+import wandb
+
+
+class MissingDependencyError(Exception):
+ """An optional dependency is missing."""
+
+ def __init__(self, *args: object, warning: str) -> None:
+ super().__init__(*args)
+ self._wb_warning = warning
+
+ def warn(self) -> None:
+ """Print a warning for the problem."""
+ wandb.termwarn(self._wb_warning)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/metaflow/metaflow.py b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/metaflow.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa5579eebb05f308e78dab56b48c35e8e621cbb
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/metaflow/metaflow.py
@@ -0,0 +1,398 @@
+import inspect
+import pickle
+from functools import wraps
+from pathlib import Path
+from typing import Optional, Union
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+from . import errors
+
+try:
+ from metaflow import current
+except ImportError as e:
+ raise Exception(
+ "Error: `metaflow` not installed >> This integration requires metaflow!"
+ " To fix, please `pip install -Uqq metaflow`"
+ ) from e
+
+
+# Classes for isinstance() checks.
+_NN_MODULE = None
+_BASE_ESTIMATOR = None
+
+try:
+ from . import data_pandas
+except errors.MissingDependencyError as e:
+ e.warn()
+ data_pandas = None
+
+try:
+ import torch
+ import torch.nn as nn
+
+ _NN_MODULE = nn.Module
+
+ def _use_torch_module(
+ name: str,
+ data: nn.Module,
+ run,
+ testing: bool = False,
+ ) -> Optional[str]:
+ if testing:
+ return "models"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+ def _track_torch_module(
+ name: str,
+ data: nn.Module,
+ run,
+ testing: bool = False,
+ ) -> Optional[str]:
+ if testing:
+ return "nn.Module"
+
+ artifact = wandb.Artifact(name, type="model")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ torch.save(data, f)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+except ImportError:
+ wandb.termwarn(
+ "`pytorch` not installed >> @wandb_log(models=True) may not auto log your model!"
+ )
+
+try:
+ from sklearn.base import BaseEstimator
+
+ _BASE_ESTIMATOR = BaseEstimator
+
+ def _use_sklearn_estimator(
+ name: str,
+ data: BaseEstimator,
+ run,
+ testing: bool = False,
+ ) -> Optional[str]:
+ if testing:
+ return "models"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+ def _track_sklearn_estimator(
+ name: str,
+ data: BaseEstimator,
+ run,
+ testing: bool = False,
+ ) -> Optional[str]:
+ if testing:
+ return "BaseEstimator"
+
+ artifact = wandb.Artifact(name, type="model")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ pickle.dump(data, f)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+except ImportError:
+ wandb.termwarn(
+ "`sklearn` not installed >> @wandb_log(models=True) may not auto log your model!"
+ )
+
+
+class ArtifactProxy:
+ def __init__(self, flow):
+ # do this to avoid recursion problem with __setattr__
+ self.__dict__.update(
+ {
+ "flow": flow,
+ "inputs": {},
+ "outputs": {},
+ "base": set(dir(flow)),
+ "params": {p: getattr(flow, p) for p in current.parameter_names},
+ }
+ )
+
+ def __setattr__(self, key, val):
+ self.outputs[key] = val
+ return setattr(self.flow, key, val)
+
+ def __getattr__(self, key):
+ if key not in self.base and key not in self.outputs:
+ self.inputs[key] = getattr(self.flow, key)
+ return getattr(self.flow, key)
+
+
+def _track_scalar(
+ name: str,
+ data: Union[dict, list, set, str, int, float, bool],
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "scalar"
+
+ run.log({name: data})
+ return None
+
+
+def _track_path(
+ name: str,
+ data: Path,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "Path"
+
+ artifact = wandb.Artifact(name, type="dataset")
+ if data.is_dir():
+ artifact.add_dir(data)
+ elif data.is_file():
+ artifact.add_file(data)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+
+def _track_generic(
+ name: str,
+ data,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "generic"
+
+ artifact = wandb.Artifact(name, type="other")
+ with artifact.new_file(f"{name}.pkl", "wb") as f:
+ pickle.dump(data, f)
+ run.log_artifact(artifact)
+ wandb.termlog(f"Logging artifact: {name} ({type(data)})")
+ return None
+
+
+def wandb_track(
+ name: str,
+ data,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ run: Optional[wandb.Run] = None,
+ testing: bool = False,
+) -> Optional[str]:
+ """Track data as wandb artifacts based on type and flags."""
+ # Check for pandas DataFrame
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
+ return data_pandas.track_dataframe(name, data, run, testing)
+
+ # Check for PyTorch Module
+ if _NN_MODULE and isinstance(data, _NN_MODULE) and models:
+ return _track_torch_module(name, data, run, testing)
+
+ # Check for scikit-learn BaseEstimator
+ if _BASE_ESTIMATOR and isinstance(data, _BASE_ESTIMATOR) and models:
+ return _track_sklearn_estimator(name, data, run, testing)
+
+ # Check for Path objects
+ if isinstance(data, Path) and datasets:
+ return _track_path(name, data, run, testing)
+
+ # Check for scalar types
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
+ return _track_scalar(name, data, run, testing)
+
+ # Generic fallback
+ if others:
+ return _track_generic(name, data, run, testing)
+
+ # No action taken
+ return None
+
+
+def wandb_use(
+ name: str,
+ data,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ run=None,
+ testing: bool = False,
+) -> Optional[str]:
+ """Use wandb artifacts based on data type and flags."""
+ # Skip scalar types - nothing to use
+ if isinstance(data, (dict, list, set, str, int, float, bool)):
+ return None
+
+ try:
+ # Check for pandas DataFrame
+ if data_pandas and data_pandas.is_dataframe(data) and datasets:
+ return data_pandas.use_dataframe(name, run, testing)
+
+ # Check for PyTorch Module
+ elif _NN_MODULE and isinstance(data, _NN_MODULE) and models:
+ return _use_torch_module(name, data, run, testing)
+
+ # Check for scikit-learn BaseEstimator
+ elif _BASE_ESTIMATOR and isinstance(data, _BASE_ESTIMATOR) and models:
+ return _use_sklearn_estimator(name, data, run, testing)
+
+ # Check for Path objects
+ elif isinstance(data, Path) and datasets:
+ return _use_path(name, data, run, testing)
+
+ # Generic fallback
+ elif others:
+ return _use_generic(name, data, run, testing)
+
+ else:
+ return None
+
+ except wandb.CommError:
+ wandb.termwarn(
+ f"This artifact ({name}, {type(data)}) does not exist in the wandb datastore!"
+ " If you created an instance inline (e.g. sklearn.ensemble.RandomForestClassifier),"
+ " then you can safely ignore this. Otherwise you may want to check your internet connection!"
+ )
+ return None
+
+
+def _use_path(
+ name: str,
+ data: Path,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "datasets"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+
+def _use_generic(
+ name: str,
+ data,
+ run,
+ testing: bool = False,
+) -> Optional[str]:
+ if testing:
+ return "others"
+
+ run.use_artifact(f"{name}:latest")
+ wandb.termlog(f"Using artifact: {name} ({type(data)})")
+ return None
+
+
+def coalesce(*arg):
+ return next((a for a in arg if a is not None), None)
+
+
+def wandb_log(
+ func=None,
+ /,
+ datasets: bool = False,
+ models: bool = False,
+ others: bool = False,
+ settings: Optional[wandb.Settings] = None,
+):
+ """Automatically log parameters and artifacts to W&B.
+
+ This decorator can be applied to a flow, step, or both:
+
+ - Decorating a step enables or disables logging within that step
+ - Decorating a flow is equivalent to decorating all steps
+ - Decorating a step after decorating its flow overwrites the flow decoration
+
+ Args:
+ func: The step method or flow class to decorate.
+ datasets: Whether to log `pd.DataFrame` and `pathlib.Path`
+ types. Defaults to False.
+ models: Whether to log `nn.Module` and `sklearn.base.BaseEstimator`
+ types. Defaults to False.
+ others: If `True`, log anything pickle-able. Defaults to False.
+ settings: Custom settings to pass to `wandb.init`.
+ If `run_group` is `None`, it is set to `{flow_name}/{run_id}`.
+ If `run_job_type` is `None`, it is set to `{run_job_type}/{step_name}`.
+ """
+
+ @wraps(func)
+ def decorator(func):
+ # If you decorate a class, apply the decoration to all methods in that class
+ if inspect.isclass(func):
+ cls = func
+ for attr in cls.__dict__:
+ if callable(getattr(cls, attr)):
+ if not hasattr(attr, "_base_func"):
+ setattr(cls, attr, decorator(getattr(cls, attr)))
+ return cls
+
+ # prefer the earliest decoration (i.e. method decoration overrides class decoration)
+ if hasattr(func, "_base_func"):
+ return func
+
+ @wraps(func)
+ def wrapper(self, *args, settings=settings, **kwargs):
+ if not isinstance(settings, wandb.sdk.wandb_settings.Settings):
+ settings = wandb.Settings()
+
+ settings.update_from_dict(
+ {
+ "run_group": coalesce(
+ settings.run_group, f"{current.flow_name}/{current.run_id}"
+ ),
+ "run_job_type": coalesce(settings.run_job_type, current.step_name),
+ }
+ )
+
+ with wandb.init(settings=settings) as run:
+ with wb_telemetry.context(run=run) as tel:
+ tel.feature.metaflow = True
+ proxy = ArtifactProxy(self)
+ run.config.update(proxy.params)
+ func(proxy, *args, **kwargs)
+
+ for name, data in proxy.inputs.items():
+ wandb_use(
+ name,
+ data,
+ datasets=datasets,
+ models=models,
+ others=others,
+ run=run,
+ )
+
+ for name, data in proxy.outputs.items():
+ wandb_track(
+ name,
+ data,
+ datasets=datasets,
+ models=models,
+ others=others,
+ run=run,
+ )
+
+ wrapper._base_func = func
+
+ # Add for testing visibility
+ wrapper._kwargs = {
+ "datasets": datasets,
+ "models": models,
+ "others": others,
+ "settings": settings,
+ }
+ return wrapper
+
+ if func is None:
+ return decorator
+ else:
+ return decorator(func)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/openai/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2c216c5f72a7d0310b5cfab98b4c6ff5e0e75e6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/openai/__init__.py
@@ -0,0 +1,3 @@
+__all__ = ("autolog", "WandbLogger")
+
+from .openai import autolog
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba3fd125adf3d099260cfdde003dcb69c14fca20
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/fine_tuning.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/fine_tuning.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4666f8bc62666ab0b3e5905b1397287b14ed1933
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/fine_tuning.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/openai.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/openai.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e7e104646082aa905be9fcde1fd31aa6f246789
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/openai.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e48782f7514dc7f1261c025b785ca70abc6f0aa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py b/venv/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d7430cea8d2da89bd3cdc8e999efa12ebcea64b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/openai/fine_tuning.py
@@ -0,0 +1,480 @@
+import base64
+import datetime
+import io
+import json
+import os
+import re
+import tempfile
+import time
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from packaging.version import parse
+
+import wandb
+from wandb import util
+from wandb.data_types import Table
+from wandb.sdk.lib import telemetry
+
+openai = util.get_module(
+ name="openai",
+ required="This integration requires `openai`. To install, please run `pip install openai`",
+ lazy=False,
+)
+
+if parse(openai.__version__) < parse("1.12.0"):
+ raise wandb.Error(
+ f"This integration requires openai version 1.12.0 and above. Your current version is {openai.__version__} "
+ "To fix, please `pip install -U openai`"
+ )
+
+from openai import OpenAI # noqa: E402
+from openai.types.fine_tuning import FineTuningJob # noqa: E402
+from openai.types.fine_tuning.fine_tuning_job import ( # noqa: E402
+ Error,
+ Hyperparameters,
+)
+
+np = util.get_module(
+ name="numpy",
+ required="`numpy` not installed >> This integration requires numpy! To fix, please `pip install numpy`",
+ lazy=False,
+)
+
+pd = util.get_module(
+ name="pandas",
+ required="`pandas` not installed >> This integration requires pandas! To fix, please `pip install pandas`",
+ lazy=False,
+)
+
+
+class WandbLogger:
+ """Log OpenAI fine-tunes to [Weights & Biases](https://wandb.me/openai-docs)."""
+
+ _wandb_api: Optional[wandb.Api] = None
+ _logged_in: bool = False
+ openai_client: Optional[OpenAI] = None
+ _run: Optional[wandb.Run] = None
+
+ @classmethod
+ def sync(
+ cls,
+ fine_tune_job_id: Optional[str] = None,
+ openai_client: Optional[OpenAI] = None,
+ num_fine_tunes: Optional[int] = None,
+ project: str = "OpenAI-Fine-Tune",
+ entity: Optional[str] = None,
+ overwrite: bool = False,
+ wait_for_job_success: bool = True,
+ log_datasets: bool = True,
+ model_artifact_name: str = "model-metadata",
+ model_artifact_type: str = "model",
+ **kwargs_wandb_init: Dict[str, Any],
+ ) -> str:
+ """Sync fine-tunes to Weights & Biases.
+
+ :param fine_tune_job_id: The id of the fine-tune (optional)
+ :param openai_client: Pass the `OpenAI()` client (optional)
+ :param num_fine_tunes: Number of most recent fine-tunes to log when an fine_tune_job_id is not provided. By default, every fine-tune is synced.
+ :param project: Name of the project where you're sending runs. By default, it is "GPT-3".
+ :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.
+ :param overwrite: Forces logging and overwrite existing wandb run of the same fine-tune.
+ :param wait_for_job_success: Waits for the fine-tune to be complete and then log metrics to W&B. By default, it is True.
+ :param model_artifact_name: Name of the model artifact that is logged
+ :param model_artifact_type: Type of the model artifact that is logged
+ """
+ if openai_client is None:
+ openai_client = OpenAI()
+ cls.openai_client = openai_client
+
+ if fine_tune_job_id:
+ wandb.termlog("Retrieving fine-tune job...")
+ fine_tune = openai_client.fine_tuning.jobs.retrieve(
+ fine_tuning_job_id=fine_tune_job_id
+ )
+ fine_tunes = [fine_tune]
+ else:
+ # get list of fine_tune to log
+ fine_tunes = openai_client.fine_tuning.jobs.list()
+ if not fine_tunes or fine_tunes.data is None:
+ wandb.termwarn("No fine-tune has been retrieved")
+ return
+ # Select the `num_fine_tunes` from the `fine_tunes.data` list.
+ # If `num_fine_tunes` is None, it selects all items in the list (from start to end).
+ # If for example, `num_fine_tunes` is 5, it selects the last 5 items in the list.
+ # Note that the last items in the list are the latest fine-tune jobs.
+ fine_tunes = fine_tunes.data[
+ -num_fine_tunes if num_fine_tunes is not None else None :
+ ]
+
+ # log starting from oldest fine_tune
+ show_individual_warnings = (
+ fine_tune_job_id is not None or num_fine_tunes is not None
+ )
+ fine_tune_logged = []
+ for fine_tune in fine_tunes:
+ fine_tune_id = fine_tune.id
+ # check run with the given `fine_tune_id` has not been logged already
+ run_path = f"{project}/{fine_tune_id}"
+ if entity is not None:
+ run_path = f"{entity}/{run_path}"
+ wandb_run = cls._get_wandb_run(run_path)
+ if wandb_run:
+ wandb_status = wandb_run.summary.get("status")
+ if show_individual_warnings:
+ if wandb_status == "succeeded" and not overwrite:
+ wandb.termwarn(
+ f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}. "
+ "Use `overwrite=True` if you want to overwrite previous run"
+ )
+ elif wandb_status != "succeeded" or overwrite:
+ if wandb_status != "succeeded":
+ wandb.termwarn(
+ f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully"
+ )
+ wandb.termlog(
+ f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten"
+ )
+ overwrite = True
+ if wandb_status == "succeeded" and not overwrite:
+ return
+
+ # check if the user has not created a wandb run externally
+ if wandb.run is None:
+ cls._run = wandb.init(
+ job_type="fine-tune",
+ project=project,
+ entity=entity,
+ name=fine_tune_id,
+ id=fine_tune_id,
+ **kwargs_wandb_init,
+ )
+ else:
+ # if a run exits - created externally
+ cls._run = wandb.run
+
+ if wait_for_job_success:
+ fine_tune = cls._wait_for_job_success(fine_tune)
+
+ cls._log_fine_tune(
+ fine_tune,
+ project,
+ entity,
+ overwrite,
+ show_individual_warnings,
+ log_datasets,
+ model_artifact_name,
+ model_artifact_type,
+ **kwargs_wandb_init,
+ )
+
+ if not show_individual_warnings and not any(fine_tune_logged):
+ wandb.termwarn("No new successful fine-tunes were found")
+
+ return "🎉 wandb sync completed successfully"
+
+ @classmethod
+ def _wait_for_job_success(cls, fine_tune: FineTuningJob) -> FineTuningJob:
+ wandb.termlog("Waiting for the OpenAI fine-tuning job to finish training...")
+ wandb.termlog(
+ "To avoid blocking, you can call `WandbLogger.sync` with `wait_for_job_success=False` after OpenAI training completes."
+ )
+ while True:
+ if fine_tune.status == "succeeded":
+ wandb.termlog(
+ "Fine-tuning finished, logging metrics, model metadata, and run metadata to Weights & Biases"
+ )
+ return fine_tune
+ if fine_tune.status == "failed":
+ wandb.termwarn(
+ f"Fine-tune {fine_tune.id} has failed and will not be logged"
+ )
+ return fine_tune
+ if fine_tune.status == "cancelled":
+ wandb.termwarn(
+ f"Fine-tune {fine_tune.id} was cancelled and will not be logged"
+ )
+ return fine_tune
+ time.sleep(10)
+ fine_tune = cls.openai_client.fine_tuning.jobs.retrieve(
+ fine_tuning_job_id=fine_tune.id
+ )
+
+ @classmethod
+ def _log_fine_tune(
+ cls,
+ fine_tune: FineTuningJob,
+ project: str,
+ entity: Optional[str],
+ overwrite: bool,
+ show_individual_warnings: bool,
+ log_datasets: bool,
+ model_artifact_name: str,
+ model_artifact_type: str,
+ **kwargs_wandb_init: Dict[str, Any],
+ ):
+ fine_tune_id = fine_tune.id
+ status = fine_tune.status
+
+ with telemetry.context(run=cls._run) as tel:
+ tel.feature.openai_finetuning = True
+
+ # check run completed successfully
+ if status != "succeeded":
+ if show_individual_warnings:
+ wandb.termwarn(
+ f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged'
+ )
+ return
+
+ # check results are present
+ try:
+ results_id = fine_tune.result_files[0]
+ try:
+ encoded_results = cls.openai_client.files.content(
+ file_id=results_id
+ ).read()
+ results = base64.b64decode(encoded_results).decode("utf-8")
+ except Exception:
+ # attempt to read as text, works for older jobs
+ results = cls.openai_client.files.content(file_id=results_id).text
+ except openai.NotFoundError:
+ if show_individual_warnings:
+ wandb.termwarn(
+ f"Fine-tune {fine_tune_id} has no results and will not be logged"
+ )
+ return
+
+ # update the config
+ cls._run.config.update(cls._get_config(fine_tune))
+
+ # log results
+ df_results = pd.read_csv(io.StringIO(results))
+ for _, row in df_results.iterrows():
+ metrics = {k: v for k, v in row.items() if not np.isnan(v)}
+ step = metrics.pop("step")
+ if step is not None:
+ step = int(step)
+ cls._run.log(metrics, step=step)
+ fine_tuned_model = fine_tune.fine_tuned_model
+ if fine_tuned_model is not None:
+ cls._run.summary["fine_tuned_model"] = fine_tuned_model
+
+ # training/validation files and fine-tune details
+ cls._log_artifacts(
+ fine_tune,
+ project,
+ entity,
+ log_datasets,
+ overwrite,
+ model_artifact_name,
+ model_artifact_type,
+ )
+
+ # mark run as complete
+ cls._run.summary["status"] = "succeeded"
+
+ cls._run.finish()
+ return True
+
+ @classmethod
+ def _ensure_logged_in(cls):
+ if not cls._logged_in:
+ if wandb.login():
+ cls._logged_in = True
+ else:
+ raise Exception(
+ "It appears you are not currently logged in to Weights & Biases. "
+ "Please run `wandb login` in your terminal or `wandb.login()` in a notebook."
+ "When prompted, you can obtain your API key by visiting wandb.ai/authorize."
+ )
+
+ @classmethod
+ def _get_wandb_run(cls, run_path: str):
+ cls._ensure_logged_in()
+ try:
+ if cls._wandb_api is None:
+ cls._wandb_api = wandb.Api()
+ return cls._wandb_api.run(run_path)
+ except Exception:
+ return None
+
+ @classmethod
+ def _get_wandb_artifact(cls, artifact_path: str):
+ cls._ensure_logged_in()
+ try:
+ if cls._wandb_api is None:
+ cls._wandb_api = wandb.Api()
+ return cls._wandb_api.artifact(artifact_path)
+ except Exception:
+ return None
+
+ @classmethod
+ def _get_config(cls, fine_tune: FineTuningJob) -> Dict[str, Any]:
+ config = dict(fine_tune)
+ config["result_files"] = config["result_files"][0]
+ if config.get("created_at"):
+ config["created_at"] = datetime.datetime.fromtimestamp(
+ config["created_at"]
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ if config.get("finished_at"):
+ config["finished_at"] = datetime.datetime.fromtimestamp(
+ config["finished_at"]
+ ).strftime("%Y-%m-%d %H:%M:%S")
+ if config.get("hyperparameters"):
+ config["hyperparameters"] = cls.sanitize(config["hyperparameters"])
+ if config.get("error"):
+ config["error"] = cls.sanitize(config["error"])
+ return config
+
+ @classmethod
+ def _unpack_hyperparameters(cls, hyperparameters: Hyperparameters):
+ # `Hyperparameters` object is not unpacking properly using `vars` or `__dict__`,
+ # vars(hyperparameters) return {n_epochs: n} only.
+ hyperparams = {}
+ try:
+ hyperparams["n_epochs"] = hyperparameters.n_epochs
+ hyperparams["batch_size"] = hyperparameters.batch_size
+ hyperparams["learning_rate_multiplier"] = (
+ hyperparameters.learning_rate_multiplier
+ )
+ except Exception:
+ # If unpacking fails, return the object to be logged as config
+ return None
+
+ return hyperparams
+
+ @staticmethod
+ def sanitize(input: Any) -> Union[Dict, List, str]:
+ valid_types = [bool, int, float, str]
+ if isinstance(input, (Hyperparameters, Error)):
+ return dict(input)
+ if isinstance(input, dict):
+ return {
+ k: v if type(v) in valid_types else str(v) for k, v in input.items()
+ }
+ elif isinstance(input, list):
+ return [v if type(v) in valid_types else str(v) for v in input]
+ else:
+ return str(input)
+
+ @classmethod
+ def _log_artifacts(
+ cls,
+ fine_tune: FineTuningJob,
+ project: str,
+ entity: Optional[str],
+ log_datasets: bool,
+ overwrite: bool,
+ model_artifact_name: str,
+ model_artifact_type: str,
+ ) -> None:
+ if log_datasets:
+ wandb.termlog("Logging training/validation files...")
+ # training/validation files
+ training_file = fine_tune.training_file if fine_tune.training_file else None
+ validation_file = (
+ fine_tune.validation_file if fine_tune.validation_file else None
+ )
+ for file, prefix, artifact_type in (
+ (training_file, "train", "training_files"),
+ (validation_file, "valid", "validation_files"),
+ ):
+ if file is not None:
+ cls._log_artifact_inputs(
+ file, prefix, artifact_type, project, entity, overwrite
+ )
+
+ # fine-tune details
+ fine_tune_id = fine_tune.id
+ artifact = wandb.Artifact(
+ model_artifact_name,
+ type=model_artifact_type,
+ metadata=dict(fine_tune),
+ )
+
+ with artifact.new_file("model_metadata.json", mode="w", encoding="utf-8") as f:
+ dict_fine_tune = dict(fine_tune)
+ dict_fine_tune["hyperparameters"] = cls.sanitize(
+ dict_fine_tune["hyperparameters"]
+ )
+ dict_fine_tune["error"] = cls.sanitize(dict_fine_tune["error"])
+ dict_fine_tune = cls.sanitize(dict_fine_tune)
+ json.dump(dict_fine_tune, f, indent=2)
+ cls._run.log_artifact(
+ artifact,
+ aliases=["latest", fine_tune_id],
+ )
+
+ @classmethod
+ def _log_artifact_inputs(
+ cls,
+ file_id: Optional[str],
+ prefix: str,
+ artifact_type: str,
+ project: str,
+ entity: Optional[str],
+ overwrite: bool,
+ ) -> None:
+ # get input artifact
+ artifact_name = f"{prefix}-{file_id}"
+ # sanitize name to valid wandb artifact name
+ artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name)
+ artifact_alias = file_id
+ artifact_path = f"{project}/{artifact_name}:{artifact_alias}"
+ if entity is not None:
+ artifact_path = f"{entity}/{artifact_path}"
+ artifact = cls._get_wandb_artifact(artifact_path)
+
+ # create artifact if file not already logged previously
+ if artifact is None or overwrite:
+ # get file content
+ try:
+ file_content = cls.openai_client.files.content(file_id=file_id)
+ except openai.NotFoundError:
+ wandb.termerror(
+ f"File {file_id} could not be retrieved. Make sure you have OpenAI permissions to download training/validation files"
+ )
+ return
+
+ artifact = wandb.Artifact(artifact_name, type=artifact_type)
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
+ tmp_file.write(file_content.content)
+ tmp_file_path = tmp_file.name
+ artifact.add_file(tmp_file_path, file_id)
+ os.unlink(tmp_file_path)
+
+ # create a Table
+ try:
+ table, n_items = cls._make_table(file_content.text)
+ # Add table to the artifact.
+ artifact.add(table, file_id)
+ # Add the same table to the workspace.
+ cls._run.log({f"{prefix}_data": table})
+ # Update the run config and artifact metadata
+ cls._run.config.update({f"n_{prefix}": n_items})
+ artifact.metadata["items"] = n_items
+ except Exception as e:
+ wandb.termerror(
+ f"Issue saving {file_id} as a Table to Artifacts, exception:\n '{e}'"
+ )
+ else:
+ # log number of items
+ cls._run.config.update({f"n_{prefix}": artifact.metadata.get("items")})
+
+ cls._run.use_artifact(artifact, aliases=["latest", artifact_alias])
+
+ @classmethod
+ def _make_table(cls, file_content: str) -> Tuple[Table, int]:
+ table = wandb.Table(columns=["role: system", "role: user", "role: assistant"])
+
+ df = pd.read_json(io.StringIO(file_content), orient="records", lines=True)
+ for _idx, message in df.iterrows():
+ messages = message.messages
+ assert len(messages) == 3
+ table.add_data(
+ messages[0]["content"],
+ messages[1]["content"],
+ messages[2]["content"],
+ )
+
+ return table, len(df)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/openai.py b/venv/lib/python3.10/site-packages/wandb/integration/openai/openai.py
new file mode 100644
index 0000000000000000000000000000000000000000..250d437d7239bbcd31cc950c80563519f87e5fde
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/openai/openai.py
@@ -0,0 +1,22 @@
+import logging
+
+from wandb.sdk.integration_utils.auto_logging import AutologAPI
+
+from .resolver import OpenAIRequestResponseResolver
+
+logger = logging.getLogger(__name__)
+
+
+autolog = AutologAPI(
+ name="OpenAI",
+ symbols=(
+ "Edit.create",
+ "Completion.create",
+ "ChatCompletion.create",
+ "Edit.acreate",
+ "Completion.acreate",
+ "ChatCompletion.acreate",
+ ),
+ resolver=OpenAIRequestResponseResolver(),
+ telemetry_feature="openai_autolog",
+)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/openai/resolver.py b/venv/lib/python3.10/site-packages/wandb/integration/openai/resolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..500c58ce2f4b33a6a987243169bc998cf387fef4
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/openai/resolver.py
@@ -0,0 +1,240 @@
+import datetime
+import io
+import logging
+from dataclasses import asdict, dataclass
+from typing import Any, Dict, List, Optional, Sequence
+
+import wandb
+from wandb.sdk.data_types import trace_tree
+from wandb.sdk.integration_utils.auto_logging import Response
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class UsageMetrics:
+ elapsed_time: float = None
+ prompt_tokens: int = None
+ completion_tokens: int = None
+ total_tokens: int = None
+
+
+@dataclass
+class Metrics:
+ usage: UsageMetrics = None
+ stats: wandb.Table = None
+ trace: trace_tree.WBTraceTree = None
+
+
+usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())}
+
+
+class OpenAIRequestResponseResolver:
+ def __init__(self):
+ self.define_metrics_called = False
+
+ def __call__(
+ self,
+ args: Sequence[Any],
+ kwargs: Dict[str, Any],
+ response: Response,
+ start_time: float, # pass to comply with the protocol, but use response["created"] instead
+ time_elapsed: float,
+ ) -> Optional[Dict[str, Any]]:
+ request = kwargs
+
+ if not self.define_metrics_called:
+ # define metrics on first call
+ for key in usage_metric_keys:
+ wandb.define_metric(key, step_metric="_timestamp")
+ self.define_metrics_called = True
+
+ try:
+ if response.get("object") == "edit":
+ return self._resolve_edit(request, response, time_elapsed)
+ elif response.get("object") == "text_completion":
+ return self._resolve_completion(request, response, time_elapsed)
+ elif response.get("object") == "chat.completion":
+ return self._resolve_chat_completion(request, response, time_elapsed)
+ else:
+ # todo: properly treat failed requests
+ logger.info(
+ f"Unsupported OpenAI response object: {response.get('object')}"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to resolve request/response: {e}")
+ return None
+
+ @staticmethod
+ def results_to_trace_tree(
+ request: Dict[str, Any],
+ response: Response,
+ results: List[trace_tree.Result],
+ time_elapsed: float,
+ ) -> trace_tree.WBTraceTree:
+ """Converts the request, response, and results into a trace tree.
+
+ params:
+ request: The request dictionary
+ response: The response object
+ results: A list of results object
+ time_elapsed: The time elapsed in seconds
+ returns:
+ A wandb trace tree object.
+ """
+ start_time_ms = int(round(response["created"] * 1000))
+ end_time_ms = start_time_ms + int(round(time_elapsed * 1000))
+ span = trace_tree.Span(
+ name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}",
+ attributes=dict(response), # type: ignore
+ start_time_ms=start_time_ms,
+ end_time_ms=end_time_ms,
+ span_kind=trace_tree.SpanKind.LLM,
+ results=results,
+ )
+ model_obj = {"request": request, "response": response, "_kind": "openai"}
+ return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj)
+
+ def _resolve_edit(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Edit`."""
+ request_str = (
+ f"\n\n**Instruction**: {request['instruction']}\n\n"
+ f"**Input**: {request['input']}\n"
+ )
+ choices = [
+ f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_completion(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ request_str = f"\n\n**Prompt**: {request['prompt']}\n"
+ choices = [
+ f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_chat_completion(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ prompt = io.StringIO()
+ for message in request["messages"]:
+ prompt.write(f"\n\n**{message['role']}**: {message['content']}\n")
+ request_str = prompt.getvalue()
+
+ choices = [
+ f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n"
+ for choice in response["choices"]
+ ]
+
+ return self._resolve_metrics(
+ request=request,
+ response=response,
+ request_str=request_str,
+ choices=choices,
+ time_elapsed=time_elapsed,
+ )
+
+ def _resolve_metrics(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ request_str: str,
+ choices: List[str],
+ time_elapsed: float,
+ ) -> Dict[str, Any]:
+ """Resolves the request and response objects for `openai.Completion`."""
+ results = [
+ trace_tree.Result(
+ inputs={"request": request_str},
+ outputs={"response": choice},
+ )
+ for choice in choices
+ ]
+ metrics = self._get_metrics_to_log(request, response, results, time_elapsed)
+ return self._convert_metrics_to_dict(metrics)
+
+ @staticmethod
+ def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics:
+ """Gets the usage stats from the response object."""
+ if response.get("usage"):
+ usage_stats = UsageMetrics(**response["usage"])
+ else:
+ usage_stats = UsageMetrics()
+ usage_stats.elapsed_time = time_elapsed
+ return usage_stats
+
+ def _get_metrics_to_log(
+ self,
+ request: Dict[str, Any],
+ response: Response,
+ results: List[Any],
+ time_elapsed: float,
+ ) -> Metrics:
+ model = response.get("model") or request.get("model")
+ usage_metrics = self._get_usage_metrics(response, time_elapsed)
+
+ usage = []
+ for result in results:
+ row = {
+ "request": result.inputs["request"],
+ "response": result.outputs["response"],
+ "model": model,
+ "start_time": datetime.datetime.fromtimestamp(response["created"]),
+ "end_time": datetime.datetime.fromtimestamp(
+ response["created"] + time_elapsed
+ ),
+ "request_id": response.get("id", None),
+ "api_type": response.get("api_type", "openai"),
+ "session_id": wandb.run.id,
+ }
+ row.update(asdict(usage_metrics))
+ usage.append(row)
+ usage_table = wandb.Table(
+ columns=list(usage[0].keys()),
+ data=[(item.values()) for item in usage],
+ )
+
+ trace = self.results_to_trace_tree(request, response, results, time_elapsed)
+
+ metrics = Metrics(stats=usage_table, trace=trace, usage=usage_metrics)
+ return metrics
+
+ @staticmethod
+ def _convert_metrics_to_dict(metrics: Metrics) -> Dict[str, Any]:
+ """Converts metrics to a dict."""
+ metrics_dict = {
+ "stats": metrics.stats,
+ "trace": metrics.trace,
+ }
+ usage_stats = {f"usage/{k}": v for k, v in asdict(metrics.usage).items()}
+ metrics_dict.update(usage_stats)
+ return metrics_dict
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94ed0ea26bc5f886cf90db26da37dc8f08f9b18e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__init__.py
@@ -0,0 +1,3 @@
+from .prodigy import upload_dataset
+
+__all__ = ["upload_dataset"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4dfc7e9e2ddc445dc6387d61c4a4231e98595f1e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4f0ea1bcf9a1caf50b6af8ed28cc16e6e4a3741
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/prodigy/prodigy.py b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/prodigy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d25fc3cbab7a2c49aa585631e7162485487945e6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/prodigy/prodigy.py
@@ -0,0 +1,291 @@
+"""Prodigy integration for W&B.
+
+User can upload Prodigy annotated datasets directly
+from the local database to W&B in Tables format.
+
+Example usage:
+
+```python
+import wandb
+from wandb.integration.prodigy import upload_dataset
+
+run = wandb.init(project="prodigy")
+upload_dataset("name_of_dataset")
+wandb.finish()
+```
+"""
+
+import base64
+import collections.abc
+import io
+import urllib
+from copy import deepcopy
+
+import pandas as pd
+from PIL import Image
+
+import wandb
+from wandb import util
+from wandb.plot.utils import test_missing
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+
+def named_entity(docs):
+ """Create a named entity visualization.
+
+ Taken from https://github.com/wandb/wandb/blob/main/wandb/plots/named_entity.py.
+ """
+ spacy = util.get_module(
+ "spacy",
+ required="part_of_speech requires the spacy library, install with `pip install spacy`",
+ )
+
+ util.get_module(
+ "en_core_web_md",
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
+ )
+
+ # Test for required packages and missing & non-integer values in docs data
+ if test_missing(docs=docs):
+ html = spacy.displacy.render(
+ docs, style="ent", page=True, minify=True, jupyter=False
+ )
+ wandb_html = wandb.Html(html)
+ return wandb_html
+
+
+def merge(dict1, dict2):
+ """Return a new dictionary by merging two dictionaries recursively."""
+ result = deepcopy(dict1)
+
+ for key, value in dict2.items():
+ if isinstance(value, collections.abc.Mapping):
+ result[key] = merge(result.get(key, {}), value)
+ else:
+ result[key] = deepcopy(dict2[key])
+
+ return result
+
+
+def get_schema(list_data_dict, struct, array_dict_types):
+ """Get a schema of the dataset's structure and data types."""
+ # Get the structure of the JSON objects in the database
+ # This is similar to getting a JSON schema but with slightly different format
+ for _i, item in enumerate(list_data_dict):
+ # If the list contains dict objects
+ for k, v in item.items():
+ # Check if key already exists in template
+ if k not in struct.keys():
+ if isinstance(v, list):
+ if len(v) > 0 and isinstance(v[0], list):
+ # nested list structure
+ struct[k] = type(v) # type list
+ elif len(v) > 0 and not (
+ isinstance(v[0], list) or isinstance(v[0], dict)
+ ):
+ # list of singular values
+ struct[k] = type(v) # type list
+ else:
+ # list of dicts
+ array_dict_types.append(
+ k
+ ) # keep track of keys that are type list[dict]
+ struct[k] = {}
+ struct[k] = get_schema(v, struct[k], array_dict_types)
+ elif isinstance(v, dict):
+ struct[k] = {}
+ struct[k] = get_schema([v], struct[k], array_dict_types)
+ else:
+ struct[k] = type(v)
+ else:
+ # Get the value of struct[k] which is the current template
+ # Find new keys and then merge the two templates together
+ cur_struct = struct[k]
+ if isinstance(v, list):
+ if len(v) > 0 and isinstance(v[0], list):
+ # nested list coordinate structure
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v) # type list
+ elif len(v) > 0 and not (
+ isinstance(v[0], list) or isinstance(v[0], dict)
+ ):
+ # single list with values
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v) # type list
+ else:
+ array_dict_types.append(
+ k
+ ) # keep track of keys that are type list[dict]
+ struct[k] = {}
+ struct[k] = get_schema(v, struct[k], array_dict_types)
+ # merge cur_struct and struct[k], remove duplicates
+ struct[k] = merge(struct[k], cur_struct)
+ elif isinstance(v, dict):
+ struct[k] = {}
+ struct[k] = get_schema([v], struct[k], array_dict_types)
+ # merge cur_struct and struct[k], remove duplicates
+ struct[k] = merge(struct[k], cur_struct)
+ else:
+ # if the value in the item is currently None, then update
+ if v is not None:
+ struct[k] = type(v)
+
+ return struct
+
+
+def standardize(item, structure, array_dict_types):
+ """Standardize all rows/entries in dataset to fit the schema.
+
+ Will look for missing values and fill it in so all rows have
+ the same items and structure.
+ """
+ for k, v in structure.items():
+ if k not in item:
+ # If the structure/field does not exist
+ if isinstance(v, dict) and (k not in array_dict_types):
+ # If key k is of type dict, and not not a type list[dict]
+ item[k] = {}
+ standardize(item[k], v, array_dict_types)
+ elif isinstance(v, dict) and (k in array_dict_types):
+ # If key k is of type dict, and is actually of type list[dict],
+ # just treat as a list and set to None by default
+ item[k] = None
+ else:
+ # Assign a default type
+ item[k] = v()
+ else:
+ # If the structure/field already exists and is a list or dict
+ if isinstance(item[k], list):
+ # ignore if item is a nested list structure or list of non-dicts
+ condition = (
+ not (len(item[k]) > 0 and isinstance(item[k][0], list))
+ ) and (
+ not (
+ len(item[k]) > 0
+ and not (
+ isinstance(item[k][0], list) or isinstance(item[k][0], dict)
+ )
+ )
+ )
+ if condition:
+ for sub_item in item[k]:
+ standardize(sub_item, v, array_dict_types)
+ elif isinstance(item[k], dict):
+ standardize(item[k], v, array_dict_types)
+
+
+def create_table(data):
+ """Create a W&B Table.
+
+ - Create/decode images from URL/Base64
+ - Uses spacy to translate NER span data to visualizations.
+ """
+ # create table object from columns
+ table_df = pd.DataFrame(data)
+ columns = list(table_df.columns)
+ if ("spans" in table_df.columns) and ("text" in table_df.columns):
+ columns.append("spans_visual")
+ if "image" in columns:
+ columns.append("image_visual")
+ main_table = wandb.Table(columns=columns)
+
+ # Convert to dictionary format to maintain order during processing
+ matrix = table_df.to_dict(orient="records")
+
+ # Import en_core_web_md if exists
+ en_core_web_md = util.get_module(
+ "en_core_web_md",
+ required="part_of_speech requires `en_core_web_md` library, install with `python -m spacy download en_core_web_md`",
+ )
+ nlp = en_core_web_md.load(disable=["ner"])
+
+ # Go through each individual row
+ for _i, document in enumerate(matrix):
+ # Text NER span visualizations
+ if ("spans_visual" in columns) and ("text" in columns):
+ # Add visuals for spans
+ document["spans_visual"] = None
+ doc = nlp(document["text"])
+ ents = []
+ if ("spans" in document) and (document["spans"] is not None):
+ for span in document["spans"]:
+ if ("start" in span) and ("end" in span) and ("label" in span):
+ charspan = doc.char_span(
+ span["start"], span["end"], span["label"]
+ )
+ ents.append(charspan)
+ doc.ents = ents
+ document["spans_visual"] = named_entity(docs=doc)
+
+ # Convert image link to wandb Image
+ if "image" in columns:
+ # Turn into wandb image
+ document["image_visual"] = None
+ if ("image" in document) and (document["image"] is not None):
+ isurl = urllib.parse.urlparse(document["image"]).scheme in (
+ "http",
+ "https",
+ )
+ isbase64 = ("data:" in document["image"]) and (
+ ";base64" in document["image"]
+ )
+ if isurl:
+ # is url
+ try:
+ im = Image.open(urllib.request.urlopen(document["image"]))
+ document["image_visual"] = wandb.Image(im)
+ except urllib.error.URLError:
+ wandb.termwarn(f"Image URL {document['image']} is invalid.")
+ document["image_visual"] = None
+ elif isbase64:
+ # is base64 uri
+ imgb64 = document["image"].split("base64,")[1]
+ try:
+ msg = base64.b64decode(imgb64)
+ buf = io.BytesIO(msg)
+ im = Image.open(buf)
+ document["image_visual"] = wandb.Image(im)
+ except base64.binascii.Error:
+ wandb.termwarn(f"Base64 string {document['image']} is invalid.")
+ document["image_visual"] = None
+ else:
+ # is data path
+ document["image_visual"] = wandb.Image(document["image"])
+
+ # Create row and append to table
+ values_list = list(document.values())
+ main_table.add_data(*values_list)
+ return main_table
+
+
+def upload_dataset(dataset_name):
+ """Upload dataset from local database to Weights & Biases.
+
+ Args:
+ dataset_name: The name of the dataset in the Prodigy database.
+ """
+ # Check if wandb.init has been called
+ if wandb.run is None:
+ raise ValueError("You must call wandb.init() before upload_dataset()")
+
+ with wb_telemetry.context(run=wandb.run) as tel:
+ tel.feature.prodigy = True
+
+ prodigy_db = util.get_module(
+ "prodigy.components.db",
+ required="`prodigy` library is required but not installed. Please see https://prodi.gy/docs/install",
+ )
+ # Retrieve and upload prodigy dataset
+ database = prodigy_db.connect()
+ data = database.get_dataset(dataset_name)
+
+ array_dict_types = []
+ schema = get_schema(data, {}, array_dict_types)
+
+ for i, _d in enumerate(data):
+ standardize(data[i], schema, array_dict_types)
+ table = create_table(data)
+ wandb.log({dataset_name: table})
+ wandb.termlog(f"Prodigy dataset `{dataset_name}` uploaded.")
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sacred/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sacred/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dabcc47afd726c57cf269e698096e399a1574b3a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sacred/__init__.py
@@ -0,0 +1,117 @@
+import warnings
+
+import numpy
+from sacred.dependencies import get_digest
+from sacred.observers import RunObserver
+
+import wandb
+
+
+class WandbObserver(RunObserver):
+ """Log sacred experiment data to W&B.
+
+ Args:
+ Accepts all the arguments accepted by wandb.init().
+
+ name — A display name for this run, which shows up in the UI and is editable, doesn't have to be unique
+ notes — A multiline string description associated with the run
+ config — a dictionary-like object to set as initial config
+ project — the name of the project to which this run will belong
+ tags — a list of strings to associate with this run as tags
+ dir — the path to a directory where artifacts will be written (default: ./wandb)
+ entity — the team posting this run (default: your username or your default team)
+ job_type — the type of job you are logging, e.g. eval, worker, ps (default: training)
+ save_code — save the main python or notebook file to wandb to enable diffing (default: editable from your settings page)
+ group — a string by which to group other runs; see Grouping
+ reinit — Shorthand for the reinit setting that defines what to do when `wandb.init()` is called while a run is active. See the setting's documentation.
+ id — A unique ID for this run primarily used for Resuming. It must be globally unique, and if you delete a run you can't reuse the ID. Use the name field for a descriptive, useful name for the run. The ID cannot contain special characters.
+ resume — if set to True, the run auto resumes; can also be a unique string for manual resuming; see Resuming (default: False)
+ anonymous — can be "allow", "never", or "must". This enables or explicitly disables anonymous logging. (default: never)
+ force — whether to force a user to be logged into wandb when running a script (default: False)
+ magic — (bool, dict, or str, optional): magic configuration as bool, dict, json string, yaml filename. If set to True will attempt to auto-instrument your script. (default: None)
+ sync_tensorboard — A boolean indicating whether or not copy all TensorBoard logs wandb; see Tensorboard (default: False)
+ monitor_gym — A boolean indicating whether or not to log videos generated by OpenAI Gym; see Ray Tune (default: False)
+ allow_val_change — whether to allow wandb.config values to change, by default we throw an exception if config values are overwritten. (default: False)
+
+ Examples:
+ Create sacred experiment::
+ from wandb.sacred import WandbObserver
+ ex.observers.append(WandbObserver(project='sacred_test',
+ name='test1'))
+ @ex.config
+ def cfg():
+ C = 1.0
+ gamma = 0.7
+ @ex.automain
+ def run(C, gamma, _run):
+ iris = datasets.load_iris()
+ per = permutation(iris.target.size)
+ iris.data = iris.data[per]
+ iris.target = iris.target[per]
+ clf = svm.SVC(C, 'rbf', gamma=gamma)
+ clf.fit(iris.data[:90],
+ iris.target[:90])
+ return clf.score(iris.data[90:],
+ iris.target[90:])
+ """
+
+ def __init__(self, **kwargs):
+ self.run = wandb.init(**kwargs)
+ self.resources = {}
+
+ def started_event(
+ self, ex_info, command, host_info, start_time, config, meta_info, _id
+ ):
+ # TODO: add the source code file
+ # TODO: add dependencies and metadata.
+ self.__update_config(config)
+
+ def completed_event(self, stop_time, result):
+ if result:
+ if not isinstance(result, tuple):
+ result = (
+ result,
+ ) # transform single result to tuple so that both single & multiple results use same code
+
+ for i, r in enumerate(result):
+ if isinstance(r, float) or isinstance(r, int):
+ wandb.log({f"result_{i}": float(r)})
+ elif isinstance(r, dict):
+ wandb.log(r)
+ elif isinstance(r, object):
+ artifact = wandb.Artifact(f"result_{i}.pkl", type="result")
+ artifact.add_file(r)
+ self.run.log_artifact(artifact)
+ elif isinstance(r, numpy.ndarray):
+ wandb.log({f"result_{i}": wandb.Image(r)})
+ else:
+ warnings.warn(
+ f"logging results does not support type '{type(r)}' results. Ignoring this result",
+ stacklevel=2,
+ )
+
+ def artifact_event(self, name, filename, metadata=None, content_type=None):
+ if content_type is None:
+ content_type = "file"
+ artifact = wandb.Artifact(name, type=content_type)
+ artifact.add_file(filename)
+ self.run.log_artifact(artifact)
+
+ def resource_event(self, filename):
+ """TODO: Maintain resources list."""
+ if filename not in self.resources:
+ md5 = get_digest(filename)
+ self.resources[filename] = md5
+
+ def log_metrics(self, metrics_by_name, info):
+ for metric_name, metric_ptr in metrics_by_name.items():
+ for _step, value in zip(metric_ptr["steps"], metric_ptr["values"]):
+ if isinstance(value, numpy.ndarray):
+ wandb.log({metric_name: wandb.Image(value)})
+ else:
+ wandb.log({metric_name: value})
+
+ def __update_config(self, config):
+ for k, v in config.items():
+ self.run.config[k] = v
+ self.run.config["resources"] = []
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e9143f657325e190b171fd7e495db9fcb6fa477
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c8509c8fae0a795d4f17bedd708c87ee587e931
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__init__.py
@@ -0,0 +1,14 @@
+"""wandb integration sagemaker module."""
+
+from .auth import sagemaker_auth
+from .config import is_using_sagemaker, parse_sm_config
+from .resources import parse_sm_secrets, set_global_settings, set_run_id
+
+__all__ = [
+ "sagemaker_auth",
+ "is_using_sagemaker",
+ "parse_sm_config",
+ "parse_sm_secrets",
+ "set_global_settings",
+ "set_run_id",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bb65fc59e9582dace48f8fc0c5ea292224c7ce7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/auth.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/auth.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..042b0f50bb983c5b907e512df0df74eea147822b
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/auth.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eadf234148ca22021a9ee4a0416197a3f578c822
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4692e6185d6802a35e878696f67d67ceb7c17af0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/resources.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/resources.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a627cfad7588ff23b768488fc4b183f016811573
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/__pycache__/resources.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/auth.py b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc82952db6dd710c1e474640cf939476ca171c8d
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/auth.py
@@ -0,0 +1,29 @@
+import os
+
+import wandb
+from wandb import env
+from wandb.sdk import wandb_setup
+
+
+def sagemaker_auth(overrides=None, path=".", api_key=None):
+ """Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
+
+ Args:
+ overrides (dict, optional): Additional environment variables to write
+ to secrets.env
+ path (str, optional): The path to write the secrets file.
+ """
+ settings = wandb_setup.singleton().settings
+ current_api_key = wandb.wandb_lib.apikey.api_key(settings=settings)
+
+ overrides = overrides or dict()
+ api_key = overrides.get(env.API_KEY, api_key or current_api_key)
+ if api_key is None:
+ raise ValueError(
+ "Can't find W&B ApiKey, set the WANDB_API_KEY env variable "
+ "or run `wandb login`"
+ )
+ overrides[env.API_KEY] = api_key
+ with open(os.path.join(path, "secrets.env"), "w") as file:
+ for k, v in overrides.items():
+ file.write(f"{k}={v}\n")
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/config.py b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..be71b92c19d204b249c277a1c0c82c70bab3a044
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/config.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import json
+import os
+import re
+import warnings
+from typing import Any
+
+from . import files as sm_files
+
+
+def is_using_sagemaker() -> bool:
+ """Returns whether we're in a SageMaker environment."""
+ return (
+ os.path.exists(sm_files.SM_PARAM_CONFIG) #
+ or "SM_TRAINING_ENV" in os.environ
+ )
+
+
+def parse_sm_config() -> dict[str, Any]:
+ """Parses SageMaker configuration.
+
+ Returns:
+ A dictionary of SageMaker config keys/values
+ or an empty dict if not found.
+ SM_TRAINING_ENV is a json string of the
+ training environment variables set by SageMaker
+ and is only available when running in SageMaker,
+ but not in local mode.
+ SM_TRAINING_ENV is set by the SageMaker container and
+ contains arguments such as hyperparameters
+ and arguments passed to the training job.
+ """
+ conf = {}
+
+ if os.path.exists(sm_files.SM_PARAM_CONFIG):
+ conf["sagemaker_training_job_name"] = os.getenv("TRAINING_JOB_NAME")
+
+ # Hyperparameter searches quote configs...
+ with open(sm_files.SM_PARAM_CONFIG) as fid:
+ for key, val in json.load(fid).items():
+ cast = val.strip('"')
+ if re.match(r"^-?[\d]+$", cast):
+ cast = int(cast)
+ elif re.match(r"^-?[.\d]+$", cast):
+ cast = float(cast)
+ conf[key] = cast
+
+ if env := os.environ.get("SM_TRAINING_ENV"):
+ try:
+ conf.update(json.loads(env))
+ except json.JSONDecodeError:
+ warnings.warn(
+ "Failed to parse SM_TRAINING_ENV not valid JSON string",
+ stacklevel=2,
+ )
+
+ return conf
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/files.py b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/files.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f91e72fb07b5febb7ee6cb89d06f18444fce826
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/files.py
@@ -0,0 +1,2 @@
+SM_PARAM_CONFIG = "/opt/ml/input/config/hyperparameters.json"
+SM_SECRETS = "secrets.env"
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/resources.py b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/resources.py
new file mode 100644
index 0000000000000000000000000000000000000000..4410c755772eead22a846cf25a5beed6fca6cc45
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sagemaker/resources.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+import os
+import secrets
+import socket
+import string
+
+import wandb
+
+from . import config
+from . import files as sm_files
+
+
+def set_run_id(run_settings: wandb.Settings) -> bool:
+ """Set a run ID and group when using SageMaker.
+
+ Returns whether the ID and group were updated.
+ """
+ # Added in https://github.com/wandb/wandb/pull/3290.
+ #
+ # Prevents SageMaker from overriding the run ID configured
+ # in environment variables. Note, however, that it will still
+ # override a run ID passed explicitly to `wandb.init()`.
+ if os.getenv("WANDB_RUN_ID"):
+ return False
+
+ run_group = os.getenv("TRAINING_JOB_NAME")
+ if not run_group:
+ return False
+
+ alphanumeric = string.ascii_lowercase + string.digits
+ random = "".join(secrets.choice(alphanumeric) for _ in range(6))
+
+ host = os.getenv("CURRENT_HOST", socket.gethostname())
+
+ run_settings.run_id = f"{run_group}-{random}-{host}"
+ run_settings.run_group = run_group
+ return True
+
+
+def set_global_settings(settings: wandb.Settings) -> None:
+ """Set global W&B settings based on the SageMaker environment."""
+ if env := parse_sm_secrets():
+ settings.update_from_env_vars(env)
+
+ # The SageMaker config may contain an API key, in which case it
+ # takes precedence over the value in the secrets. It's unclear
+ # whether this is by design, or by accident; we keep it for
+ # backward compatibility for now.
+ sm_config = config.parse_sm_config()
+ if api_key := sm_config.get("wandb_api_key"):
+ settings.api_key = api_key
+
+
+def parse_sm_secrets() -> dict[str, str]:
+ """We read our api_key from secrets.env in SageMaker."""
+ env_dict = dict()
+ # Set secret variables
+ if os.path.exists(sm_files.SM_SECRETS):
+ for line in open(sm_files.SM_SECRETS):
+ key, val = line.strip().split("=", 1)
+ env_dict[key] = val
+ return env_dict
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sb3/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..29dd81a941cb1745cf82fecbcf12a857ce786f45
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__init__.py
@@ -0,0 +1,3 @@
+from .sb3 import WandbCallback
+
+__all__ = ["WandbCallback"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8db1971ec0c57dc869648c4a2e4a7a9bacfb8a15
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac43762e06c8956c749bad93cf624809fa140fc8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sb3/sb3.py b/venv/lib/python3.10/site-packages/wandb/integration/sb3/sb3.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eec145d0fc052575ca6ba65d68283dcaa0ea69b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sb3/sb3.py
@@ -0,0 +1,147 @@
+"""W&B callback for sb3.
+
+Really simple callback to get logging for each tree
+
+Example usage:
+
+```python
+import gym
+from stable_baselines3 import PPO
+from stable_baselines3.common.monitor import Monitor
+from stable_baselines3.common.vec_env import DummyVecEnv, VecVideoRecorder
+import wandb
+from wandb.integration.sb3 import WandbCallback
+
+
+config = {
+ "policy_type": "MlpPolicy",
+ "total_timesteps": 25000,
+ "env_name": "CartPole-v1",
+}
+run = wandb.init(
+ project="sb3",
+ config=config,
+ sync_tensorboard=True, # auto-upload sb3's tensorboard metrics
+ monitor_gym=True, # auto-upload the videos of agents playing the game
+ save_code=True, # optional
+)
+
+
+def make_env():
+ env = gym.make(config["env_name"])
+ env = Monitor(env) # record stats such as returns
+ return env
+
+
+env = DummyVecEnv([make_env])
+env = VecVideoRecorder(
+ env, "videos", record_video_trigger=lambda x: x % 2000 == 0, video_length=200
+)
+model = PPO(config["policy_type"], env, verbose=1, tensorboard_log=f"runs")
+model.learn(
+ total_timesteps=config["total_timesteps"],
+ callback=WandbCallback(
+ model_save_path=f"models/{run.id}",
+ gradient_save_freq=100,
+ log="all",
+ ),
+)
+```
+"""
+
+import logging
+import os
+from typing import Literal, Optional
+
+from stable_baselines3.common.callbacks import BaseCallback # type: ignore
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+logger = logging.getLogger(__name__)
+
+
+class WandbCallback(BaseCallback):
+ """Callback for logging experiments to Weights and Biases.
+
+ Log SB3 experiments to Weights and Biases
+ - Added model tracking and uploading
+ - Added complete hyperparameters recording
+ - Added gradient logging
+ - Note that `wandb.init(...)` must be called before the WandbCallback can be used.
+
+ Args:
+ verbose: The verbosity of sb3 output
+ model_save_path: Path to the folder where the model will be saved, The default value is `None` so the model is not logged
+ model_save_freq: Frequency to save the model
+ gradient_save_freq: Frequency to log gradient. The default value is 0 so the gradients are not logged
+ log: What to log. One of "gradients", "parameters", or "all".
+ """
+
+ def __init__(
+ self,
+ verbose: int = 0,
+ model_save_path: Optional[str] = None,
+ model_save_freq: int = 0,
+ gradient_save_freq: int = 0,
+ log: Optional[Literal["gradients", "parameters", "all"]] = "all",
+ ) -> None:
+ super().__init__(verbose)
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+ with wb_telemetry.context() as tel:
+ tel.feature.sb3 = True
+ self.model_save_freq = model_save_freq
+ self.model_save_path = model_save_path
+ self.gradient_save_freq = gradient_save_freq
+ if log not in ["gradients", "parameters", "all", None]:
+ wandb.termwarn(
+ "`log` must be one of `None`, 'gradients', 'parameters', or 'all', "
+ "falling back to 'all'"
+ )
+ log = "all"
+ self.log = log
+ # Create folder if needed
+ if self.model_save_path is not None:
+ os.makedirs(self.model_save_path, exist_ok=True)
+ self.path = os.path.join(self.model_save_path, "model.zip")
+ else:
+ assert self.model_save_freq == 0, (
+ "to use the `model_save_freq` you have to set the `model_save_path` parameter"
+ )
+
+ def _init_callback(self) -> None:
+ d = {}
+ if "algo" not in d:
+ d["algo"] = type(self.model).__name__
+ for key in self.model.__dict__:
+ if key in wandb.config:
+ continue
+ if type(self.model.__dict__[key]) in [float, int, str]:
+ d[key] = self.model.__dict__[key]
+ else:
+ d[key] = str(self.model.__dict__[key])
+ if self.gradient_save_freq > 0:
+ wandb.watch(
+ self.model.policy,
+ log_freq=self.gradient_save_freq,
+ log=self.log,
+ )
+ wandb.config.setdefaults(d)
+
+ def _on_step(self) -> bool:
+ if self.model_save_freq > 0:
+ if self.model_save_path is not None:
+ if self.n_calls % self.model_save_freq == 0:
+ self.save_model()
+ return True
+
+ def _on_training_end(self) -> None:
+ if self.model_save_path is not None:
+ self.save_model()
+
+ def save_model(self) -> None:
+ self.model.save(self.path)
+ wandb.save(self.path, base_path=self.model_save_path)
+ if self.verbose > 1:
+ logger.info(f"Saving model checkpoint to {self.path}")
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb3cb14c923c289c8075c296066f840c3c4e0858
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__init__.py
@@ -0,0 +1,37 @@
+"""Create informative charts for scikit-learn models and log them to W&B."""
+
+from .plot import (
+ plot_calibration_curve,
+ plot_class_proportions,
+ plot_classifier,
+ plot_clusterer,
+ plot_confusion_matrix,
+ plot_elbow_curve,
+ plot_feature_importances,
+ plot_learning_curve,
+ plot_outlier_candidates,
+ plot_precision_recall,
+ plot_regressor,
+ plot_residuals,
+ plot_roc,
+ plot_silhouette,
+ plot_summary_metrics,
+)
+
+__all__ = [
+ "plot_classifier",
+ "plot_clusterer",
+ "plot_regressor",
+ "plot_summary_metrics",
+ "plot_learning_curve",
+ "plot_feature_importances",
+ "plot_class_proportions",
+ "plot_calibration_curve",
+ "plot_roc",
+ "plot_precision_recall",
+ "plot_confusion_matrix",
+ "plot_elbow_curve",
+ "plot_silhouette",
+ "plot_residuals",
+ "plot_outlier_candidates",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c02ccd4fa6612c45b9d48bf9f0a83caf5673b55
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3810e983db2f9c4d512309bd64b5c41ef2e360f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d22d629bbc7dced6da390f885a4d327049491ff
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__init__.py
@@ -0,0 +1,32 @@
+"""Calculates and formats metrics and charts for introspecting sklearn models.
+
+The functions in these modules are designed to be called by functions from the
+plot submodule that have been exported into the namespace of the wandb.sklearn
+submodule, rather than being called directly.
+"""
+
+from .calibration_curves import calibration_curves
+from .class_proportions import class_proportions
+from .confusion_matrix import confusion_matrix
+from .decision_boundaries import decision_boundaries
+from .elbow_curve import elbow_curve
+from .feature_importances import feature_importances
+from .learning_curve import learning_curve
+from .outlier_candidates import outlier_candidates
+from .residuals import residuals
+from .silhouette import silhouette
+from .summary_metrics import summary_metrics
+
+__all__ = [
+ "calibration_curves",
+ "class_proportions",
+ "confusion_matrix",
+ "decision_boundaries",
+ "elbow_curve",
+ "feature_importances",
+ "learning_curve",
+ "outlier_candidates",
+ "residuals",
+ "silhouette",
+ "summary_metrics",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e09f7803306a4fb650dee9e672501104040f682d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/calibration_curves.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/calibration_curves.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4a073a9f359151882703f686c94432687266174
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/calibration_curves.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..488edfbeb81c5b7f93b9784a3a603cbc4c21598a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/confusion_matrix.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/confusion_matrix.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74720e37209d76bfea13777948cc7a01cef47339
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/confusion_matrix.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dbc8ea78215d0a1f2ce1715c26d40c48b9667539
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96e2472a2a1e44cbdfe30585d37837891a04ec49
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b29c75e3c287b82cc18bb3983325cc26af2c2b22
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fd5e838f43729ed1899ce3a791dc542a599246e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/outlier_candidates.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/outlier_candidates.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd538d4d3b12620c2bddde781e786e862b65fedc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/outlier_candidates.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/residuals.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/residuals.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c14665c9dbca38d332f1d15c3e977770e31bed25
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/residuals.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7307a9a551b2c89bc8feed20df4bf18705f2feb9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/summary_metrics.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/summary_metrics.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3110a21bb0a94f059e5cb019c2e0765d31a0d90e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/__pycache__/summary_metrics.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py
new file mode 100644
index 0000000000000000000000000000000000000000..b59aa25d7d8c984ca30529d497eb0e263570c365
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py
@@ -0,0 +1,125 @@
+from warnings import simplefilter
+
+import numpy as np
+import sklearn
+from sklearn import model_selection, naive_bayes
+from sklearn.calibration import CalibratedClassifierCV
+from sklearn.linear_model import LogisticRegression
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def calibration_curves(clf, X, y, clf_name): # noqa: N803
+ # ComplementNB (introduced in 0.20.0) requires non-negative features
+ if int(sklearn.__version__.split(".")[1]) >= 20 and isinstance(
+ clf, naive_bayes.ComplementNB
+ ):
+ X = X - X.min() # noqa:N806
+
+ # Calibrated with isotonic calibration
+ isotonic = CalibratedClassifierCV(clf, cv=2, method="isotonic")
+
+ # Calibrated with sigmoid calibration
+ sigmoid = CalibratedClassifierCV(clf, cv=2, method="sigmoid")
+
+ # Logistic regression with no calibration as baseline
+ lr = LogisticRegression(C=1.0)
+
+ model_column = [] # color
+ frac_positives_column = [] # y axis
+ mean_pred_value_column = [] # x axis
+ hist_column = [] # barchart y
+ edge_column = [] # barchart x
+
+ # Add curve for perfectly calibrated model
+ # format: model, fraction_of_positives, mean_predicted_value
+ model_column.append("Perfectly calibrated")
+ frac_positives_column.append(0)
+ mean_pred_value_column.append(0)
+ hist_column.append(0)
+ edge_column.append(0)
+ model_column.append("Perfectly calibrated")
+ hist_column.append(0)
+ edge_column.append(0)
+ frac_positives_column.append(1)
+ mean_pred_value_column.append(1)
+
+ x_train, x_test, y_train, y_test = model_selection.train_test_split(
+ X, y, test_size=0.9, random_state=42
+ )
+
+ # Add curve for LogisticRegression baseline and other models
+
+ models = [lr, isotonic, sigmoid]
+ names = ["Logistic", f"{clf_name} Isotonic", f"{clf_name} Sigmoid"]
+
+ for model, name in zip(models, names):
+ model.fit(x_train, y_train)
+ if hasattr(model, "predict_proba"):
+ prob_pos = model.predict_proba(x_test)[:, 1]
+ else: # use decision function
+ prob_pos = model.decision_function(x_test)
+ prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())
+
+ hist, edges = np.histogram(prob_pos, bins=10, density=False)
+ frac_positives, mean_pred_value = sklearn.calibration.calibration_curve(
+ y_test, prob_pos, n_bins=10
+ )
+
+ # format: model, fraction_of_positives, mean_predicted_value
+ num_entries = len(frac_positives)
+ for i in range(num_entries):
+ hist_column.append(hist[i])
+ edge_column.append(edges[i])
+ model_column.append(name)
+ frac_positives_column.append(utils.round_3(frac_positives[i]))
+ mean_pred_value_column.append(utils.round_3(mean_pred_value[i]))
+ if utils.check_against_limit(
+ i,
+ "calibration_curve",
+ utils.chart_limit - 2,
+ ):
+ break
+
+ table = make_table(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+ )
+ chart = wandb.visualize("wandb/calibration/v1", table)
+
+ return chart
+
+
+def make_table(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+):
+ columns = [
+ "model",
+ "fraction_of_positives",
+ "mean_predicted_value",
+ "hist_dict",
+ "edge_dict",
+ ]
+
+ data = list(
+ zip(
+ model_column,
+ frac_positives_column,
+ mean_pred_value_column,
+ hist_column,
+ edge_column,
+ )
+ )
+
+ return wandb.Table(columns=columns, data=data)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py
new file mode 100644
index 0000000000000000000000000000000000000000..183bf785a2fb62e2efe20fbdfde68f7a0fc45024
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/class_proportions.py
@@ -0,0 +1,68 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn.utils.multiclass import unique_labels
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def class_proportions(y_train, y_test, labels):
+ # Get the unique values from the dataset
+ targets = (y_train,) if y_test is None else (y_train, y_test)
+ class_ids = np.array(unique_labels(*targets))
+
+ # Compute the class counts
+ counts_train = np.array([(y_train == c).sum() for c in class_ids])
+ counts_test = np.array([(y_test == c).sum() for c in class_ids])
+
+ class_column, dataset_column, count_column = make_columns(
+ class_ids, counts_train, counts_test
+ )
+
+ if labels is not None and (
+ isinstance(class_column[0], int) or isinstance(class_column[0], np.integer)
+ ):
+ class_column = get_named_labels(labels, class_column)
+
+ table = make_table(class_column, dataset_column, count_column)
+ chart = wandb.visualize("wandb/class_proportions/v1", table)
+
+ return chart
+
+
+def make_table(class_column, dataset_column, count_column):
+ columns = ["class", "dataset", "count"]
+ data = list(zip(class_column, dataset_column, count_column))
+
+ return wandb.Table(data=data, columns=columns)
+
+
+def make_columns(class_ids, counts_train, counts_test):
+ class_column, dataset_column, count_column = [], [], []
+
+ for i in range(len(class_ids)):
+ # add class counts from training set
+ class_column.append(class_ids[i])
+ dataset_column.append("train")
+ count_column.append(counts_train[i])
+ # add class counts from test set
+ class_column.append(class_ids[i])
+ dataset_column.append("test")
+ count_column.append(counts_test[i])
+
+ if utils.check_against_limit(
+ i,
+ "class_proportions",
+ utils.chart_limit,
+ ):
+ break
+
+ return class_column, dataset_column, count_column
+
+
+def get_named_labels(labels, numeric_labels):
+ return np.array([labels[num_label] for num_label in numeric_labels])
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..777c84ada92237222e0a058c5facd7b761313b12
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py
@@ -0,0 +1,93 @@
+import itertools
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import metrics
+from sklearn.utils.multiclass import unique_labels
+
+import wandb
+
+from .. import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def validate_labels(*args, **kwargs): # FIXME
+ raise AssertionError()
+
+
+def confusion_matrix(
+ y_true=None,
+ y_pred=None,
+ labels=None,
+ true_labels=None,
+ pred_labels=None,
+ normalize=False,
+):
+ """Compute the confusion matrix to evaluate the performance of a classification.
+
+ Called by plot_confusion_matrix to visualize roc curves. Please use the function
+ plot_confusion_matrix() if you wish to visualize your confusion matrix.
+ """
+ cm = metrics.confusion_matrix(y_true, y_pred)
+
+ if labels is None:
+ classes = unique_labels(y_true, y_pred)
+ else:
+ classes = np.asarray(labels)
+
+ if normalize:
+ cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis]
+ cm = np.around(cm, decimals=2)
+ cm[np.isnan(cm)] = 0.0
+
+ if true_labels is None:
+ true_classes = classes
+ else:
+ validate_labels(classes, true_labels, "true_labels")
+
+ true_label_indexes = np.in1d(classes, true_labels)
+
+ true_classes = classes[true_label_indexes]
+ cm = cm[true_label_indexes]
+
+ if pred_labels is None:
+ pred_classes = classes
+ else:
+ validate_labels(classes, pred_labels, "pred_labels")
+
+ pred_label_indexes = np.in1d(classes, pred_labels)
+
+ pred_classes = classes[pred_label_indexes]
+ cm = cm[:, pred_label_indexes]
+
+ table = make_table(cm, pred_classes, true_classes, labels)
+ chart = wandb.visualize("wandb/confusion_matrix/v1", table)
+
+ return chart
+
+
+def make_table(cm, pred_classes, true_classes, labels):
+ data, count = [], 0
+ for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
+ if labels is not None and (
+ isinstance(pred_classes[i], int) or isinstance(pred_classes[0], np.integer)
+ ):
+ pred = labels[pred_classes[i]]
+ true = labels[true_classes[j]]
+ else:
+ pred = pred_classes[i]
+ true = true_classes[j]
+ data.append([pred, true, cm[i, j]])
+ count += 1
+ if utils.check_against_limit(
+ count,
+ "confusion_matrix",
+ utils.chart_limit,
+ ):
+ break
+
+ table = wandb.Table(columns=["Predicted", "Actual", "Count"], data=data)
+
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7a849b86b151270adf2437e4f2e72a03ce6c1a9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py
@@ -0,0 +1,40 @@
+from warnings import simplefilter
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def decision_boundaries(
+ decision_boundary_x,
+ decision_boundary_y,
+ decision_boundary_color,
+ train_x,
+ train_y,
+ train_color,
+ test_x,
+ test_y,
+ test_color,
+):
+ x_dict, y_dict, color_dict = [], [], []
+ for i in range(min(len(decision_boundary_x), 100)):
+ x_dict.append(decision_boundary_x[i])
+ y_dict.append(decision_boundary_y[i])
+ color_dict.append(decision_boundary_color)
+ for i in range(300):
+ x_dict.append(test_x[i])
+ y_dict.append(test_y[i])
+ color_dict.append(test_color[i])
+ for i in range(min(len(train_x), 600)):
+ x_dict.append(train_x[i])
+ y_dict.append(train_y[i])
+ color_dict.append(train_color[i])
+
+ return wandb.visualize(
+ "wandb/decision_boundaries/v1",
+ wandb.Table(
+ columns=["x", "y", "color"],
+ data=[[x_dict[i], y_dict[i], color_dict[i]] for i in range(len(x_dict))],
+ ),
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..731102d75adabf238d44de00b8d79bca59f0a87a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py
@@ -0,0 +1,55 @@
+import time
+from warnings import simplefilter
+
+import numpy as np
+from joblib import Parallel, delayed
+from sklearn.base import clone
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def elbow_curve(clusterer, X, cluster_ranges, n_jobs, show_cluster_time): # noqa: N803
+ if cluster_ranges is None:
+ cluster_ranges = range(1, 10, 2)
+ else:
+ cluster_ranges = sorted(cluster_ranges)
+
+ clfs, times = _compute_results_parallel(n_jobs, clusterer, X, cluster_ranges)
+
+ clfs = np.absolute(clfs)
+
+ table = make_table(cluster_ranges, clfs, times)
+ chart = wandb.visualize("wandb/elbow/v1", table)
+
+ return chart
+
+
+def make_table(cluster_ranges, clfs, times):
+ columns = ["cluster_ranges", "errors", "clustering_time"]
+
+ data = list(zip(cluster_ranges, clfs, times))
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
+
+
+def _compute_results_parallel(n_jobs, clusterer, x, cluster_ranges):
+ parallel_runner = Parallel(n_jobs=n_jobs)
+ _cluster_scorer = delayed(_clone_and_score_clusterer)
+ results = parallel_runner(_cluster_scorer(clusterer, x, i) for i in cluster_ranges)
+
+ clfs, times = zip(*results)
+
+ return clfs, times
+
+
+def _clone_and_score_clusterer(clusterer, x, n_clusters):
+ start = time.time()
+ clusterer = clone(clusterer)
+ clusterer.n_clusters = n_clusters
+
+ return clusterer.fit(x).score(x), time.time() - start
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py
new file mode 100644
index 0000000000000000000000000000000000000000..fac0452b944fd31d3bf611df054f4f6c0dbc0895
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/feature_importances.py
@@ -0,0 +1,67 @@
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def feature_importances(model, feature_names):
+ attributes_to_check = ["feature_importances_", "feature_log_prob_", "coef_"]
+ found_attribute = check_for_attribute_on(model, attributes_to_check)
+ if found_attribute is None:
+ wandb.termwarn(
+ f"could not find any of attributes {', '.join(attributes_to_check)} on classifier. Cannot plot feature importances."
+ )
+ return
+ elif found_attribute == "feature_importances_":
+ importances = model.feature_importances_
+ elif found_attribute == "coef_": # ElasticNet-like models
+ importances = model.coef_
+ elif found_attribute == "feature_log_prob_":
+ # coef_ was deprecated in sklearn 0.24, replaced with
+ # feature_log_prob_
+ importances = model.feature_log_prob_
+
+ if len(importances.shape) > 1:
+ n_significant_dims = sum(i > 1 for i in importances.shape)
+ if n_significant_dims > 1:
+ nd = len(importances.shape)
+ wandb.termwarn(
+ f"{nd}-dimensional feature importances array passed to plot_feature_importances. "
+ f"{nd}-dimensional and higher feature importances arrays are not currently supported. "
+ f"These importances will not be plotted."
+ )
+ return
+ else:
+ importances = np.squeeze(importances)
+
+ indices = np.argsort(importances)[::-1]
+ importances = importances[indices]
+
+ if feature_names is None:
+ feature_names = indices
+ else:
+ feature_names = np.array(feature_names)[indices]
+
+ table = make_table(feature_names, importances)
+ chart = wandb.visualize("wandb/feature_importances/v1", table)
+
+ return chart
+
+
+def make_table(feature_names, importances):
+ table = wandb.Table(
+ columns=["feature_names", "importances"],
+ data=[[feature_names[i], importances[i]] for i in range(len(feature_names))],
+ )
+ return table
+
+
+def check_for_attribute_on(model, attributes_to_check):
+ for attr in attributes_to_check:
+ if hasattr(model, attr):
+ return attr
+ return None
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..296c7d7780fec21e5f9e3a7a346301c3c38b7de8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/learning_curve.py
@@ -0,0 +1,64 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import model_selection
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def learning_curve(
+ model,
+ X, # noqa: N803
+ y,
+ cv=None,
+ shuffle=False,
+ random_state=None,
+ train_sizes=None,
+ n_jobs=1,
+ scoring=None,
+):
+ """Train model on datasets of varying size and generates plot of score vs size.
+
+ Called by plot_learning_curve to visualize learning curve. Please use the function
+ plot_learning_curve() if you wish to visualize your learning curves.
+ """
+ train_sizes, train_scores, test_scores = model_selection.learning_curve(
+ model,
+ X,
+ y,
+ cv=cv,
+ n_jobs=n_jobs,
+ train_sizes=train_sizes,
+ scoring=scoring,
+ shuffle=shuffle,
+ random_state=random_state,
+ )
+ train_scores_mean = np.mean(train_scores, axis=1)
+ test_scores_mean = np.mean(test_scores, axis=1)
+
+ table = make_table(train_scores_mean, test_scores_mean, train_sizes)
+ chart = wandb.visualize("wandb/learning_curve/v1", table)
+
+ return chart
+
+
+def make_table(train, test, train_sizes):
+ data = []
+ for i in range(len(train)):
+ if utils.check_against_limit(
+ i,
+ "learning_curve",
+ utils.chart_limit / 2,
+ ):
+ break
+ train_set = ["train", utils.round_2(train[i]), train_sizes[i]]
+ test_set = ["test", utils.round_2(test[i]), train_sizes[i]]
+ data.append(train_set)
+ data.append(test_set)
+
+ table = wandb.Table(columns=["dataset", "score", "train_size"], data=data)
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fb0a29f4e7c49939e2d34420c02f9d82d08570b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py
@@ -0,0 +1,69 @@
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def outlier_candidates(regressor, X, y): # noqa: N803
+ # Fit a linear model to X and y to compute MSE
+ regressor.fit(X, y)
+
+ # Leverage is computed as the diagonal of the projection matrix of X
+ leverage = (X * np.linalg.pinv(X).T).sum(1)
+
+ # Compute the rank and the degrees of freedom of the OLS model
+ rank = np.linalg.matrix_rank(X)
+ df = X.shape[0] - rank
+
+ # Compute the MSE from the residuals
+ residuals = y - regressor.predict(X)
+ mse = np.dot(residuals, residuals) / df
+
+ # Compute Cook's distance
+ residuals_studentized = residuals / np.sqrt(mse) / np.sqrt(1 - leverage)
+ distance_ = residuals_studentized**2 / X.shape[1]
+ distance_ *= leverage / (1 - leverage)
+
+ # Compute the influence threshold rule of thumb
+ influence_threshold_ = 4 / X.shape[0]
+ outlier_percentage_ = sum(distance_ >= influence_threshold_) / X.shape[0]
+ outlier_percentage_ *= 100.0
+
+ distance_dict, count = [], 0
+ for d in distance_:
+ distance_dict.append(d)
+ count += 1
+ if utils.check_against_limit(
+ count,
+ "outlier_candidates",
+ utils.chart_limit,
+ ):
+ break
+
+ table = make_table(distance_dict, outlier_percentage_, influence_threshold_)
+ chart = wandb.visualize("wandb/outliers/v1", table)
+
+ return chart
+
+
+def make_table(distance, outlier_percentage, influence_threshold):
+ columns = [
+ "distance",
+ "instance_indicies",
+ "outlier_percentage",
+ "influence_threshold",
+ ]
+
+ data = [
+ [distance[i], i, utils.round_3(outlier_percentage), influence_threshold]
+ for i in range(len(distance))
+ ]
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py
new file mode 100644
index 0000000000000000000000000000000000000000..b45df7b84fa5b3824f99425800bbf0039f7cacd8
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/residuals.py
@@ -0,0 +1,86 @@
+from warnings import simplefilter
+
+from sklearn import model_selection
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def residuals(regressor, X, y): # noqa: N803
+ # Create the train and test splits
+ x_train, x_test, y_train, y_test = model_selection.train_test_split(
+ X, y, test_size=0.2
+ )
+
+ # Store labels and colors for the legend ordered by call
+ regressor.fit(x_train, y_train)
+ train_score_ = regressor.score(x_train, y_train)
+ test_score_ = regressor.score(x_test, y_test)
+
+ y_pred_train = regressor.predict(x_train)
+ residuals_train = y_pred_train - y_train
+
+ y_pred_test = regressor.predict(x_test)
+ residuals_test = y_pred_test - y_test
+
+ table = make_table(
+ y_pred_train,
+ residuals_train,
+ y_pred_test,
+ residuals_test,
+ train_score_,
+ test_score_,
+ )
+ chart = wandb.visualize("wandb/residuals_plot/v1", table)
+
+ return chart
+
+
+def make_table(
+ y_pred_train,
+ residuals_train,
+ y_pred_test,
+ residuals_test,
+ train_score_,
+ test_score_,
+):
+ y_pred_column, dataset_column, residuals_column = [], [], []
+
+ datapoints, max_datapoints_train = 0, 100
+ for pred, residual in zip(y_pred_train, residuals_train):
+ # add class counts from training set
+ y_pred_column.append(pred)
+ dataset_column.append("train")
+ residuals_column.append(residual)
+ datapoints += 1
+ if utils.check_against_limit(datapoints, "residuals", max_datapoints_train):
+ break
+
+ datapoints = 0
+ for pred, residual in zip(y_pred_test, residuals_test):
+ # add class counts from training set
+ y_pred_column.append(pred)
+ dataset_column.append("test")
+ residuals_column.append(residual)
+ datapoints += 1
+ if utils.check_against_limit(datapoints, "residuals", max_datapoints_train):
+ break
+
+ columns = ["dataset", "y_pred", "residuals", "train_score", "test_score"]
+ data = [
+ [
+ dataset_column[i],
+ y_pred_column[i],
+ residuals_column[i],
+ train_score_,
+ test_score_,
+ ]
+ for i in range(len(y_pred_column))
+ ]
+
+ table = wandb.Table(columns=columns, data=data)
+
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py
new file mode 100644
index 0000000000000000000000000000000000000000..a71ba88c8f03d99e6908e4f886ba5d0be4f4dd41
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/silhouette.py
@@ -0,0 +1,118 @@
+from warnings import simplefilter
+
+import numpy as np
+from sklearn.metrics import silhouette_samples, silhouette_score
+from sklearn.preprocessing import LabelEncoder
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def silhouette(clusterer, X, cluster_labels, labels, metric, kmeans): # noqa: N803
+ # Run clusterer for n_clusters in range(len(cluster_ranges), get cluster labels
+ # TODO - keep/delete once we decide if we should train clusterers
+ # or ask for trained models
+ # clusterer.set_params(n_clusters=n_clusters, random_state=42)
+ # cluster_labels = clusterer.fit_predict(X)
+ cluster_labels = np.asarray(cluster_labels)
+ labels = np.asarray(labels)
+
+ le = LabelEncoder()
+ _ = le.fit_transform(cluster_labels)
+ n_clusters = len(np.unique(cluster_labels))
+
+ # The silhouette_score gives the average value for all the samples.
+ # This gives a perspective into the density and separation of the formed
+ # clusters
+ silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
+
+ # Compute the silhouette scores for each sample
+ sample_silhouette_values = silhouette_samples(X, cluster_labels, metric=metric)
+
+ x_sil, y_sil, color_sil = [], [], []
+
+ count, y_lower = 0, 10
+ for i in range(n_clusters):
+ # Aggregate the silhouette scores for samples belonging to
+ # cluster i, and sort them
+ ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
+
+ ith_cluster_silhouette_values.sort()
+
+ size_cluster_i = ith_cluster_silhouette_values.shape[0]
+ y_upper = y_lower + size_cluster_i
+
+ y_values = np.arange(y_lower, y_upper)
+
+ for j in range(len(y_values)):
+ y_sil.append(y_values[j])
+ x_sil.append(ith_cluster_silhouette_values[j])
+ color_sil.append(i)
+ count += 1
+ if utils.check_against_limit(count, "silhouette", utils.chart_limit):
+ break
+
+ # Compute the new y_lower for next plot
+ y_lower = y_upper + 10 # 10 for the 0 samples
+
+ if kmeans:
+ centers = clusterer.cluster_centers_
+ centerx = centers[:, 0]
+ centery = centers[:, 1]
+
+ else:
+ centerx = [None] * len(color_sil)
+ centery = [None] * len(color_sil)
+
+ table = make_table(
+ X[:, 0],
+ X[:, 1],
+ cluster_labels,
+ centerx,
+ centery,
+ y_sil,
+ x_sil,
+ color_sil,
+ silhouette_avg,
+ )
+ chart = wandb.visualize("wandb/silhouette_/v1", table)
+
+ return chart
+
+
+def make_table(x, y, colors, centerx, centery, y_sil, x_sil, color_sil, silhouette_avg):
+ columns = [
+ "x",
+ "y",
+ "colors",
+ "centerx",
+ "centery",
+ "y_sil",
+ "x1",
+ "x2",
+ "color_sil",
+ "silhouette_avg",
+ ]
+
+ data = [
+ [
+ x[i],
+ y[i],
+ colors[i],
+ centerx[colors[i]],
+ centery[colors[i]],
+ y_sil[i],
+ 0,
+ x_sil[i],
+ color_sil[i],
+ silhouette_avg,
+ ]
+ for i in range(len(color_sil))
+ ]
+
+ table = wandb.Table(data=data, columns=columns)
+
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4b6f25ead2fd3c94c302db7693ca3fd529812d9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py
@@ -0,0 +1,62 @@
+from warnings import simplefilter
+
+import numpy as np
+import sklearn
+
+import wandb
+from wandb.integration.sklearn import utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None): # noqa: N803
+ """Calculate summary metrics for both regressors and classifiers.
+
+ Called by plot_summary_metrics to visualize metrics. Please use the function
+ plot_summary_metrics() if you wish to visualize your summary metrics.
+ """
+ y, y_test = np.asarray(y), np.asarray(y_test)
+ metrics = {}
+ model_name = model.__class__.__name__
+
+ y_pred = model.predict(X_test)
+
+ if sklearn.base.is_classifier(model):
+ accuracy_score = sklearn.metrics.accuracy_score(y_test, y_pred)
+ metrics["accuracy_score"] = accuracy_score
+
+ precision = sklearn.metrics.precision_score(y_test, y_pred, average="weighted")
+ metrics["precision"] = precision
+
+ recall = sklearn.metrics.recall_score(y_test, y_pred, average="weighted")
+ metrics["recall"] = recall
+
+ f1_score = sklearn.metrics.f1_score(y_test, y_pred, average="weighted")
+ metrics["f1_score"] = f1_score
+
+ elif sklearn.base.is_regressor(model):
+ mae = sklearn.metrics.mean_absolute_error(y_test, y_pred)
+ metrics["mae"] = mae
+
+ mse = sklearn.metrics.mean_squared_error(y_test, y_pred)
+ metrics["mse"] = mse
+
+ r2_score = sklearn.metrics.r2_score(y_test, y_pred)
+ metrics["r2_score"] = r2_score
+
+ metrics = {name: utils.round_2(metric) for name, metric in metrics.items()}
+
+ table = make_table(metrics, model_name)
+ chart = wandb.visualize("wandb/metrics/v1", table)
+
+ return chart
+
+
+def make_table(metrics, model_name):
+ columns = ["metric_name", "metric_value", "model_name"]
+ table_content = [[name, value, model_name] for name, value in metrics.items()]
+
+ table = wandb.Table(columns=columns, data=table_content)
+
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..710e24c010e108bb4f25d361092a55182ad26917
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__init__.py
@@ -0,0 +1,35 @@
+"""Create and logs charts introspecting models built with scikit-learn to W&B."""
+
+from .classifier import calibration_curve as plot_calibration_curve
+from .classifier import class_proportions as plot_class_proportions
+from .classifier import classifier as plot_classifier
+from .classifier import confusion_matrix as plot_confusion_matrix
+from .classifier import feature_importances as plot_feature_importances
+from .classifier import precision_recall as plot_precision_recall
+from .classifier import roc as plot_roc
+from .clusterer import clusterer as plot_clusterer
+from .clusterer import elbow_curve as plot_elbow_curve
+from .clusterer import silhouette as plot_silhouette
+from .regressor import outlier_candidates as plot_outlier_candidates
+from .regressor import regressor as plot_regressor
+from .regressor import residuals as plot_residuals
+from .shared import learning_curve as plot_learning_curve
+from .shared import summary_metrics as plot_summary_metrics
+
+__all__ = [
+ "plot_classifier",
+ "plot_clusterer",
+ "plot_regressor",
+ "plot_summary_metrics",
+ "plot_learning_curve",
+ "plot_feature_importances",
+ "plot_class_proportions",
+ "plot_calibration_curve",
+ "plot_roc",
+ "plot_precision_recall",
+ "plot_confusion_matrix",
+ "plot_elbow_curve",
+ "plot_silhouette",
+ "plot_residuals",
+ "plot_outlier_candidates",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0024fa3081c3eb174c0bbdc2702f42ff701a60e0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ef2c4b6f194f5fc7150a83050d80d6362fabca8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/clusterer.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/clusterer.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a55a2ec1b06aeffcedb4485eac290bc24b271c0f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/clusterer.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/regressor.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/regressor.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..907c8b695d9087564ba39567d1b03b5a41aa2a7e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/regressor.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae6518158e9fd8130ea7055b5d8c98381c79e93a
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py
new file mode 100644
index 0000000000000000000000000000000000000000..e431c8090b565518315f7906c85314f7d4b0ad9b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/classifier.py
@@ -0,0 +1,329 @@
+"""Define plots for classification models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import numpy as np
+from sklearn import naive_bayes
+
+import wandb
+import wandb.plot
+from wandb.integration.sklearn import calculate, utils
+
+from . import shared
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def classifier(
+ model,
+ X_train, # noqa: N803
+ X_test, # noqa: N803
+ y_train,
+ y_test,
+ y_pred,
+ y_probas,
+ labels,
+ is_binary=False,
+ model_name="Classifier",
+ feature_names=None,
+ log_learning_curve=False,
+):
+ """Generate all sklearn classifier plots supported by W&B.
+
+ The following plots are generated:
+ feature importances, confusion matrix, summary metrics,
+ class proportions, calibration curve, roc curve, precision-recall curve.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+
+ Args:
+ model: (classifier) Takes in a fitted classifier.
+ X_train: (arr) Training set features.
+ y_train: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+ y_pred: (arr) Test set predictions by the model passed.
+ y_probas: (arr) Test set predicted probabilities by the model passed.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+ is_binary: (bool) Is the model passed a binary classifier? Defaults to False
+ model_name: (str) Model name. Defaults to 'Classifier'
+ feature_names: (list) Names for features. Makes plots easier to read by
+ replacing feature indexes with corresponding names.
+ log_learning_curve: (bool) Whether or not to log the learning curve.
+ Defaults to False.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_classifier(
+ model,
+ X_train,
+ X_test,
+ y_train,
+ y_test,
+ y_pred,
+ y_probas,
+ ["cat", "dog"],
+ False,
+ "RandomForest",
+ ["barks", "drools", "plays_fetch", "breed"],
+ )
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+
+ if not isinstance(model, naive_bayes.MultinomialNB):
+ feature_importances(model, feature_names)
+ wandb.termlog("Logged feature importances.")
+
+ if log_learning_curve:
+ shared.learning_curve(model, X_train, y_train)
+ wandb.termlog("Logged learning curve.")
+
+ confusion_matrix(y_test, y_pred, labels)
+ wandb.termlog("Logged confusion matrix.")
+
+ shared.summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test)
+ wandb.termlog("Logged summary metrics.")
+
+ class_proportions(y_train, y_test, labels)
+ wandb.termlog("Logged class proportions.")
+
+ if not isinstance(model, naive_bayes.MultinomialNB):
+ calibration_curve(model, X_train, y_train, model_name)
+ wandb.termlog("Logged calibration curve.")
+
+ roc(y_test, y_probas, labels)
+ wandb.termlog("Logged roc curve.")
+
+ precision_recall(y_test, y_probas, labels)
+ wandb.termlog("Logged precision-recall curve.")
+
+
+def roc(
+ y_true=None,
+ y_probas=None,
+ labels=None,
+ plot_micro=True,
+ plot_macro=True,
+ classes_to_plot=None,
+):
+ """Log the receiver-operating characteristic curve.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_roc(y_true, y_probas, labels)
+ ```
+ """
+ roc_chart = wandb.plot.roc_curve(y_true, y_probas, labels, classes_to_plot)
+ wandb.log({"roc": roc_chart})
+
+
+def confusion_matrix(
+ y_true=None,
+ y_pred=None,
+ labels=None,
+ true_labels=None,
+ pred_labels=None,
+ normalize=False,
+):
+ """Log a confusion matrix to W&B.
+
+ Confusion matrices depict the pattern of misclassifications by a model.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)
+ ```
+ """
+ y_true = np.asarray(y_true)
+ y_pred = np.asarray(y_pred)
+
+ not_missing = utils.test_missing(y_true=y_true, y_pred=y_pred)
+ correct_types = utils.test_types(y_true=y_true, y_pred=y_pred)
+
+ if not_missing and correct_types:
+ confusion_matrix_chart = calculate.confusion_matrix(
+ y_true,
+ y_pred,
+ labels,
+ true_labels,
+ pred_labels,
+ normalize,
+ )
+
+ wandb.log({"confusion_matrix": confusion_matrix_chart})
+
+
+def precision_recall(
+ y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None
+):
+ """Log a precision-recall curve to W&B.
+
+ Precision-recall curves depict the tradeoff between positive predictive value (precision)
+ and true positive rate (recall) as the threshold of a classifier is shifted.
+
+ Args:
+ y_true: (arr) Test set labels.
+ y_probas: (arr) Test set predicted probabilities.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)
+ ```
+ """
+ precision_recall_chart = wandb.plot.pr_curve(
+ y_true, y_probas, labels, classes_to_plot
+ )
+
+ wandb.log({"precision_recall": precision_recall_chart})
+
+
+def feature_importances(
+ model=None, feature_names=None, title="Feature Importance", max_num_features=50
+):
+ """Log a plot depicting the relative importance of each feature for a classifier's decisions.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+ Only works with classifiers that have a feature_importances_ attribute, like trees.
+
+ Args:
+ model: (clf) Takes in a fitted classifier.
+ feature_names: (list) Names for features. Makes plots easier to read by
+ replacing feature indexes with corresponding names.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_feature_importances(model, ["width", "height", "length"])
+ ```
+ """
+ not_missing = utils.test_missing(model=model)
+ correct_types = utils.test_types(model=model)
+ model_fitted = utils.test_fitted(model)
+
+ if not_missing and correct_types and model_fitted:
+ feature_importance_chart = calculate.feature_importances(model, feature_names)
+ wandb.log({"feature_importances": feature_importance_chart})
+
+
+def class_proportions(y_train=None, y_test=None, labels=None):
+ """Plot the distribution of target classes in training and test sets.
+
+ Useful for detecting imbalanced classes.
+
+ Args:
+ y_train: (arr) Training set labels.
+ y_test: (arr) Test set labels.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_class_proportions(y_train, y_test, ["dog", "cat", "owl"])
+ ```
+ """
+ not_missing = utils.test_missing(y_train=y_train, y_test=y_test)
+ correct_types = utils.test_types(y_train=y_train, y_test=y_test)
+ if not_missing and correct_types:
+ y_train, y_test = np.array(y_train), np.array(y_test)
+ class_proportions_chart = calculate.class_proportions(y_train, y_test, labels)
+
+ wandb.log({"class_proportions": class_proportions_chart})
+
+
+def calibration_curve(clf=None, X=None, y=None, clf_name="Classifier"): # noqa: N803
+ """Log a plot depicting how well-calibrated the predicted probabilities of a classifier are.
+
+ Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted
+ probabilities by a baseline logistic regression model, the model passed as
+ an argument, and by both its isotonic calibration and sigmoid calibrations.
+ The closer the calibration curves are to a diagonal the better.
+ A sine wave like curve represents an overfitted classifier, while a cosine
+ wave like curve represents an underfitted classifier.
+ By training isotonic and sigmoid calibrations of the model and comparing
+ their curves we can figure out whether the model is over or underfitting and
+ if so which calibration (sigmoid or isotonic) might help fix this.
+ For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html.
+
+ Should only be called with a fitted classifier (otherwise an error is thrown).
+
+ Please note this function fits variations of the model on the training set when called.
+
+ Args:
+ clf: (clf) Takes in a fitted classifier.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+ model_name: (str) Model name. Defaults to 'Classifier'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_calibration_curve(clf, X, y, "RandomForestClassifier")
+ ```
+ """
+ not_missing = utils.test_missing(clf=clf, X=X, y=y)
+ correct_types = utils.test_types(clf=clf, X=X, y=y)
+ is_fitted = utils.test_fitted(clf)
+ if not_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+ if y.dtype.char == "U" or not ((y == 0) | (y == 1)).all():
+ wandb.termwarn(
+ "This function only supports binary classification at the moment and therefore expects labels to be binary. Skipping calibration curve."
+ )
+ return
+
+ calibration_curve_chart = calculate.calibration_curves(clf, X, y, clf_name)
+
+ wandb.log({"calibration_curve": calibration_curve_chart})
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py
new file mode 100644
index 0000000000000000000000000000000000000000..bced65ae105780961e434b78e6ef316297b5182e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/clusterer.py
@@ -0,0 +1,146 @@
+"""Define plots for clustering models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import pandas as pd
+import sklearn
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def clusterer(model, X_train, cluster_labels, labels=None, model_name="Clusterer"): # noqa: N803
+ """Generates all sklearn clusterer plots supported by W&B.
+
+ The following plots are generated:
+ elbow curve, silhouette plot.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X_train: (arr) Training set features.
+ cluster_labels: (list) Names for cluster labels. Makes plots easier to read
+ by replacing cluster indexes with corresponding names.
+ labels: (list) Named labels for target variable (y). Makes plots easier to
+ read by replacing target values with corresponding index.
+ For example if `labels=['dog', 'cat', 'owl']` all 0s are
+ replaced by dog, 1s by cat.
+ model_name: (str) Model name. Defaults to 'Clusterer'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_clusterer(kmeans, X, cluster_labels, labels, "KMeans")
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+ if isinstance(model, sklearn.cluster.KMeans):
+ elbow_curve(model, X_train)
+ wandb.termlog("Logged elbow curve.")
+
+ silhouette(model, X_train, cluster_labels, labels=labels, kmeans=True)
+
+ else:
+ silhouette(model, X_train, cluster_labels, kmeans=False)
+
+ wandb.termlog("Logged silhouette plot.")
+
+
+def elbow_curve(
+ clusterer=None,
+ X=None, # noqa: N803
+ cluster_ranges=None,
+ n_jobs=1,
+ show_cluster_time=True,
+):
+ """Measures and plots variance explained as a function of the number of clusters.
+
+ Useful in picking the optimal number of clusters.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X: (arr) Training set features.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_elbow_curve(model, X_train)
+ ```
+ """
+ if not hasattr(clusterer, "n_clusters"):
+ wandb.termlog(
+ "n_clusters attribute not in classifier. Cannot plot elbow method."
+ )
+ return
+
+ not_missing = utils.test_missing(clusterer=clusterer)
+ correct_types = utils.test_types
+ is_fitted = utils.test_fitted(clusterer)
+
+ if not_missing and correct_types and is_fitted:
+ elbow_curve_chart = calculate.elbow_curve(
+ clusterer, X, cluster_ranges, n_jobs, show_cluster_time
+ )
+
+ wandb.log({"elbow_curve": elbow_curve_chart})
+
+
+def silhouette(
+ clusterer=None,
+ X=None, # noqa: N803
+ cluster_labels=None,
+ labels=None,
+ metric="euclidean",
+ kmeans=True,
+):
+ """Measures & plots silhouette coefficients.
+
+ Silhouette coefficients near +1 indicate that the sample is far away from
+ the neighboring clusters. A value near 0 indicates that the sample is on or
+ very close to the decision boundary between two neighboring clusters and
+ negative values indicate that the samples might have been assigned to the wrong cluster.
+
+ Should only be called with a fitted clusterer (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (clusterer) Takes in a fitted clusterer.
+ X: (arr) Training set features.
+ cluster_labels: (list) Names for cluster labels. Makes plots easier to read
+ by replacing cluster indexes with corresponding names.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_silhouette(model, X_train, ["spam", "not spam"])
+ ```
+ """
+ not_missing = utils.test_missing(clusterer=clusterer)
+ correct_types = utils.test_types(clusterer=clusterer)
+ is_fitted = utils.test_fitted(clusterer)
+
+ if not_missing and correct_types and is_fitted:
+ if isinstance(X, (pd.DataFrame)):
+ X = X.values # noqa: N806
+ silhouette_chart = calculate.silhouette(
+ clusterer, X, cluster_labels, labels, metric, kmeans
+ )
+ wandb.log({"silhouette_plot": silhouette_chart})
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2840a06dabfd27cbe0d980af2988f6cc1ef0604
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/regressor.py
@@ -0,0 +1,121 @@
+"""Define plots for regression models built with scikit-learn."""
+
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+from . import shared
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def regressor(model, X_train, X_test, y_train, y_test, model_name="Regressor"): # noqa: N803
+ """Generates all sklearn regressor plots supported by W&B.
+
+ The following plots are generated:
+ learning curve, summary metrics, residuals plot, outlier candidates.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Args:
+ model: (regressor) Takes in a fitted regressor.
+ X_train: (arr) Training set features.
+ y_train: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+ model_name: (str) Model name. Defaults to 'Regressor'
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test, "Ridge")
+ ```
+ """
+ wandb.termlog(f"\nPlotting {model_name}.")
+
+ shared.summary_metrics(model, X_train, y_train, X_test, y_test)
+ wandb.termlog("Logged summary metrics.")
+
+ shared.learning_curve(model, X_train, y_train)
+ wandb.termlog("Logged learning curve.")
+
+ outlier_candidates(model, X_train, y_train)
+ wandb.termlog("Logged outlier candidates.")
+
+ residuals(model, X_train, y_train)
+ wandb.termlog("Logged residuals.")
+
+
+def outlier_candidates(regressor=None, X=None, y=None): # noqa: N803
+ """Measures a datapoint's influence on regression model via cook's distance.
+
+ Instances with high influences could potentially be outliers.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Please note this function fits the model on the training set when called.
+
+ Args:
+ model: (regressor) Takes in a fitted regressor.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_outlier_candidates(model, X, y)
+ ```
+ """
+ is_missing = utils.test_missing(regressor=regressor, X=X, y=y)
+ correct_types = utils.test_types(regressor=regressor, X=X, y=y)
+ is_fitted = utils.test_fitted(regressor)
+
+ if is_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+
+ outliers_chart = calculate.outlier_candidates(regressor, X, y)
+ wandb.log({"outlier_candidates": outliers_chart})
+
+
+def residuals(regressor=None, X=None, y=None): # noqa: N803
+ """Measures and plots the regressor's predicted value against the residual.
+
+ The marginal distribution of residuals is also calculated and plotted.
+
+ Should only be called with a fitted regressor (otherwise an error is thrown).
+
+ Please note this function fits variations of the model on the training set when called.
+
+ Args:
+ regressor: (regressor) Takes in a fitted regressor.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_residuals(model, X, y)
+ ```
+ """
+ not_missing = utils.test_missing(regressor=regressor, X=X, y=y)
+ correct_types = utils.test_types(regressor=regressor, X=X, y=y)
+ is_fitted = utils.test_fitted(regressor)
+
+ if not_missing and correct_types and is_fitted:
+ y = np.asarray(y)
+
+ residuals_chart = calculate.residuals(regressor, X, y)
+ wandb.log({"residuals": residuals_chart})
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py
new file mode 100644
index 0000000000000000000000000000000000000000..871dbd742c960d681803f240fbccddff02000733
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/plot/shared.py
@@ -0,0 +1,91 @@
+"""Define plots used by multiple sklearn model classes."""
+
+from warnings import simplefilter
+
+import numpy as np
+
+import wandb
+from wandb.integration.sklearn import calculate, utils
+
+# ignore all future warnings
+simplefilter(action="ignore", category=FutureWarning)
+
+
+def summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None): # noqa: N803
+ """Logs a chart depicting summary metrics for a model.
+
+ Should only be called with a fitted model (otherwise an error is thrown).
+
+ Args:
+ model: (clf or reg) Takes in a fitted regressor or classifier.
+ X: (arr) Training set features.
+ y: (arr) Training set labels.
+ X_test: (arr) Test set features.
+ y_test: (arr) Test set labels.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_summary_metrics(model, X_train, y_train, X_test, y_test)
+ ```
+ """
+ not_missing = utils.test_missing(
+ model=model, X=X, y=y, X_test=X_test, y_test=y_test
+ )
+ correct_types = utils.test_types(
+ model=model, X=X, y=y, X_test=X_test, y_test=y_test
+ )
+ model_fitted = utils.test_fitted(model)
+
+ if not_missing and correct_types and model_fitted:
+ metrics_chart = calculate.summary_metrics(model, X, y, X_test, y_test)
+ wandb.log({"summary_metrics": metrics_chart})
+
+
+def learning_curve(
+ model=None,
+ X=None, # noqa: N803
+ y=None,
+ cv=None,
+ shuffle=False,
+ random_state=None,
+ train_sizes=None,
+ n_jobs=1,
+ scoring=None,
+):
+ """Logs a plot depicting model performance against dataset size.
+
+ Please note this function fits the model to datasets of varying sizes when called.
+
+ Args:
+ model: (clf or reg) Takes in a fitted regressor or classifier.
+ X: (arr) Dataset features.
+ y: (arr) Dataset labels.
+
+ For details on the other keyword arguments, see the documentation for
+ `sklearn.model_selection.learning_curve`.
+
+ Returns:
+ None: To see plots, go to your W&B run page then expand the 'media' tab
+ under 'auto visualizations'.
+
+ Example:
+ ```python
+ wandb.sklearn.plot_learning_curve(model, X, y)
+ ```
+ """
+ not_missing = utils.test_missing(model=model, X=X, y=y)
+ correct_types = utils.test_types(model=model, X=X, y=y)
+ if not_missing and correct_types:
+ if train_sizes is None:
+ train_sizes = np.linspace(0.1, 1.0, 5)
+ y = np.asarray(y)
+
+ learning_curve_chart = calculate.learning_curve(
+ model, X, y, cv, shuffle, random_state, train_sizes, n_jobs, scoring
+ )
+
+ wandb.log({"learning_curve": learning_curve_chart})
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/sklearn/utils.py b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b2ef628bbb4165e15d33cd26feb144bd2e40d11
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/sklearn/utils.py
@@ -0,0 +1,184 @@
+"""Shared utilities for the modules in wandb.sklearn."""
+
+from collections.abc import Iterable, Sequence
+
+import numpy as np
+import pandas as pd
+import scipy
+import sklearn
+
+import wandb
+
+chart_limit = 1000
+
+
+def check_against_limit(count, chart, limit=None):
+ if limit is None:
+ limit = chart_limit
+ if count > limit:
+ warn_chart_limit(limit, chart)
+ return True
+ else:
+ return False
+
+
+def warn_chart_limit(limit, chart):
+ warning = f"using only the first {limit} datapoints to create chart {chart}"
+ wandb.termwarn(warning)
+
+
+def encode_labels(df):
+ le = sklearn.preprocessing.LabelEncoder()
+ # apply le on categorical feature columns
+ categorical_cols = df.select_dtypes(
+ exclude=["int", "float", "float64", "float32", "int32", "int64"]
+ ).columns
+ df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col))
+
+
+def test_types(**kwargs):
+ test_passed = True
+ for k, v in kwargs.items():
+ # check for incorrect types
+ if (
+ (k == "X")
+ or (k == "X_test")
+ or (k == "y")
+ or (k == "y_test")
+ or (k == "y_true")
+ or (k == "y_probas")
+ ):
+ # FIXME: do this individually
+ if not isinstance(
+ v,
+ (
+ Sequence,
+ Iterable,
+ np.ndarray,
+ np.generic,
+ pd.DataFrame,
+ pd.Series,
+ list,
+ ),
+ ):
+ wandb.termerror(f"{k} is not an array. Please try again.")
+ test_passed = False
+ # check for classifier types
+ if k == "model":
+ if (not sklearn.base.is_classifier(v)) and (
+ not sklearn.base.is_regressor(v)
+ ):
+ wandb.termerror(
+ f"{k} is not a classifier or regressor. Please try again."
+ )
+ test_passed = False
+ elif k == "clf" or k == "binary_clf":
+ if not (sklearn.base.is_classifier(v)):
+ wandb.termerror(f"{k} is not a classifier. Please try again.")
+ test_passed = False
+ elif k == "regressor":
+ if not sklearn.base.is_regressor(v):
+ wandb.termerror(f"{k} is not a regressor. Please try again.")
+ test_passed = False
+ elif k == "clusterer":
+ if not (getattr(v, "_estimator_type", None) == "clusterer"):
+ wandb.termerror(f"{k} is not a clusterer. Please try again.")
+ test_passed = False
+ return test_passed
+
+
+def test_fitted(model):
+ try:
+ model.predict(np.zeros((7, 3)))
+ except sklearn.exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ except AttributeError:
+ # Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict``
+ try:
+ sklearn.utils.validation.check_is_fitted(
+ model,
+ [
+ "coef_",
+ "estimator_",
+ "labels_",
+ "n_clusters_",
+ "children_",
+ "components_",
+ "n_components_",
+ "n_iter_",
+ "n_batch_iter_",
+ "explained_variance_",
+ "singular_values_",
+ "mean_",
+ ],
+ all_or_any=any,
+ )
+ except sklearn.exceptions.NotFittedError:
+ wandb.termerror("Please fit the model before passing it in.")
+ return False
+ else:
+ return True
+ except Exception:
+ # Assume it's fitted, since ``NotFittedError`` wasn't raised
+ return True
+
+
+# Test Asummptions for plotting parameters and datasets
+def test_missing(**kwargs):
+ test_passed = True
+ for k, v in kwargs.items():
+ # Missing/empty params/datapoint arrays
+ if v is None:
+ wandb.termerror(f"{k} is None. Please try again.")
+ test_passed = False
+ if (k == "X") or (k == "X_test"):
+ if isinstance(v, scipy.sparse.csr.csr_matrix):
+ v = v.toarray()
+ elif isinstance(v, (pd.DataFrame, pd.Series)):
+ v = v.to_numpy()
+ elif isinstance(v, list):
+ v = np.asarray(v)
+
+ # Warn the user about missing values
+ missing = 0
+ missing = np.count_nonzero(pd.isnull(v))
+ if missing > 0:
+ wandb.termwarn(f"{k} contains {missing} missing values. ")
+ test_passed = False
+ # Ensure the dataset contains only integers
+ non_nums = 0
+ if v.ndim == 1:
+ non_nums = sum(
+ 1
+ for val in v
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ else:
+ non_nums = sum(
+ 1
+ for sl in v
+ for val in sl
+ if (
+ not isinstance(val, (int, float, complex))
+ and not isinstance(val, np.number)
+ )
+ )
+ if non_nums > 0:
+ wandb.termerror(
+ f"{k} contains values that are not numbers. Please vectorize, label encode or one hot encode {k} "
+ "and call the plotting function again."
+ )
+ test_passed = False
+ return test_passed
+
+
+def round_3(n):
+ return round(n, 3)
+
+
+def round_2(n):
+ return round(n, 2)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80f60ef258a10fb2e7ad2f81594084ccd6098f6c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__init__.py
@@ -0,0 +1,10 @@
+"""wandb integration tensorboard module."""
+
+from .log import _log, log, reset_state, tf_summary_to_dict
+from .monkeypatch import patch, unpatch
+
+__all__ = [
+ "patch",
+ "unpatch",
+ "log",
+]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c65ce42be547d555a3e0be0fe8559f186099763e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..958de9dc89be07cc800d3c575ca561069cdb03fd
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/monkeypatch.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/monkeypatch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41672485c2ff6abbc517432c53566d08c15e7284
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/__pycache__/monkeypatch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/log.py b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/log.py
new file mode 100644
index 0000000000000000000000000000000000000000..5062a9b0d14109aae1901e751e7864d701d2b7da
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/log.py
@@ -0,0 +1,351 @@
+import io
+import re
+import time
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+
+import wandb
+import wandb.util
+from wandb.sdk.lib import telemetry
+
+if TYPE_CHECKING:
+ import numpy as np
+
+ from wandb.sdk.internal.tb_watcher import TBHistory
+
+# We have at least the default namestep and a global step to track
+# TODO: reset this structure on wandb.finish
+STEPS: Dict[str, Dict[str, Any]] = {
+ "": {"step": 0},
+ "global": {"step": 0, "last_log": None},
+}
+# TODO(cling): Set these when tensorboard behavior is configured.
+# We support rate limited logging by setting this to number of seconds,
+# can be a floating point.
+RATE_LIMIT_SECONDS: Optional[Union[float, int]] = None
+IGNORE_KINDS = ["graphs"]
+tensor_util = wandb.util.get_module("tensorboard.util.tensor_util")
+
+
+# prefer tensorboard, fallback to protobuf in tensorflow when tboard isn't available
+pb = wandb.util.get_module(
+ "tensorboard.compat.proto.summary_pb2"
+) or wandb.util.get_module("tensorflow.core.framework.summary_pb2")
+
+Summary = pb.Summary if pb else None
+
+
+def make_ndarray(tensor: Any) -> Optional["np.ndarray"]:
+ if tensor_util:
+ res = tensor_util.make_ndarray(tensor)
+ # Tensorboard can log generic objects, and we don't want to save them
+ if res.dtype == "object":
+ return None
+ else:
+ return res # type: ignore
+ else:
+ wandb.termwarn(
+ "Can't convert tensor summary, upgrade tensorboard with `pip"
+ " install tensorboard --upgrade`"
+ )
+ return None
+
+
+def namespaced_tag(tag: str, namespace: str = "") -> str:
+ if not namespace:
+ return tag
+ else:
+ return namespace + "/" + tag
+
+
+def history_image_key(key: str, namespace: str = "") -> str:
+ """Convert invalid filesystem characters to _ for use in History keys.
+
+ Unfortunately this means currently certain image keys will collide silently. We
+ implement this mapping up here in the TensorFlow stuff rather than in the History
+ stuff so that we don't have to store a mapping anywhere from the original keys to
+ the safe ones.
+ """
+ return namespaced_tag(re.sub(r"[/\\]", "_", key), namespace)
+
+
+def tf_summary_to_dict( # noqa: C901
+ tf_summary_str_or_pb: Any, namespace: str = ""
+) -> Optional[Dict[str, Any]]:
+ """Convert a Tensorboard Summary to a dictionary.
+
+ Accepts a tensorflow.summary.Summary, one encoded as a string,
+ or a list of such encoded as strings.
+ """
+ values = {}
+ if hasattr(tf_summary_str_or_pb, "summary"):
+ summary_pb = tf_summary_str_or_pb.summary
+ values[namespaced_tag("global_step", namespace)] = tf_summary_str_or_pb.step
+ values["_timestamp"] = tf_summary_str_or_pb.wall_time
+ elif isinstance(tf_summary_str_or_pb, (str, bytes, bytearray)):
+ summary_pb = Summary()
+ summary_pb.ParseFromString(tf_summary_str_or_pb)
+ elif hasattr(tf_summary_str_or_pb, "__iter__"):
+ summary_pb = [Summary() for _ in range(len(tf_summary_str_or_pb))]
+ for i, summary in enumerate(tf_summary_str_or_pb):
+ summary_pb[i].ParseFromString(summary)
+ if i > 0:
+ summary_pb[0].MergeFrom(summary_pb[i])
+ summary_pb = summary_pb[0]
+ else:
+ summary_pb = tf_summary_str_or_pb
+
+ if not hasattr(summary_pb, "value") or len(summary_pb.value) == 0:
+ # Ignore these, caller is responsible for handling None
+ return None
+
+ def encode_images(_img_strs: List[bytes], _value: Any) -> None:
+ try:
+ from PIL import Image
+ except ImportError:
+ wandb.termwarn(
+ "Install pillow if you are logging images with Tensorboard. "
+ "To install, run `pip install pillow`.",
+ repeat=False,
+ )
+ return None
+
+ if len(_img_strs) == 0:
+ return None
+
+ images: List[Union[wandb.Video, wandb.Image]] = []
+ for _img_str in _img_strs:
+ # Supports gifs from TensorboardX
+ if _img_str.startswith(b"GIF"):
+ images.append(wandb.Video(io.BytesIO(_img_str), format="gif"))
+ else:
+ images.append(wandb.Image(Image.open(io.BytesIO(_img_str))))
+ tag_idx = _value.tag.rsplit("/", 1)
+ if len(tag_idx) > 1 and tag_idx[1].isdigit():
+ tag, idx = tag_idx
+ values.setdefault(history_image_key(tag, namespace), []).extend(images)
+ else:
+ values[history_image_key(_value.tag, namespace)] = images
+
+ return None
+
+ for value in summary_pb.value:
+ kind = value.WhichOneof("value")
+ if kind in IGNORE_KINDS:
+ continue
+ if kind == "simple_value":
+ values[namespaced_tag(value.tag, namespace)] = value.simple_value
+ elif kind == "tensor":
+ plugin_name = value.metadata.plugin_data.plugin_name
+ if plugin_name == "scalars" or plugin_name == "":
+ values[namespaced_tag(value.tag, namespace)] = make_ndarray(
+ value.tensor
+ )
+ elif plugin_name == "images":
+ img_strs = value.tensor.string_val[2:] # First two items are dims.
+ encode_images(img_strs, value)
+ elif plugin_name == "histograms":
+ # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/summary_v2.py#L15-L26
+ ndarray = make_ndarray(value.tensor)
+ if ndarray is None:
+ continue
+ shape = ndarray.shape
+ counts = []
+ bins = []
+ if shape[0] > 1:
+ bins.append(ndarray[0][0]) # Add the left most edge
+ for v in ndarray:
+ counts.append(v[2])
+ bins.append(v[1]) # Add the right most edges
+ elif shape[0] == 1:
+ counts = [ndarray[0][2]]
+ bins = ndarray[0][:2]
+ if len(counts) > 0:
+ try:
+ # TODO: we should just re-bin if there are too many buckets
+ values[namespaced_tag(value.tag, namespace)] = wandb.Histogram(
+ np_histogram=(counts, bins) # type: ignore
+ )
+ except ValueError:
+ wandb.termwarn(
+ f'Not logging key "{namespaced_tag(value.tag, namespace)}". '
+ f"Histograms must have fewer than {wandb.Histogram.MAX_LENGTH} bins",
+ repeat=False,
+ )
+ elif plugin_name == "pr_curves":
+ pr_curve_data = make_ndarray(value.tensor)
+ if pr_curve_data is None:
+ continue
+ precision = pr_curve_data[-2, :].tolist()
+ recall = pr_curve_data[-1, :].tolist()
+ # TODO: (kdg) implement spec for showing additional info in tool tips
+ # true_pos = pr_curve_data[1,:]
+ # false_pos = pr_curve_data[2,:]
+ # true_neg = pr_curve_data[1,:]
+ # false_neg = pr_curve_data[1,:]
+ # threshold = [1.0 / n for n in range(len(true_pos), 0, -1)]
+ # min of each in case tensorboard ever changes their pr_curve
+ # to allow for different length outputs
+ data = []
+ for i in range(min(len(precision), len(recall))):
+ # drop additional threshold values if they exist
+ if precision[i] != 0 or recall[i] != 0:
+ data.append((recall[i], precision[i]))
+ # sort data so custom chart looks the same as tb generated pr curve
+ # ascending recall, descending precision for the same recall values
+ data = sorted(data, key=lambda x: (x[0], -x[1]))
+ data_table = wandb.Table(data=data, columns=["recall", "precision"])
+ name = namespaced_tag(value.tag, namespace)
+
+ values[name] = wandb.plot_table(
+ "wandb/line/v0",
+ data_table,
+ {"x": "recall", "y": "precision"},
+ {"title": f"{name} Precision v. Recall"},
+ )
+ elif kind == "image":
+ img_str = value.image.encoded_image_string
+ encode_images([img_str], value)
+ # Coming soon...
+ # elif kind == "audio":
+ # audio = wandb.Audio(
+ # six.BytesIO(value.audio.encoded_audio_string),
+ # sample_rate=value.audio.sample_rate,
+ # content_type=value.audio.content_type,
+ # )
+ elif kind == "histo":
+ tag = namespaced_tag(value.tag, namespace)
+ if len(value.histo.bucket_limit) >= 3:
+ first = (
+ value.histo.bucket_limit[0]
+ + value.histo.bucket_limit[0]
+ - value.histo.bucket_limit[1]
+ )
+ last = (
+ value.histo.bucket_limit[-2]
+ + value.histo.bucket_limit[-2]
+ - value.histo.bucket_limit[-3]
+ )
+ np_histogram = (
+ list(value.histo.bucket),
+ [first] + value.histo.bucket_limit[:-1] + [last],
+ )
+ try:
+ # TODO: we should just re-bin if there are too many buckets
+ values[tag] = wandb.Histogram(np_histogram=np_histogram) # type: ignore
+ except ValueError:
+ wandb.termwarn(
+ f"Not logging key {tag!r}. "
+ f"Histograms must have fewer than {wandb.Histogram.MAX_LENGTH} bins",
+ repeat=False,
+ )
+ else:
+ # TODO: is there a case where we can render this?
+ wandb.termwarn(
+ f"Not logging key {tag!r}. Found a histogram with only 2 bins.",
+ repeat=False,
+ )
+ # TODO(jhr): figure out how to share this between userspace and internal process or dont
+ # elif value.tag == "_hparams_/session_start_info":
+ # if wandb.util.get_module("tensorboard.plugins.hparams"):
+ # from tensorboard.plugins.hparams import plugin_data_pb2
+ #
+ # plugin_data = plugin_data_pb2.HParamsPluginData() #
+ # plugin_data.ParseFromString(value.metadata.plugin_data.content)
+ # for key, param in six.iteritems(plugin_data.session_start_info.hparams):
+ # if not wandb.run.config.get(key):
+ # wandb.run.config[key] = (
+ # param.number_value or param.string_value or param.bool_value
+ # )
+ # else:
+ # wandb.termerror(
+ # "Received hparams tf.summary, but could not import "
+ # "the hparams plugin from tensorboard"
+ # )
+ return values
+
+
+def reset_state() -> None:
+ """Internal method for resetting state, called by wandb.finish()."""
+ global STEPS
+ STEPS = {"": {"step": 0}, "global": {"step": 0, "last_log": None}}
+
+
+def _log(
+ tf_summary_str_or_pb: Any,
+ history: Optional["TBHistory"] = None,
+ step: int = 0,
+ namespace: str = "",
+ **kwargs: Any,
+) -> None:
+ """Logs a tfsummary to wandb.
+
+ Can accept a tf summary string or parsed event. Will use wandb.run.history unless a
+ history object is passed. Can optionally namespace events. Results are committed
+ when step increases for this namespace.
+
+ NOTE: This assumes that events being passed in are in chronological order
+ """
+ global STEPS
+ global RATE_LIMIT_SECONDS
+ # To handle multiple global_steps, we keep track of them here instead
+ # of the global log
+ last_step = STEPS.get(namespace, {"step": 0})
+
+ # Commit our existing data if this namespace increased its step
+ commit = False
+ if last_step["step"] < step:
+ commit = True
+
+ log_dict = tf_summary_to_dict(tf_summary_str_or_pb, namespace)
+ if log_dict is None:
+ # not an event, just return
+ return
+
+ # Pass timestamp to history for loading historic data
+ timestamp = log_dict.get("_timestamp", time.time())
+ # Store our initial timestamp
+ if STEPS["global"]["last_log"] is None:
+ STEPS["global"]["last_log"] = timestamp
+ # Rollup events that share the same step across namespaces
+ if commit and step == STEPS["global"]["step"]:
+ commit = False
+ # Always add the biggest global_step key for non-default namespaces
+ if step > STEPS["global"]["step"]:
+ STEPS["global"]["step"] = step
+ if namespace != "":
+ log_dict["global_step"] = STEPS["global"]["step"]
+
+ # Keep internal step counter
+ STEPS[namespace] = {"step": step}
+
+ if commit:
+ # Only commit our data if we're below the rate limit or don't have one
+ if (
+ RATE_LIMIT_SECONDS is None
+ or timestamp - STEPS["global"]["last_log"] >= RATE_LIMIT_SECONDS
+ ):
+ if history is None:
+ if wandb.run is not None:
+ wandb.run._log({})
+ else:
+ history.add({})
+
+ STEPS["global"]["last_log"] = timestamp
+
+ if history is None:
+ if wandb.run is not None:
+ wandb.run._log(log_dict, commit=False)
+ else:
+ history._row_update(log_dict)
+
+
+def log(tf_summary_str_or_pb: Any, step: int = 0, namespace: str = "") -> None:
+ if wandb.run is None:
+ raise wandb.Error(
+ "You must call `wandb.init()` before calling `wandb.tensorflow.log`"
+ )
+
+ with telemetry.context() as tel:
+ tel.feature.tensorboard_log = True
+
+ _log(tf_summary_str_or_pb, namespace=namespace, step=step)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0db49aaf79bad018642eea9e1d555f65827ba6e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/tensorboard/monkeypatch.py
@@ -0,0 +1,186 @@
+"""monkeypatch: patch code to add tensorboard hooks."""
+
+import os
+import re
+import socket
+from typing import Any, Optional
+
+import wandb
+import wandb.util
+
+TENSORBOARD_C_MODULE = "tensorflow.python.ops.gen_summary_ops"
+TENSORBOARD_X_MODULE = "tensorboardX.writer"
+TENSORFLOW_PY_MODULE = "tensorflow.python.summary.writer.writer"
+TENSORBOARD_WRITER_MODULE = "tensorboard.summary.writer.event_file_writer"
+TENSORBOARD_PYTORCH_MODULE = "torch.utils.tensorboard.writer"
+
+
+def unpatch() -> None:
+ for module, method in wandb.patched["tensorboard"]:
+ writer = wandb.util.get_module(module, lazy=False)
+ setattr(writer, method, getattr(writer, f"orig_{method}"))
+ wandb.patched["tensorboard"] = []
+
+
+def patch(
+ save: bool = True,
+ tensorboard_x: Optional[bool] = None,
+ pytorch: Optional[bool] = None,
+ root_logdir: str = "",
+) -> None:
+ if len(wandb.patched["tensorboard"]) > 0:
+ raise ValueError(
+ "Tensorboard already patched. Call `wandb.tensorboard.unpatch()` first; "
+ "remove `sync_tensorboard=True` from `wandb.init`; "
+ "or only call `wandb.tensorboard.patch` once."
+ )
+
+ # TODO: Some older versions of tensorflow don't require tensorboard to be present.
+ # we may want to lift this requirement, but it's safer to have it for now
+ wandb.util.get_module(
+ "tensorboard", required="Please install tensorboard package", lazy=False
+ )
+ c_writer = wandb.util.get_module(TENSORBOARD_C_MODULE, lazy=False)
+ py_writer = wandb.util.get_module(TENSORFLOW_PY_MODULE, lazy=False)
+ tb_writer = wandb.util.get_module(TENSORBOARD_WRITER_MODULE, lazy=False)
+ pt_writer = wandb.util.get_module(TENSORBOARD_PYTORCH_MODULE, lazy=False)
+ tbx_writer = wandb.util.get_module(TENSORBOARD_X_MODULE, lazy=False)
+
+ if not pytorch and not tensorboard_x and c_writer:
+ _patch_tensorflow2(
+ writer=c_writer,
+ module=TENSORBOARD_C_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ # This is for tensorflow <= 1.15 (tf.compat.v1.summary.FileWriter)
+ if py_writer:
+ _patch_file_writer(
+ writer=py_writer,
+ module=TENSORFLOW_PY_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if tb_writer:
+ _patch_file_writer(
+ writer=tb_writer,
+ module=TENSORBOARD_WRITER_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if pt_writer:
+ _patch_file_writer(
+ writer=pt_writer,
+ module=TENSORBOARD_PYTORCH_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if tbx_writer:
+ _patch_file_writer(
+ writer=tbx_writer,
+ module=TENSORBOARD_X_MODULE,
+ save=save,
+ root_logdir=root_logdir,
+ )
+ if not c_writer and not tb_writer and not tb_writer:
+ wandb.termerror("Unsupported tensorboard configuration")
+
+
+def _patch_tensorflow2(
+ writer: Any,
+ module: Any,
+ save: bool = True,
+ root_logdir: str = "",
+) -> None:
+ # This configures TensorFlow 2 style Tensorboard logging
+ old_csfw_func = writer.create_summary_file_writer
+ logdir_hist = []
+
+ def new_csfw_func(*args: Any, **kwargs: Any) -> Any:
+ logdir = (
+ kwargs["logdir"].numpy().decode("utf8")
+ if hasattr(kwargs["logdir"], "numpy")
+ else kwargs["logdir"]
+ )
+ logdir_hist.append(logdir)
+ root_logdir_arg = root_logdir
+
+ if len(set(logdir_hist)) > 1 and root_logdir == "":
+ wandb.termwarn(
+ "When using several event log directories, "
+ 'please call `wandb.tensorboard.patch(root_logdir="...")` before `wandb.init`'
+ )
+ # if the logdir contains the hostname, the writer was not given a logdir.
+ # In this case, the generated logdir
+ # is generated and ends with the hostname, update the root_logdir to match.
+ hostname = socket.gethostname()
+ search = re.search(rf"-\d+_{hostname}", logdir)
+ if search:
+ root_logdir_arg = logdir[: search.span()[1]]
+ elif root_logdir is not None and not os.path.abspath(logdir).startswith(
+ os.path.abspath(root_logdir)
+ ):
+ wandb.termwarn(
+ "Found log directory outside of given root_logdir, "
+ f"dropping given root_logdir for event file in {logdir}"
+ )
+ root_logdir_arg = ""
+
+ _notify_tensorboard_logdir(logdir, save=save, root_logdir=root_logdir_arg)
+ return old_csfw_func(*args, **kwargs)
+
+ writer.orig_create_summary_file_writer = old_csfw_func
+ writer.create_summary_file_writer = new_csfw_func
+ wandb.patched["tensorboard"].append([module, "create_summary_file_writer"])
+
+
+def _patch_file_writer(
+ writer: Any,
+ module: Any,
+ save: bool = True,
+ root_logdir: str = "",
+) -> None:
+ # This configures non-TensorFlow Tensorboard logging, or tensorflow <= 1.15
+ logdir_hist = []
+
+ class TBXEventFileWriter(writer.EventFileWriter):
+ def __init__(self, logdir: str, *args: Any, **kwargs: Any) -> None:
+ logdir_hist.append(logdir)
+ root_logdir_arg = root_logdir
+ if len(set(logdir_hist)) > 1 and root_logdir == "":
+ wandb.termwarn(
+ "When using several event log directories, "
+ 'please call `wandb.tensorboard.patch(root_logdir="...")` before `wandb.init`'
+ )
+
+ # if the logdir contains the hostname, the writer was not given a logdir.
+ # In this case, the logdir is generated and ends with the hostname,
+ # update the root_logdir to match.
+ hostname = socket.gethostname()
+ search = re.search(rf"-\d+_{hostname}", logdir)
+ if search:
+ root_logdir_arg = logdir[: search.span()[1]]
+
+ elif root_logdir is not None and not os.path.abspath(logdir).startswith(
+ os.path.abspath(root_logdir)
+ ):
+ wandb.termwarn(
+ "Found log directory outside of given root_logdir, "
+ f"dropping given root_logdir for event file in {logdir}"
+ )
+ root_logdir_arg = ""
+
+ _notify_tensorboard_logdir(logdir, save=save, root_logdir=root_logdir_arg)
+
+ super().__init__(logdir, *args, **kwargs)
+
+ writer.orig_EventFileWriter = writer.EventFileWriter
+ writer.EventFileWriter = TBXEventFileWriter
+ wandb.patched["tensorboard"].append([module, "EventFileWriter"])
+
+
+def _notify_tensorboard_logdir(
+ logdir: str, save: bool = True, root_logdir: str = ""
+) -> None:
+ if wandb.run is not None:
+ wandb.run._tensorboard_callback(logdir, save=save, root_logdir=root_logdir)
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5a5838c7d3eb5e5ea9e50b420bf42a605084dc6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__init__.py
@@ -0,0 +1,5 @@
+"""api."""
+
+from wandb.integration.tensorboard import log
+
+from .estimator_hook import WandbHook
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71a4b1fa8e005bedcf94faa508bfa22e1db7bb44
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/estimator_hook.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/estimator_hook.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e789f8ab06d89bdbf69211c1cb9ad5b60a01dbe
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/__pycache__/estimator_hook.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..88d58abe3c6ee81759ce01a8e7254e1e324034de
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/tensorflow/estimator_hook.py
@@ -0,0 +1,54 @@
+import tensorflow as tf
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+if hasattr(tf.estimator, "SessionRunHook"):
+ # In tf 1.14 and beyond, SessionRunHook is in the estimator package.
+ SessionRunHook = tf.estimator.SessionRunHook
+ SessionRunArgs = tf.estimator.SessionRunArgs
+else:
+ # In older versions it's in train.
+ SessionRunHook = tf.train.SessionRunHook
+ SessionRunArgs = tf.train.SessionRunArgs
+
+if hasattr(tf.train, "get_global_step"):
+ get_global_step = tf.train.get_global_step
+else:
+ get_global_step = tf.compat.v1.train.get_global_step
+
+if hasattr(tf.summary, "merge_all"):
+ merge_all_summaries = tf.summary.merge_all
+else:
+ merge_all_summaries = tf.compat.v1.summary.merge_all
+
+
+class WandbHook(SessionRunHook):
+ def __init__(self, summary_op=None, steps_per_log=1000, history=None):
+ self._summary_op = summary_op
+ self._steps_per_log = steps_per_log
+ self._history = history
+
+ with telemetry.context() as tel:
+ tel.feature.estimator_hook = True
+
+ def begin(self):
+ if wandb.run is None:
+ raise wandb.Error("You must call `wandb.init()` before calling `WandbHook`")
+ if self._summary_op is None:
+ self._summary_op = merge_all_summaries()
+ self._step = -1
+
+ def before_run(self, run_context):
+ return SessionRunArgs(
+ {"summary": self._summary_op, "global_step": get_global_step()}
+ )
+
+ def after_run(self, run_context, run_values):
+ step = run_values.results["global_step"]
+ if step % self._steps_per_log == 0:
+ wandb.tensorboard._log(
+ run_values.results["summary"],
+ history=self._history,
+ step=step,
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/torch/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9932b7926375ca23a73e7d764607d645f00795c
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53e0c411add71ee7be8891c4043969debac0c058
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/torch/wandb_torch.py b/venv/lib/python3.10/site-packages/wandb/integration/torch/wandb_torch.py
new file mode 100644
index 0000000000000000000000000000000000000000..28d5971f8fd640ef6315aa22cb795163bc9d0724
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/torch/wandb_torch.py
@@ -0,0 +1,554 @@
+"""PyTorch-specific functionality."""
+
+import itertools
+from functools import reduce
+from operator import mul
+from typing import TYPE_CHECKING, List
+
+import wandb
+from wandb import util
+from wandb.data_types import Node
+
+torch = None
+
+if TYPE_CHECKING:
+ from torch import Tensor
+ from torch.nn import Module
+
+
+def nested_shape(array_or_tuple, seen=None):
+ """Figure out the shape of tensors possibly embedded in tuples.
+
+ for example:
+ - [0,0] returns (2)
+ - ([0,0], [0,0]) returns (2,2)
+ - (([0,0], [0,0]),[0,0]) returns ((2,2),2).
+ """
+ if seen is None:
+ seen = set()
+ if hasattr(array_or_tuple, "size"):
+ # pytorch tensors use V.size() to get size of tensor
+ return list(array_or_tuple.size())
+ elif hasattr(array_or_tuple, "get_shape"):
+ # tensorflow uses V.get_shape() to get size of tensor
+ return array_or_tuple.get_shape().as_list()
+ elif hasattr(array_or_tuple, "shape"):
+ return array_or_tuple.shape
+
+ seen.add(id(array_or_tuple))
+ try:
+ # treat object as iterable
+ return [
+ nested_shape(item, seen) if id(item) not in seen else 0
+ for item in list(array_or_tuple)
+ ]
+ except TypeError:
+ # object is not actually iterable
+ # LB: Maybe we should throw an error?
+ return []
+
+
+LOG_TRACK_COUNT, LOG_TRACK_THRESHOLD = range(2)
+
+
+def log_track_init(log_freq: int) -> List[int]:
+ """Create tracking structure used by log_track_update."""
+ log_track = [0, 0]
+ log_track[LOG_TRACK_THRESHOLD] = log_freq
+ return log_track
+
+
+def log_track_update(log_track: int) -> bool:
+ """Count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached."""
+ log_track[LOG_TRACK_COUNT] += 1
+ if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]:
+ return False
+ log_track[LOG_TRACK_COUNT] = 0
+ return True
+
+
+class TorchHistory:
+ """History methods specific to PyTorch."""
+
+ def __init__(self):
+ global torch
+ torch = wandb.util.get_module("torch", "Could not import torch")
+ self._hook_handles = {}
+ self._num_bins = 64
+ self._is_cuda_histc_supported = None
+ self.hook_torch = TorchGraph.hook_torch
+
+ def add_log_parameters_hook(
+ self,
+ module: "Module",
+ name: str = "",
+ prefix: str = "",
+ log_freq: int = 0,
+ ) -> None:
+ """This instruments hooks into the pytorch module.
+
+ log parameters after a forward pass
+ log_freq - log gradients/parameters every N batches.
+ """
+ # if name is not None:
+ prefix = prefix + name
+
+ if not hasattr(module, "_wandb_hook_names"):
+ module._wandb_hook_names = []
+
+ def parameter_log_hook(module, input_, output, log_track):
+ if not log_track_update(log_track):
+ return
+ for name, parameter in module.named_parameters():
+ # for pytorch 0.3 Variables
+ if isinstance(parameter, torch.autograd.Variable):
+ data = parameter.data
+ else:
+ data = parameter
+ self.log_tensor_stats(data.cpu(), "parameters/" + prefix + name)
+
+ log_track_params = log_track_init(log_freq)
+ try:
+ hook = module.register_forward_hook(
+ lambda mod, inp, outp: parameter_log_hook(
+ mod, inp, outp, log_track_params
+ )
+ )
+ self._hook_handles["parameters/" + prefix] = hook
+ module._wandb_hook_names.append("parameters/" + prefix)
+ except RuntimeError as e:
+ wandb.termwarn(
+ f"Trying to register forward_hook failed ({e}) - skipping parameter tracking."
+ )
+
+ def add_log_gradients_hook(
+ self,
+ module: "Module",
+ name: str = "",
+ prefix: str = "",
+ log_freq: int = 0,
+ ) -> None:
+ """This instruments hooks into the PyTorch module slog gradients after a backward pass.
+
+ Args:
+ module: torch.nn.Module - the module to instrument
+ name: str - the name of the module
+ prefix: str - the prefix to add to the name
+ log_freq: log gradients/parameters every N batches
+ """
+ # if name is not None:
+ prefix = prefix + name
+
+ if not hasattr(module, "_wandb_hook_names"):
+ module._wandb_hook_names = []
+
+ for name, parameter in module.named_parameters():
+ if parameter.requires_grad:
+ log_track_grad = log_track_init(log_freq)
+ module._wandb_hook_names.append("gradients/" + prefix + name)
+ self._hook_variable_gradient_stats(
+ parameter, "gradients/" + prefix + name, log_track_grad
+ )
+
+ def log_tensor_stats(self, tensor, name): # noqa: C901
+ """Add distribution statistics on a tensor's elements to the current History entry."""
+ # TODO Handle the case of duplicate names.
+ if isinstance(tensor, (tuple, list)):
+ while isinstance(tensor, (tuple, list)) and isinstance(
+ tensor[0], (tuple, list)
+ ):
+ tensor = [item for sublist in tensor for item in sublist]
+ tensor = torch.cat([t.detach().clone().reshape(-1) for t in tensor])
+
+ tensor = tensor.detach().clone()
+ # checking for inheritance from _TensorBase didn't work for some reason
+ if not hasattr(tensor, "shape"):
+ cls = type(tensor)
+ raise TypeError(f"Expected Tensor, not {cls.__module__}.{cls.__name__}")
+
+ # Sparse tensors have a bunch of implicit zeros. In order to histo them correctly,
+ # we have to count them up and add them to the histo ourselves.
+ sparse_zeros = None
+ if tensor.is_sparse:
+ # Have to call this on a sparse tensor before most other ops.
+ tensor = tensor.cpu().coalesce()
+
+ backing_values = tensor._values()
+ sparse_zeros = tensor.numel() - backing_values.numel()
+ tensor = backing_values
+
+ flat = tensor.reshape(-1)
+
+ if flat.is_cuda:
+ if self._is_cuda_histc_supported is None:
+ try:
+ flat.histc(bins=self._num_bins)
+ except RuntimeError:
+ self._is_cuda_histc_supported = False
+ else:
+ self._is_cuda_histc_supported = True
+
+ # As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32)
+ if not self._is_cuda_histc_supported:
+ flat = flat.cpu()
+ elif not isinstance(
+ flat, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor)
+ ):
+ flat = flat.type(torch.cuda.FloatTensor)
+
+ # Since we use histc, we need to make sure that torch supports the operation on CPU,
+ # otherwise we'll get a runtime error. Hence, we need to upcast to float32.
+ if not flat.is_cuda and not isinstance(
+ flat, (torch.FloatTensor, torch.DoubleTensor)
+ ):
+ flat = flat.type(torch.FloatTensor)
+
+ # Skip logging if all values are nan or inf or the tensor is empty.
+ if self._no_finite_values(flat):
+ return
+
+ # Remove nans and infs if present. There's no good way to represent that in histograms.
+ flat = self._remove_infs_nans(flat)
+
+ tmin = flat.min().item()
+ tmax = flat.max().item()
+ if sparse_zeros:
+ # If we've got zeros to add in, make sure zero is in the hist range.
+ tmin = 0 if tmin > 0 else tmin
+ tmax = 0 if tmax < 0 else tmax
+ # Anecdotally, this can somehow happen sometimes. Maybe a precision error
+ # in min()/max() above. Swap here to prevent a runtime error.
+ # If all values are equal, just return a single bin.
+ if tmin > tmax:
+ tmin, tmax = tmax, tmin
+ if tmin == tmax:
+ tensor = torch.Tensor([flat.numel()])
+ tensor = tensor.cpu().clone().detach()
+ bins = torch.Tensor([tmin, tmax])
+ else:
+ tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax)
+ tensor = tensor.cpu().detach().clone()
+ bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1)
+
+ # Add back zeroes from a sparse tensor.
+ if sparse_zeros:
+ bins_np = bins.numpy()
+ tensor_np = tensor.numpy()
+ bin_idx = 0
+ num_buckets = len(bins_np) - 1
+ for i in range(num_buckets):
+ start = bins_np[i]
+ end = bins_np[i + 1]
+ # There are 3 cases to consider here, all of which mean we've found the right bucket
+ # 1. The bucket range contains zero.
+ # 2. The bucket range lower bound *is* zero.
+ # 3. This is the last bucket and the bucket range upper bound is zero.
+ if (start <= 0 and end > 0) or (i == num_buckets - 1 and end == 0):
+ bin_idx = i
+ break
+
+ tensor_np[bin_idx] += sparse_zeros
+ tensor = torch.Tensor(tensor_np)
+ bins = torch.Tensor(bins_np)
+
+ wandb.run._log(
+ {name: wandb.Histogram(np_histogram=(tensor.tolist(), bins.tolist()))},
+ commit=False,
+ )
+
+ def _hook_variable_gradient_stats(self, var, name, log_track):
+ """Logs a Variable's gradient's distribution statistics next time backward() is called on it."""
+ if not isinstance(var, torch.autograd.Variable):
+ cls = type(var)
+ raise TypeError(
+ f"Expected torch.Variable, not {cls.__module__}.{cls.__name__}"
+ )
+
+ handle = self._hook_handles.get(name)
+ if handle is not None and self._torch_hook_handle_is_valid(handle):
+ raise ValueError(f'A hook has already been set under name "{name}"')
+
+ def _callback(grad, log_track):
+ if not log_track_update(log_track):
+ return
+ self.log_tensor_stats(grad.data, name)
+
+ handle = var.register_hook(lambda grad: _callback(grad, log_track))
+ self._hook_handles[name] = handle
+ return handle
+
+ def unhook_all(self):
+ for handle in self._hook_handles.values():
+ handle.remove()
+ self._hook_handles = {}
+
+ def unhook(self, name):
+ handle = self._hook_handles.pop(name)
+ handle.remove()
+
+ def _torch_hook_handle_is_valid(self, handle):
+ d = handle.hooks_dict_ref()
+ if d is None:
+ return False
+ else:
+ return handle.id in d
+
+ def _no_finite_values(self, tensor: "Tensor") -> bool:
+ return tensor.shape == torch.Size([0]) or (~torch.isfinite(tensor)).all().item()
+
+ def _remove_infs_nans(self, tensor: "Tensor") -> "Tensor":
+ if not torch.isfinite(tensor).all():
+ tensor = tensor[torch.isfinite(tensor)]
+
+ return tensor
+
+
+class TorchGraph(wandb.data_types.Graph):
+ def __init__(self):
+ super().__init__("torch")
+ self._graph_hooks = set()
+
+ @classmethod
+ def hook_torch(cls, model, criterion=None, graph_idx=0):
+ wandb.termlog("logging graph, to disable use `wandb.watch(log_graph=False)`")
+ graph = TorchGraph()
+ graph.hook_torch_modules(model, criterion, graph_idx=graph_idx)
+ return graph
+
+ def create_forward_hook(self, name, graph_idx):
+ graph = self
+
+ def after_forward_hook(module, input, output):
+ if id(module) not in self._graph_hooks:
+ # hook already processed -> noop
+ return
+ if not isinstance(output, tuple):
+ output = (output,)
+ parameters = [
+ (pname, list(param.size()))
+ for pname, param in module.named_parameters()
+ ]
+
+ node = Node(
+ id=id(module),
+ name=name,
+ class_name=str(module),
+ output_shape=nested_shape(output),
+ parameters=parameters,
+ num_parameters=[reduce(mul, size, 1) for (pname, size) in parameters],
+ )
+ graph.nodes_by_id[id(module)] = node
+ for param in module.parameters():
+ graph.nodes_by_id[id(param)] = node
+ graph.add_node(node)
+ if not graph.criterion_passed:
+ if hasattr(output[0], "grad_fn"):
+ graph.criterion = output[0].grad_fn
+ elif (
+ isinstance(output[0], list)
+ and output[0]
+ and hasattr(output[0][0], "grad_fn")
+ ):
+ graph.criterion = output[0][0].grad_fn
+
+ # hook has been processed
+ self._graph_hooks -= {id(module)}
+
+ if not self._graph_hooks:
+ # we went through the entire graph
+ wandb.run.summary[f"graph_{graph_idx}"] = self
+
+ return after_forward_hook
+
+ def hook_torch_modules(
+ self, module, criterion=None, prefix=None, graph_idx=0, parent=None
+ ):
+ torch = util.get_module("torch", "Could not import torch")
+ layers = 0
+ graph = self
+ if hasattr(module, "_wandb_watch_called") and module._wandb_watch_called:
+ raise ValueError(
+ "You can only call `wandb.watch` once per model. Pass a new instance of the model if you need to call wandb.watch again in your code."
+ )
+ module._wandb_watch_called = True
+ if criterion:
+ graph.criterion = criterion
+ graph.criterion_passed = True
+
+ for name, sub_module in module.named_children():
+ name = name or str(layers)
+ if prefix:
+ name = prefix + "." + name
+ layers += 1
+ if not isinstance(sub_module, torch.nn.Module):
+ # TODO: Why does this happen?
+ break
+
+ # Trying to support torch >0.3 making this code complicated
+ # We want a list of types that we should recurse into
+ # Torch 0.3 uses containers
+ # 0.4 has ModuleList
+ # 0.4.1 has ModuleDict
+ module_types = [
+ getattr(torch.nn, module_classname)
+ for module_classname in (
+ "Container",
+ "Sequential",
+ "ModuleList",
+ "ModuleDict",
+ )
+ if hasattr(torch.nn, module_classname)
+ ]
+ if parent is None:
+ parent = module
+
+ if isinstance(sub_module, tuple(module_types)):
+ self.hook_torch_modules(sub_module, prefix=name, parent=parent)
+ else:
+ self._graph_hooks |= {id(sub_module)}
+ try:
+ graph_hook = sub_module.register_forward_hook(
+ self.create_forward_hook(name, graph_idx)
+ )
+ wandb.run._torch._hook_handles[
+ "topology/" + str(id(graph_hook))
+ ] = graph_hook
+ if not hasattr(parent, "_wandb_hook_names"):
+ # should never happen but let's be extra safe
+ parent._wandb_hook_names = []
+ parent._wandb_hook_names.append("topology/" + str(id(graph_hook)))
+ except RuntimeError as e:
+ wandb.termwarn(
+ f"Trying to register forward_hook failed ({e}) - skipping graph tracking.",
+ repeat=False,
+ )
+
+ @classmethod
+ def from_torch_layers(cls, module_graph, variable):
+ """Recover something like neural net layers from PyTorch Module's and the compute graph from a Variable.
+
+ Example output for a multi-layer RNN. We confusingly assign shared embedding values
+ to the encoder, but ordered next to the decoder.
+
+ rnns.0.linear.module.weight_raw rnns.0
+ rnns.0.linear.module.bias rnns.0
+ rnns.1.linear.module.weight_raw rnns.1
+ rnns.1.linear.module.bias rnns.1
+ rnns.2.linear.module.weight_raw rnns.2
+ rnns.2.linear.module.bias rnns.2
+ rnns.3.linear.module.weight_raw rnns.3
+ rnns.3.linear.module.bias rnns.3
+ decoder.weight encoder
+ decoder.bias decoder
+ """
+ # TODO: We're currently not using this, but I left it here in case we want to resurrect! - CVP
+ torch = util.get_module("torch", "Could not import torch")
+
+ module_nodes_by_hash = {id(n): n for n in module_graph.nodes}
+ module_parameter_nodes = [
+ n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)
+ ]
+
+ names_by_pid = {id(n.obj): n.name for n in module_parameter_nodes}
+
+ reachable_param_nodes = module_graph[0].reachable_descendents()
+ reachable_params = {}
+ module_reachable_params = {}
+ names = {}
+ for pid, reachable_nodes in reachable_param_nodes.items():
+ node = module_nodes_by_hash[pid]
+ if not isinstance(node.obj, torch.nn.Module):
+ continue
+ module = node.obj
+ reachable_params = {} # by object id
+ module_reachable_params[id(module)] = reachable_params
+ names[node.name] = set()
+ for reachable_hash in reachable_nodes:
+ reachable = module_nodes_by_hash[reachable_hash]
+ if isinstance(reachable.obj, torch.nn.Parameter):
+ param = reachable.obj
+ reachable_params[id(param)] = param
+ names[node.name].add(names_by_pid[id(param)])
+
+ # we look for correspondences between sets of parameters used in subtrees of the
+ # computation graph and sets of parameters contained in subtrees of the module
+ # graph
+ node_depths = {id(n): d for n, d in module_graph[0].descendent_bfs()}
+ parameter_module_names = {}
+ parameter_modules = {}
+ for param_node in (
+ n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)
+ ):
+ pid = id(param_node.obj)
+ best_node = None
+ best_depth = None
+ best_reachable_params = None
+ for node in module_graph.nodes:
+ if not isinstance(node.obj, torch.nn.Module):
+ continue
+ module = node.obj
+ reachable_params = module_reachable_params[id(module)]
+ if pid in reachable_params:
+ depth = node_depths[id(node)]
+ if best_node is None or (len(reachable_params), depth) <= (
+ len(best_reachable_params),
+ best_depth,
+ ):
+ best_node = node
+ best_depth = depth
+ best_reachable_params = reachable_params
+
+ parameter_modules[pid] = best_node
+ parameter_module_names[param_node.name] = best_node.name
+
+ # contains all parameters but only a minimal set of modules necessary
+ # to contain them (and which ideally correspond to conceptual layers)
+ reduced_module_graph = cls()
+ rmg_ids = itertools.count()
+ rmg_root = Node(id=next(rmg_ids), node=module_graph[0])
+ reduced_module_graph.add_node(rmg_root)
+ reduced_module_graph.root = rmg_root
+ rmg_nodes_by_pid = {}
+
+ module_nodes_by_pid = {id(n.obj): n for n in module_graph.nodes}
+
+ compute_graph, compute_node_vars = cls.from_torch_compute_graph(variable)
+ for node, _ in reversed(list(compute_graph[0].ancestor_bfs())):
+ param = compute_node_vars.get(node.id)
+ pid = id(param)
+ if not isinstance(param, torch.nn.Parameter):
+ continue
+ if pid not in module_nodes_by_pid:
+ # not all Parameters that occur in the compute graph come from the Module graph
+ continue
+
+ # add the nodes in the order we want to display them on the frontend
+ mid = id(parameter_modules[pid].obj)
+ if mid in rmg_nodes_by_pid:
+ rmg_module = rmg_nodes_by_pid[mid]
+ else:
+ rmg_module = rmg_nodes_by_pid[mid] = Node(
+ id=next(rmg_ids), node=module_nodes_by_pid[mid]
+ )
+ reduced_module_graph.add_node(rmg_module)
+ reduced_module_graph.add_edge(rmg_root, rmg_module)
+
+ rmg_param = Node(id=next(rmg_ids), node=module_nodes_by_pid[pid])
+ rmg_nodes_by_pid[pid] = rmg_param
+ reduced_module_graph.add_node(rmg_param)
+
+ reduced_module_graph.add_edge(rmg_module, rmg_param)
+ return reduced_module_graph
+
+ @classmethod
+ def node_from_module(cls, nid, module):
+ numpy = util.get_module("numpy", "Could not import numpy")
+
+ node = wandb.Node()
+ node.id = nid
+ node.child_parameters = 0
+ for parameter in module.parameters():
+ node.child_parameters += numpy.prod(parameter.size())
+ node.class_name = type(module).__name__
+
+ return node
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c25ae320c8c946a25150b870770710f58a8bf713
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__init__.py
@@ -0,0 +1,11 @@
+"""Tools for integrating with [`ultralytics`](https://docs.ultralytics.com/).
+
+Ultralytics is a computer vision framework for training and deploying YOLOv8 models.
+"""
+
+from wandb.integration.ultralytics.callback import (
+ WandBUltralyticsCallback,
+ add_wandb_callback,
+)
+
+__all__ = ("WandBUltralyticsCallback", "add_wandb_callback")
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99b211a89fdc0cf323ad9a063d8dabf874f69b58
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/bbox_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/bbox_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e6acfa60d93f7256a558bc5b058ad8d31ef6583
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/bbox_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/callback.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/callback.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac9cf438b1c121fb1545584b096484888779379d
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/callback.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/classification_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/classification_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49c94599b30939365b8d489de94a8dd0965555fc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/classification_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/mask_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/mask_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ba275d55f3b316e331af5d11635be901d5f4e03
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/mask_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5906e6e656410456c343833d1a666993ea71c520
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f87bd167bfb45cb4f9a996df301985fa46a0dc9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/bbox_utils.py
@@ -0,0 +1,215 @@
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.detect import DetectionPredictor
+from ultralytics.utils import ops
+
+import wandb
+
+
+def scale_bounding_box_to_original_image_shape(
+ box: torch.Tensor,
+ resized_image_shape: Tuple,
+ original_image_shape: Tuple,
+ ratio_pad: bool,
+) -> List[int]:
+ """YOLOv8 resizes images during training and the label values are normalized based on this resized shape.
+
+ This function rescales the bounding box labels to the original
+ image shape.
+
+ Reference: https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/utils/callbacks/comet.py#L105
+ """
+ resized_image_height, resized_image_width = resized_image_shape
+ # Convert normalized xywh format predictions to xyxy in resized scale format
+ box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width)
+ # Scale box predictions from resized image scale back to original image scale
+ box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad)
+ # # Convert bounding box format from xyxy to xywh for Comet logging
+ box = ops.xyxy2xywh(box)
+ return box.tolist()
+
+
+def get_ground_truth_bbox_annotations(
+ img_idx: int, image_path: str, batch: Dict, class_name_map: Dict = None
+) -> List[Dict[str, Any]]:
+ """Get ground truth bounding box annotation data in the form required for `wandb.Image` overlay system."""
+ indices = batch["batch_idx"] == img_idx
+ bboxes = batch["bboxes"][indices]
+ if len(batch["cls"][indices]):
+ cls_labels = batch["cls"][indices].squeeze(1).tolist()
+ else:
+ cls_labels = []
+
+ class_name_map_reverse = {v: k for k, v in class_name_map.items()}
+
+ if len(bboxes) == 0:
+ wandb.termwarn(
+ f"Image: {image_path} has no bounding boxes labels", repeat=False
+ )
+ return None
+
+ if len(batch["cls"][indices]):
+ cls_labels = batch["cls"][indices].squeeze(1).tolist()
+ else:
+ cls_labels = []
+
+ if class_name_map:
+ cls_labels = [str(class_name_map[label]) for label in cls_labels]
+
+ original_image_shape = batch["ori_shape"][img_idx]
+ resized_image_shape = batch["resized_shape"][img_idx]
+ ratio_pad = batch["ratio_pad"][img_idx]
+
+ data = []
+ for box, label in zip(bboxes, cls_labels):
+ box = scale_bounding_box_to_original_image_shape(
+ box, resized_image_shape, original_image_shape, ratio_pad
+ )
+ data.append(
+ {
+ "position": {
+ "middle": [int(box[0]), int(box[1])],
+ "width": int(box[2]),
+ "height": int(box[3]),
+ },
+ "domain": "pixel",
+ "class_id": class_name_map_reverse[label],
+ "box_caption": label,
+ }
+ )
+
+ return data
+
+
+def get_mean_confidence_map(
+ classes: List, confidence: List, class_id_to_label: Dict
+) -> Dict[str, float]:
+ """Get Mean-confidence map from the predictions to be logged into a `wandb.Table`."""
+ confidence_map = {v: [] for _, v in class_id_to_label.items()}
+ for class_idx, confidence_value in zip(classes, confidence):
+ confidence_map[class_id_to_label[class_idx]].append(confidence_value)
+ updated_confidence_map = {}
+ for label, confidence_list in confidence_map.items():
+ if len(confidence_list) > 0:
+ updated_confidence_map[label] = sum(confidence_list) / len(confidence_list)
+ else:
+ updated_confidence_map[label] = 0
+ return updated_confidence_map
+
+
+def get_boxes(result: Results) -> Tuple[Dict, Dict]:
+ """Convert an ultralytics prediction result into metadata for the `wandb.Image` overlay system."""
+ boxes = result.boxes.xywh.long().numpy()
+ classes = result.boxes.cls.long().numpy()
+ confidence = result.boxes.conf.numpy()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ mean_confidence_map = get_mean_confidence_map(
+ classes, confidence, class_id_to_label
+ )
+ box_data = []
+ for idx in range(len(boxes)):
+ box_data.append(
+ {
+ "position": {
+ "middle": [int(boxes[idx][0]), int(boxes[idx][1])],
+ "width": int(boxes[idx][2]),
+ "height": int(boxes[idx][3]),
+ },
+ "domain": "pixel",
+ "class_id": int(classes[idx]),
+ "box_caption": class_id_to_label[int(classes[idx])],
+ "scores": {"confidence": float(confidence[idx])},
+ }
+ )
+ boxes = {
+ "predictions": {
+ "box_data": box_data,
+ "class_labels": class_id_to_label,
+ },
+ }
+ return boxes, mean_confidence_map
+
+
+def plot_bbox_predictions(
+ result: Results, model_name: str, table: Optional[wandb.Table] = None
+) -> Union[wandb.Table, Tuple[wandb.Image, Dict, Dict]]:
+ """Plot the images with the W&B overlay system.
+
+ The `wandb.Image` is either added to a `wandb.Table` or returned.
+ """
+ result = result.to("cpu")
+ boxes, mean_confidence_map = get_boxes(result)
+ image = wandb.Image(result.orig_img[:, :, ::-1], boxes=boxes)
+ if table is not None:
+ table.add_data(
+ model_name,
+ image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ )
+ return table
+ return image, boxes["predictions"], mean_confidence_map
+
+
+def plot_detection_validation_results(
+ dataloader: Any,
+ class_label_map: Dict,
+ model_name: str,
+ predictor: DetectionPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ """Plot validation results in a table."""
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ _, prediction_box_data, mean_confidence_map = plot_bbox_predictions(
+ prediction_result, model_name
+ )
+ try:
+ ground_truth_data = get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ )
+ wandb_image = wandb.Image(
+ batch["im_file"][img_idx],
+ boxes={
+ "ground-truth": {
+ "box_data": ground_truth_data,
+ "class_labels": class_label_map,
+ },
+ "predictions": {
+ "box_data": prediction_box_data["box_data"],
+ "class_labels": class_label_map,
+ },
+ },
+ )
+ table_rows = [
+ data_idx,
+ batch_idx,
+ wandb_image,
+ mean_confidence_map,
+ prediction_result.speed,
+ ]
+ table_rows = [epoch] + table_rows if epoch is not None else table_rows
+ table_rows = [model_name] + table_rows
+ table.add_data(*table_rows)
+ data_idx += 1
+ except TypeError:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/callback.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47605a9579dafece3ef364bd3916f4cfd3c96f9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/callback.py
@@ -0,0 +1,528 @@
+import copy
+from datetime import datetime
+from typing import Callable, Dict, Optional, Union
+
+from packaging import version
+
+try:
+ import dill as pickle
+except ImportError:
+ import pickle
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+try:
+ import torch
+ import ultralytics
+ from tqdm.auto import tqdm
+
+ if version.parse(ultralytics.__version__) > version.parse("8.0.238"):
+ wandb.termwarn(
+ """This integration is tested and supported for ultralytics v8.0.238 and below.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.""",
+ repeat=False,
+ )
+
+ from ultralytics.models import YOLO
+ from ultralytics.models.sam.predict import Predictor as SAMPredictor
+ from ultralytics.models.yolo.classify import (
+ ClassificationPredictor,
+ ClassificationTrainer,
+ ClassificationValidator,
+ )
+ from ultralytics.models.yolo.detect import (
+ DetectionPredictor,
+ DetectionTrainer,
+ DetectionValidator,
+ )
+ from ultralytics.models.yolo.pose import PosePredictor, PoseTrainer, PoseValidator
+ from ultralytics.models.yolo.segment import (
+ SegmentationPredictor,
+ SegmentationTrainer,
+ SegmentationValidator,
+ )
+ from ultralytics.utils.torch_utils import de_parallel
+
+ try:
+ from ultralytics.yolo.utils import RANK, __version__
+ except ModuleNotFoundError:
+ from ultralytics.utils import RANK, __version__
+
+ from wandb.integration.ultralytics.bbox_utils import (
+ plot_bbox_predictions,
+ plot_detection_validation_results,
+ )
+ from wandb.integration.ultralytics.classification_utils import (
+ plot_classification_predictions,
+ plot_classification_validation_results,
+ )
+ from wandb.integration.ultralytics.mask_utils import (
+ plot_mask_predictions,
+ plot_sam_predictions,
+ plot_segmentation_validation_results,
+ )
+ from wandb.integration.ultralytics.pose_utils import (
+ plot_pose_predictions,
+ plot_pose_validation_results,
+ )
+except Exception as e:
+ wandb.Error(e)
+
+
+TRAINER_TYPE = Union[
+ ClassificationTrainer, DetectionTrainer, SegmentationTrainer, PoseTrainer
+]
+VALIDATOR_TYPE = Union[
+ ClassificationValidator, DetectionValidator, SegmentationValidator, PoseValidator
+]
+PREDICTOR_TYPE = Union[
+ ClassificationPredictor,
+ DetectionPredictor,
+ SegmentationPredictor,
+ PosePredictor,
+ SAMPredictor,
+]
+
+
+class WandBUltralyticsCallback:
+ """Stateful callback for logging to W&B.
+
+ In particular, it will log model checkpoints, predictions, and
+ ground-truth annotations with interactive overlays for bounding boxes
+ to Weights & Biases Tables during training, validation and prediction
+ for a `ultratytics` workflow.
+
+ Example:
+ ```python
+ from ultralytics.yolo.engine.model import YOLO
+ from wandb.yolov8 import add_wandb_callback
+
+ # initialize YOLO model
+ model = YOLO("yolov8n.pt")
+
+ # add wandb callback
+ add_wandb_callback(
+ model, max_validation_batches=2, enable_model_checkpointing=True
+ )
+
+ # train
+ model.train(data="coco128.yaml", epochs=5, imgsz=640)
+
+ # validate
+ model.val()
+
+ # perform inference
+ model(["img1.jpeg", "img2.jpeg"])
+ ```
+
+ Args:
+ model: (ultralytics.yolo.engine.model.YOLO) YOLO Model of type
+ `ultralytics.yolo.engine.model.YOLO`.
+ epoch_logging_interval: (int) interval to log the prediction visualizations
+ during training.
+ max_validation_batches: (int) maximum number of validation batches to log to
+ a table per epoch.
+ enable_model_checkpointing: (bool) enable logging model checkpoints as
+ artifacts at the end of eveny epoch if set to `True`.
+ visualize_skeleton: (bool) visualize pose skeleton by drawing lines connecting
+ keypoints for human pose.
+ """
+
+ def __init__(
+ self,
+ model: YOLO,
+ epoch_logging_interval: int = 1,
+ max_validation_batches: int = 1,
+ enable_model_checkpointing: bool = False,
+ visualize_skeleton: bool = False,
+ ) -> None:
+ self.epoch_logging_interval = epoch_logging_interval
+ self.max_validation_batches = max_validation_batches
+ self.enable_model_checkpointing = enable_model_checkpointing
+ self.visualize_skeleton = visualize_skeleton
+ self.task = model.task
+ self.task_map = model.task_map
+ self.model_name = (
+ model.overrides["model"].split(".")[0]
+ if "model" in model.overrides
+ else None
+ )
+ self._make_tables()
+ self._make_predictor(model)
+ self.supported_tasks = ["detect", "segment", "pose", "classify"]
+ self.prompts = None
+ self.run_id = None
+ self.train_epoch = None
+
+ def _make_tables(self):
+ if self.task in ["detect", "segment"]:
+ validation_columns = [
+ "Data-Index",
+ "Batch-Index",
+ "Image",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ train_columns = ["Epoch"] + validation_columns
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name"] + train_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=[
+ "Model-Name",
+ "Image",
+ "Num-Objects",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ )
+ elif self.task == "classify":
+ classification_columns = [
+ "Image",
+ "Predicted-Category",
+ "Prediction-Confidence",
+ "Top-5-Prediction-Categories",
+ "Top-5-Prediction-Confindence",
+ "Probabilities",
+ "Speed",
+ ]
+ validation_columns = ["Data-Index", "Batch-Index"] + classification_columns
+ validation_columns.insert(3, "Ground-Truth-Category")
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name", "Epoch"] + validation_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=["Model-Name"] + classification_columns
+ )
+ elif self.task == "pose":
+ validation_columns = [
+ "Data-Index",
+ "Batch-Index",
+ "Image-Ground-Truth",
+ "Image-Prediction",
+ "Num-Instances",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ train_columns = ["Epoch"] + validation_columns
+ self.train_validation_table = wandb.Table(
+ columns=["Model-Name"] + train_columns
+ )
+ self.validation_table = wandb.Table(
+ columns=["Model-Name"] + validation_columns
+ )
+ self.prediction_table = wandb.Table(
+ columns=[
+ "Model-Name",
+ "Image-Prediction",
+ "Num-Instances",
+ "Mean-Confidence",
+ "Speed",
+ ]
+ )
+
+ def _make_predictor(self, model: YOLO):
+ overrides = copy.deepcopy(model.overrides)
+ overrides["conf"] = 0.1
+ self.predictor = self.task_map[self.task]["predictor"](overrides=overrides)
+ self.predictor.callbacks = {}
+ self.predictor.args.save = False
+ self.predictor.args.save_txt = False
+ self.predictor.args.save_crop = False
+ self.predictor.args.verbose = None
+
+ def _save_model(self, trainer: TRAINER_TYPE):
+ model_checkpoint_artifact = wandb.Artifact(f"run_{wandb.run.id}_model", "model")
+ checkpoint_dict = {
+ "epoch": trainer.epoch,
+ "best_fitness": trainer.best_fitness,
+ "model": copy.deepcopy(de_parallel(self.model)).half(),
+ "ema": copy.deepcopy(trainer.ema.ema).half(),
+ "updates": trainer.ema.updates,
+ "optimizer": trainer.optimizer.state_dict(),
+ "train_args": vars(trainer.args),
+ "date": datetime.now().isoformat(),
+ "version": __version__,
+ }
+ checkpoint_path = trainer.wdir / f"epoch{trainer.epoch}.pt"
+ torch.save(checkpoint_dict, checkpoint_path, pickle_module=pickle)
+ model_checkpoint_artifact.add_file(checkpoint_path)
+ wandb.log_artifact(
+ model_checkpoint_artifact, aliases=[f"epoch_{trainer.epoch}"]
+ )
+
+ def on_train_start(self, trainer: TRAINER_TYPE):
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.ultralytics_yolov8 = True
+ wandb.config.train = vars(trainer.args)
+ self.run_id = wandb.run.id
+
+ @torch.no_grad()
+ def on_fit_epoch_end(self, trainer: DetectionTrainer):
+ if self.task in self.supported_tasks and self.train_epoch != trainer.epoch:
+ self.train_epoch = trainer.epoch
+ if (self.train_epoch + 1) % self.epoch_logging_interval == 0:
+ validator = trainer.validator
+ dataloader = validator.dataloader
+ class_label_map = validator.names
+ self.device = next(trainer.model.parameters()).device
+ if isinstance(trainer.model, torch.nn.parallel.DistributedDataParallel):
+ model = trainer.model.module
+ else:
+ model = trainer.model
+ self.model = copy.deepcopy(model).eval().to(self.device)
+ self.predictor.setup_model(model=self.model, verbose=False)
+ if self.task == "pose":
+ self.train_validation_table = plot_pose_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ visualize_skeleton=self.visualize_skeleton,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "segment":
+ self.train_validation_table = plot_segmentation_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "detect":
+ self.train_validation_table = plot_detection_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ elif self.task == "classify":
+ self.train_validation_table = (
+ plot_classification_validation_results(
+ dataloader=dataloader,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.train_validation_table,
+ max_validation_batches=self.max_validation_batches,
+ epoch=trainer.epoch,
+ )
+ )
+ if self.enable_model_checkpointing:
+ self._save_model(trainer)
+ trainer.model.to(self.device)
+
+ def on_train_end(self, trainer: TRAINER_TYPE):
+ if self.task in self.supported_tasks:
+ wandb.log({"Train-Table": self.train_validation_table}, commit=False)
+
+ def on_val_start(self, validator: VALIDATOR_TYPE):
+ wandb.run or wandb.init(
+ project=validator.args.project or "YOLOv8",
+ job_type="validation_" + validator.args.task,
+ )
+
+ @torch.no_grad()
+ def on_val_end(self, trainer: VALIDATOR_TYPE):
+ if self.task in self.supported_tasks:
+ validator = trainer
+ dataloader = validator.dataloader
+ class_label_map = validator.names
+ if self.task == "pose":
+ self.validation_table = plot_pose_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ visualize_skeleton=self.visualize_skeleton,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "segment":
+ self.validation_table = plot_segmentation_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "detect":
+ self.validation_table = plot_detection_validation_results(
+ dataloader=dataloader,
+ class_label_map=class_label_map,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ elif self.task == "classify":
+ self.validation_table = plot_classification_validation_results(
+ dataloader=dataloader,
+ model_name=self.model_name,
+ predictor=self.predictor,
+ table=self.validation_table,
+ max_validation_batches=self.max_validation_batches,
+ )
+ wandb.log({"Validation-Table": self.validation_table}, commit=False)
+
+ def on_predict_start(self, predictor: PREDICTOR_TYPE):
+ wandb.run or wandb.init(
+ project=predictor.args.project or "YOLOv8",
+ config=vars(predictor.args),
+ job_type="prediction_" + predictor.args.task,
+ )
+ if isinstance(predictor, SAMPredictor):
+ self.prompts = copy.deepcopy(predictor.prompts)
+ self.prediction_table = wandb.Table(columns=["Image"])
+
+ def on_predict_end(self, predictor: PREDICTOR_TYPE):
+ wandb.config.prediction_configs = vars(predictor.args)
+ if self.task in self.supported_tasks:
+ for result in tqdm(predictor.results):
+ if self.task == "pose":
+ self.prediction_table = plot_pose_predictions(
+ result,
+ self.model_name,
+ self.visualize_skeleton,
+ self.prediction_table,
+ )
+ elif self.task == "segment":
+ if isinstance(predictor, SegmentationPredictor):
+ self.prediction_table = plot_mask_predictions(
+ result, self.model_name, self.prediction_table
+ )
+ elif isinstance(predictor, SAMPredictor):
+ self.prediction_table = plot_sam_predictions(
+ result, self.prompts, self.prediction_table
+ )
+ elif self.task == "detect":
+ self.prediction_table = plot_bbox_predictions(
+ result, self.model_name, self.prediction_table
+ )
+ elif self.task == "classify":
+ self.prediction_table = plot_classification_predictions(
+ result, self.model_name, self.prediction_table
+ )
+
+ wandb.log({"Prediction-Table": self.prediction_table}, commit=False)
+
+ @property
+ def callbacks(self) -> Dict[str, Callable]:
+ """Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging."""
+ return {
+ "on_train_start": self.on_train_start,
+ "on_fit_epoch_end": self.on_fit_epoch_end,
+ "on_train_end": self.on_train_end,
+ "on_val_start": self.on_val_start,
+ "on_val_end": self.on_val_end,
+ "on_predict_start": self.on_predict_start,
+ "on_predict_end": self.on_predict_end,
+ }
+
+
+# TODO: Add epoch interval
+def add_wandb_callback(
+ model: YOLO,
+ epoch_logging_interval: int = 1,
+ enable_model_checkpointing: bool = False,
+ enable_train_validation_logging: bool = True,
+ enable_validation_logging: bool = True,
+ enable_prediction_logging: bool = True,
+ max_validation_batches: Optional[int] = 1,
+ visualize_skeleton: Optional[bool] = True,
+):
+ """Function to add the `WandBUltralyticsCallback` callback to the `YOLO` model.
+
+ Example:
+ ```python
+ from ultralytics.yolo.engine.model import YOLO
+ from wandb.yolov8 import add_wandb_callback
+
+ # initialize YOLO model
+ model = YOLO("yolov8n.pt")
+
+ # add wandb callback
+ add_wandb_callback(
+ model, max_validation_batches=2, enable_model_checkpointing=True
+ )
+
+ # train
+ model.train(data="coco128.yaml", epochs=5, imgsz=640)
+
+ # validate
+ model.val()
+
+ # perform inference
+ model(["img1.jpeg", "img2.jpeg"])
+ ```
+
+ Args:
+ model: (ultralytics.yolo.engine.model.YOLO) YOLO Model of type
+ `ultralytics.yolo.engine.model.YOLO`.
+ epoch_logging_interval: (int) interval to log the prediction visualizations
+ during training.
+ enable_model_checkpointing: (bool) enable logging model checkpoints as
+ artifacts at the end of eveny epoch if set to `True`.
+ enable_train_validation_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from
+ the validation dataloader to a `wandb.Table` along with
+ mean-confidence of the predictions per-class at the end of each
+ training epoch.
+ enable_validation_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from the
+ validation dataloader to a `wandb.Table` along with
+ mean-confidence of the predictions per-class at the end of
+ validation.
+ enable_prediction_logging: (bool) enable logging the predictions and
+ ground-truths as interactive image overlays on the images from the
+ validation dataloader to a `wandb.Table` along with mean-confidence
+ of the predictions per-class at the end of each prediction.
+ max_validation_batches: (Optional[int]) maximum number of validation batches to log to
+ a table per epoch.
+ visualize_skeleton: (Optional[bool]) visualize pose skeleton by drawing lines connecting
+ keypoints for human pose.
+
+ Returns:
+ An instance of `ultralytics.yolo.engine.model.YOLO` with the `WandBUltralyticsCallback`.
+ """
+ if RANK in [-1, 0]:
+ wandb_callback = WandBUltralyticsCallback(
+ copy.deepcopy(model),
+ epoch_logging_interval,
+ max_validation_batches,
+ enable_model_checkpointing,
+ visualize_skeleton,
+ )
+ callbacks = wandb_callback.callbacks
+ if not enable_train_validation_logging:
+ _ = callbacks.pop("on_fit_epoch_end")
+ _ = callbacks.pop("on_train_end")
+ if not enable_validation_logging:
+ _ = callbacks.pop("on_val_start")
+ _ = callbacks.pop("on_val_end")
+ if not enable_prediction_logging:
+ _ = callbacks.pop("on_predict_start")
+ _ = callbacks.pop("on_predict_end")
+ for event, callback_fn in callbacks.items():
+ model.add_callback(event, callback_fn)
+ else:
+ wandb.termerror(
+ "The RANK of the process to add the callbacks was neither 0 or "
+ "-1. No Weights & Biases callbacks were added to this instance "
+ "of the YOLO model."
+ )
+ return model
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9db6db72768dd2d16b7b44ee1ad0514a6322752f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/classification_utils.py
@@ -0,0 +1,83 @@
+from typing import Any, Optional
+
+import numpy as np
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.classify import ClassificationPredictor
+
+import wandb
+
+
+def plot_classification_predictions(
+ result: Results,
+ model_name: str,
+ table: Optional[wandb.Table] = None,
+ original_image: Optional[np.array] = None,
+):
+ """Plot classification prediction results to a `wandb.Table` if the table is passed otherwise return the data."""
+ result = result.to("cpu")
+ probabilities = result.probs
+ probabilities_list = probabilities.data.numpy().tolist()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ original_image = (
+ wandb.Image(original_image)
+ if original_image is not None
+ else wandb.Image(result.orig_img)
+ )
+ table_row = [
+ model_name,
+ original_image,
+ class_id_to_label[int(probabilities.top1)],
+ probabilities.top1conf,
+ [class_id_to_label[int(class_idx)] for class_idx in list(probabilities.top5)],
+ [probabilities_list[int(class_idx)] for class_idx in list(probabilities.top5)],
+ {
+ class_id_to_label[int(class_idx)]: probability
+ for class_idx, probability in enumerate(probabilities_list)
+ },
+ result.speed,
+ ]
+ if table is not None:
+ table.add_data(*table_row)
+ return table
+ return class_id_to_label, table_row
+
+
+def plot_classification_validation_results(
+ dataloader: Any,
+ model_name: str,
+ predictor: ClassificationPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ """Plot classification results to a `wandb.Table`."""
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ image_batch = [
+ image for image in np.transpose(batch["img"].numpy(), (0, 2, 3, 1))
+ ]
+ ground_truth = batch["cls"].numpy().tolist()
+ progress_bar_result_iterable = tqdm(
+ range(max_validation_batches),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx in progress_bar_result_iterable:
+ try:
+ prediction_result = predictor(image_batch[img_idx])[0]
+ class_id_to_label, table_row = plot_classification_predictions(
+ prediction_result, model_name, original_image=image_batch[img_idx]
+ )
+ table_row = [data_idx, batch_idx] + table_row[1:]
+ table_row.insert(3, class_id_to_label[ground_truth[img_idx]])
+ table_row = [epoch] + table_row if epoch is not None else table_row
+ table_row = [model_name] + table_row
+ table.add_data(*table_row)
+ data_idx += 1
+ except Exception:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5392d964b30ae1330349ce0978ef58eb3e5ee5dd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/mask_utils.py
@@ -0,0 +1,202 @@
+from typing import Dict, Optional, Tuple
+
+import cv2
+import numpy as np
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.segment import SegmentationPredictor
+from ultralytics.utils.ops import scale_image
+
+import wandb
+from wandb.integration.ultralytics.bbox_utils import (
+ get_ground_truth_bbox_annotations,
+ get_mean_confidence_map,
+)
+
+
+def instance_mask_to_semantic_mask(instance_mask, class_indices):
+ height, width, num_instances = instance_mask.shape
+ semantic_mask = np.zeros((height, width), dtype=np.uint8)
+ for i in range(num_instances):
+ instance_map = instance_mask[:, :, i]
+ class_index = class_indices[i]
+ semantic_mask[instance_map == 1] = class_index
+ return semantic_mask
+
+
+def get_boxes_and_masks(result: Results) -> Tuple[Dict, Dict, Dict]:
+ boxes = result.boxes.xywh.long().numpy()
+ classes = result.boxes.cls.long().numpy()
+ confidence = result.boxes.conf.numpy()
+ class_id_to_label = {int(k): str(v) for k, v in result.names.items()}
+ class_id_to_label.update({len(result.names.items()): "background"})
+ mean_confidence_map = get_mean_confidence_map(
+ classes, confidence, class_id_to_label
+ )
+ masks = None
+ if result.masks is not None:
+ scaled_instance_mask = scale_image(
+ np.transpose(result.masks.data.numpy(), (1, 2, 0)),
+ result.orig_img[:, :, ::-1].shape,
+ )
+ scaled_semantic_mask = instance_mask_to_semantic_mask(
+ scaled_instance_mask, classes.tolist()
+ )
+ scaled_semantic_mask[scaled_semantic_mask == 0] = len(result.names.items())
+ masks = {
+ "predictions": {
+ "mask_data": scaled_semantic_mask,
+ "class_labels": class_id_to_label,
+ }
+ }
+ box_data, total_confidence = [], 0.0
+ for idx in range(len(boxes)):
+ box_data.append(
+ {
+ "position": {
+ "middle": [int(boxes[idx][0]), int(boxes[idx][1])],
+ "width": int(boxes[idx][2]),
+ "height": int(boxes[idx][3]),
+ },
+ "domain": "pixel",
+ "class_id": int(classes[idx]),
+ "box_caption": class_id_to_label[int(classes[idx])],
+ "scores": {"confidence": float(confidence[idx])},
+ }
+ )
+ total_confidence += float(confidence[idx])
+
+ boxes = {
+ "predictions": {
+ "box_data": box_data,
+ "class_labels": class_id_to_label,
+ },
+ }
+ return boxes, masks, mean_confidence_map
+
+
+def plot_mask_predictions(
+ result: Results, model_name: str, table: Optional[wandb.Table] = None
+) -> Tuple[wandb.Image, Dict, Dict, Dict]:
+ result = result.to("cpu")
+ boxes, masks, mean_confidence_map = get_boxes_and_masks(result)
+ image = wandb.Image(result.orig_img[:, :, ::-1], boxes=boxes, masks=masks)
+ if table is not None:
+ table.add_data(
+ model_name,
+ image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ )
+ return table
+ return image, masks, boxes["predictions"], mean_confidence_map
+
+
+def structure_prompts_and_image(image: np.array, prompt: Dict) -> Dict:
+ wb_box_data = []
+ if prompt["bboxes"] is not None:
+ wb_box_data.append(
+ {
+ "position": {
+ "middle": [prompt["bboxes"][0], prompt["bboxes"][1]],
+ "width": prompt["bboxes"][2],
+ "height": prompt["bboxes"][3],
+ },
+ "domain": "pixel",
+ "class_id": 1,
+ "box_caption": "Prompt-Box",
+ }
+ )
+ if prompt["points"] is not None:
+ image = image.copy().astype(np.uint8)
+ image = cv2.circle(
+ image, tuple(prompt["points"]), 5, (0, 255, 0), -1, lineType=cv2.LINE_AA
+ )
+ wb_box_data = {
+ "prompts": {
+ "box_data": wb_box_data,
+ "class_labels": {1: "Prompt-Box"},
+ }
+ }
+ return image, wb_box_data
+
+
+def plot_sam_predictions(
+ result: Results, prompt: Dict, table: wandb.Table
+) -> wandb.Table:
+ result = result.to("cpu")
+ image = result.orig_img[:, :, ::-1]
+ image, wb_box_data = structure_prompts_and_image(image, prompt)
+ image = wandb.Image(
+ image,
+ boxes=wb_box_data,
+ masks={
+ "predictions": {
+ "mask_data": np.squeeze(result.masks.data.cpu().numpy().astype(int)),
+ "class_labels": {0: "Background", 1: "Prediction"},
+ }
+ },
+ )
+ table.add_data(image)
+ return table
+
+
+def plot_segmentation_validation_results(
+ dataloader,
+ class_label_map,
+ model_name: str,
+ predictor: SegmentationPredictor,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+):
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ (
+ _,
+ prediction_mask_data,
+ prediction_box_data,
+ mean_confidence_map,
+ ) = plot_mask_predictions(prediction_result, model_name)
+ try:
+ ground_truth_data = get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ )
+ wandb_image = wandb.Image(
+ batch["im_file"][img_idx],
+ boxes={
+ "ground-truth": {
+ "box_data": ground_truth_data,
+ "class_labels": class_label_map,
+ },
+ "predictions": prediction_box_data,
+ },
+ masks=prediction_mask_data,
+ )
+ table_rows = [
+ data_idx,
+ batch_idx,
+ wandb_image,
+ mean_confidence_map,
+ prediction_result.speed,
+ ]
+ table_rows = [epoch] + table_rows if epoch is not None else table_rows
+ table_rows = [model_name] + table_rows
+ table.add_data(*table_rows)
+ data_idx += 1
+ except TypeError:
+ pass
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cef5a90353d063e281ae54836d76675029aaa4e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/ultralytics/pose_utils.py
@@ -0,0 +1,103 @@
+from typing import Any, Optional
+
+import numpy as np
+from PIL import Image
+from tqdm.auto import tqdm
+from ultralytics.engine.results import Results
+from ultralytics.models.yolo.pose import PosePredictor
+from ultralytics.utils.plotting import Annotator
+
+import wandb
+from wandb.integration.ultralytics.bbox_utils import (
+ get_boxes,
+ get_ground_truth_bbox_annotations,
+)
+
+
+def annotate_keypoint_results(result: Results, visualize_skeleton: bool):
+ annotator = Annotator(np.ascontiguousarray(result.orig_img[:, :, ::-1]))
+ key_points = result.keypoints.data.numpy()
+ for idx in range(key_points.shape[0]):
+ annotator.kpts(key_points[idx], kpt_line=visualize_skeleton)
+ return annotator.im
+
+
+def annotate_keypoint_batch(image_path: str, keypoints: Any, visualize_skeleton: bool):
+ with Image.open(image_path) as original_image:
+ original_image = np.ascontiguousarray(original_image)
+ annotator = Annotator(original_image)
+ annotator.kpts(keypoints.numpy(), kpt_line=visualize_skeleton)
+ return annotator.im
+
+
+def plot_pose_predictions(
+ result: Results,
+ model_name: str,
+ visualize_skeleton: bool,
+ table: Optional[wandb.Table] = None,
+):
+ result = result.to("cpu")
+ boxes, mean_confidence_map = get_boxes(result)
+ annotated_image = annotate_keypoint_results(result, visualize_skeleton)
+ prediction_image = wandb.Image(annotated_image, boxes=boxes)
+ table_row = [
+ model_name,
+ prediction_image,
+ len(boxes["predictions"]["box_data"]),
+ mean_confidence_map,
+ result.speed,
+ ]
+ if table is not None:
+ table.add_data(*table_row)
+ return table
+ return table_row
+
+
+def plot_pose_validation_results(
+ dataloader,
+ class_label_map,
+ model_name: str,
+ predictor: PosePredictor,
+ visualize_skeleton: bool,
+ table: wandb.Table,
+ max_validation_batches: int,
+ epoch: Optional[int] = None,
+) -> wandb.Table:
+ data_idx = 0
+ num_dataloader_batches = len(dataloader.dataset) // dataloader.batch_size
+ max_validation_batches = min(max_validation_batches, num_dataloader_batches)
+ for batch_idx, batch in enumerate(dataloader):
+ prediction_results = predictor(batch["im_file"])
+ progress_bar_result_iterable = tqdm(
+ enumerate(prediction_results),
+ total=len(prediction_results),
+ desc=f"Generating Visualizations for batch-{batch_idx + 1}/{max_validation_batches}",
+ )
+ for img_idx, prediction_result in progress_bar_result_iterable:
+ prediction_result = prediction_result.to("cpu")
+ table_row = plot_pose_predictions(
+ prediction_result, model_name, visualize_skeleton
+ )
+ ground_truth_image = wandb.Image(
+ annotate_keypoint_batch(
+ batch["im_file"][img_idx],
+ batch["keypoints"][img_idx],
+ visualize_skeleton,
+ ),
+ boxes={
+ "ground-truth": {
+ "box_data": get_ground_truth_bbox_annotations(
+ img_idx, batch["im_file"][img_idx], batch, class_label_map
+ ),
+ "class_labels": class_label_map,
+ },
+ },
+ )
+ table_row = [data_idx, batch_idx, ground_truth_image] + table_row[1:]
+ table_row = [epoch] + table_row if epoch is not None else table_row
+ table_row = [model_name] + table_row
+ table.add_data(*table_row)
+ data_idx += 1
+ if batch_idx + 1 == max_validation_batches:
+ break
+ return table
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..052083e0cf7034a469a82582422ff7fee62965a5
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__init__.py
@@ -0,0 +1,11 @@
+"""W&B callback for xgboost.
+
+Simple callback to get logging for each tree
+
+Use the `wandb_callback` to add `wandb` logging to any `XGboost` model. However, it will
+be deprecated in favor of WandbCallback. Use it instead for more features.
+"""
+
+from .xgboost import WandbCallback, wandb_callback
+
+__all__ = ["wandb_callback", "WandbCallback"]
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87df0b79837c0720eb6a26e2a31946ba1e5d9ae1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3986018b5a01568a52afd04a69484f7cc1ebcfb2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/xgboost/xgboost.py b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/xgboost.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a8b63dfa2f39db9d40989dc8562cc732ba11d98
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/xgboost/xgboost.py
@@ -0,0 +1,189 @@
+"""xgboost init!"""
+
+import json
+import warnings
+from pathlib import Path
+from typing import TYPE_CHECKING, cast
+
+import xgboost as xgb # type: ignore
+from xgboost import Booster
+
+import wandb
+from wandb.sdk.lib import telemetry as wb_telemetry
+
+MINIMIZE_METRICS = [
+ "rmse",
+ "rmsle",
+ "mae",
+ "mape",
+ "mphe",
+ "logloss",
+ "error",
+ "error@t",
+ "merror",
+]
+
+MAXIMIZE_METRICS = ["auc", "aucpr", "ndcg", "map", "ndcg@n", "map@n"]
+
+
+if TYPE_CHECKING:
+ from typing import Callable, List, NamedTuple
+
+ class CallbackEnv(NamedTuple):
+ evaluation_result_list: List
+
+
+def wandb_callback() -> "Callable":
+ """Old style callback that will be deprecated in favor of WandbCallback. Please try the new logger for more features."""
+ warnings.warn(
+ "wandb_callback will be deprecated in favor of WandbCallback. Please use WandbCallback for more features.",
+ UserWarning,
+ stacklevel=2,
+ )
+
+ with wb_telemetry.context() as tel:
+ tel.feature.xgboost_old_wandb_callback = True
+
+ def callback(env: "CallbackEnv") -> None:
+ for k, v in env.evaluation_result_list:
+ wandb.log({k: v}, commit=False)
+ wandb.log({})
+
+ return callback
+
+
+class WandbCallback(xgb.callback.TrainingCallback):
+ """`WandbCallback` automatically integrates XGBoost with wandb.
+
+ Args:
+ log_model: (boolean) if True save and upload the model to Weights & Biases Artifacts
+ log_feature_importance: (boolean) if True log a feature importance bar plot
+ importance_type: (str) one of {weight, gain, cover, total_gain, total_cover} for tree model. weight for linear model.
+ define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`.
+
+ Passing `WandbCallback` to XGBoost will:
+
+ - log the booster model configuration to Weights & Biases
+ - log evaluation metrics collected by XGBoost, such as rmse, accuracy etc. to Weights & Biases
+ - log training metric collected by XGBoost (if you provide training data to eval_set)
+ - log the best score and the best iteration
+ - save and upload your trained model to Weights & Biases Artifacts (when `log_model = True`)
+ - log feature importance plot when `log_feature_importance=True` (default).
+ - Capture the best eval metric in `wandb.summary` when `define_metric=True` (default).
+
+ Example:
+ ```python
+ bst_params = dict(
+ objective="reg:squarederror",
+ colsample_bytree=0.3,
+ learning_rate=0.1,
+ max_depth=5,
+ alpha=10,
+ n_estimators=10,
+ tree_method="hist",
+ callbacks=[WandbCallback()],
+ )
+
+ xg_reg = xgb.XGBRegressor(**bst_params)
+ xg_reg.fit(
+ X_train,
+ y_train,
+ eval_set=[(X_test, y_test)],
+ )
+ ```
+ """
+
+ def __init__(
+ self,
+ log_model: bool = False,
+ log_feature_importance: bool = True,
+ importance_type: str = "gain",
+ define_metric: bool = True,
+ ):
+ self.log_model: bool = log_model
+ self.log_feature_importance: bool = log_feature_importance
+ self.importance_type: str = importance_type
+ self.define_metric: bool = define_metric
+
+ if wandb.run is None:
+ raise wandb.Error("You must call wandb.init() before WandbCallback()")
+
+ with wb_telemetry.context() as tel:
+ tel.feature.xgboost_wandb_callback = True
+
+ def before_training(self, model: Booster) -> Booster:
+ """Run before training is finished."""
+ # Update W&B config
+ config = model.save_config()
+ wandb.config.update(json.loads(config))
+
+ return model
+
+ def after_training(self, model: Booster) -> Booster:
+ """Run after training is finished."""
+ # Log the booster model as artifacts
+ if self.log_model:
+ self._log_model_as_artifact(model)
+
+ # Plot feature importance
+ if self.log_feature_importance:
+ self._log_feature_importance(model)
+
+ # Log the best score and best iteration
+ if model.attr("best_score") is not None:
+ wandb.log(
+ {
+ "best_score": float(cast(str, model.attr("best_score"))),
+ "best_iteration": int(cast(str, model.attr("best_iteration"))),
+ }
+ )
+
+ return model
+
+ def after_iteration(self, model: Booster, epoch: int, evals_log: dict) -> bool:
+ """Run after each iteration. Return True when training should stop."""
+ # Log metrics
+ for data, metric in evals_log.items():
+ for metric_name, log in metric.items():
+ if self.define_metric:
+ self._define_metric(data, metric_name)
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+ else:
+ wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False)
+
+ wandb.log({"epoch": epoch})
+
+ self.define_metric = False
+
+ return False
+
+ def _log_model_as_artifact(self, model: Booster) -> None:
+ model_name = f"{wandb.run.id}_model.json" # type: ignore
+ model_path = Path(wandb.run.dir) / model_name # type: ignore
+ model.save_model(str(model_path))
+
+ model_artifact = wandb.Artifact(name=model_name, type="model")
+ model_artifact.add_file(str(model_path))
+ wandb.log_artifact(model_artifact)
+
+ def _log_feature_importance(self, model: Booster) -> None:
+ fi = model.get_score(importance_type=self.importance_type)
+ fi_data = [[k, fi[k]] for k in fi]
+ table = wandb.Table(data=fi_data, columns=["Feature", "Importance"])
+ wandb.log(
+ {
+ "Feature Importance": wandb.plot.bar(
+ table, "Feature", "Importance", title="Feature Importance"
+ )
+ }
+ )
+
+ def _define_metric(self, data: str, metric_name: str) -> None:
+ if "loss" in str.lower(metric_name):
+ wandb.define_metric(f"{data}-{metric_name}", summary="min")
+ elif str.lower(metric_name) in MINIMIZE_METRICS:
+ wandb.define_metric(f"{data}-{metric_name}", summary="min")
+ elif str.lower(metric_name) in MAXIMIZE_METRICS:
+ wandb.define_metric(f"{data}-{metric_name}", summary="max")
+ else:
+ pass
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__init__.py b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d31ce7da47121061036bf32f5ca5eb1890412428
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/yolov8.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/yolov8.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20433dfdb9be388a0cff91f0efd91a79fa57e4e6
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/__pycache__/yolov8.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/integration/yolov8/yolov8.py b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/yolov8.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c5dbd0fe8de39f387b6427b4696f28f9c029b44
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/integration/yolov8/yolov8.py
@@ -0,0 +1,284 @@
+from typing import Any, Callable, Dict, List, Optional
+
+from ultralytics.yolo.engine.model import YOLO
+from ultralytics.yolo.engine.trainer import BaseTrainer
+
+try:
+ from ultralytics.yolo.utils import RANK
+ from ultralytics.yolo.utils.torch_utils import get_flops, get_num_params
+except ModuleNotFoundError:
+ from ultralytics.utils import RANK
+ from ultralytics.utils.torch_utils import get_flops, get_num_params
+from ultralytics.yolo.v8.classify.train import ClassificationTrainer
+
+import wandb
+from wandb.sdk.lib import telemetry
+
+
+class WandbCallback:
+ """An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.
+
+ Usage:
+ ```python
+ from wandb.integration.yolov8.yolov8 import WandbCallback
+
+ model = YOLO("yolov8n.pt")
+ wandb_logger = WandbCallback(
+ model,
+ )
+ for event, callback_fn in wandb_logger.callbacks.items():
+ model.add_callback(event, callback_fn)
+ ```
+ """
+
+ def __init__(
+ self,
+ yolo: YOLO,
+ run_name: Optional[str] = None,
+ project: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ resume: Optional[str] = None,
+ **kwargs: Optional[Any],
+ ) -> None:
+ """A utility class to manage wandb run and various callbacks for the ultralytics YOLOv8 framework.
+
+ Args:
+ yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
+ run_name, str: The name of the Weights & Biases run, defaults to an auto generated run_name if `trainer.args.name` is not defined.
+ project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
+ tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
+ resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
+ **kwargs: Additional arguments to be passed to `wandb.init()`.
+ """
+ self.yolo = yolo
+ self.run_name = run_name
+ self.project = project
+ self.tags = tags
+ self.resume = resume
+ self.kwargs = kwargs
+
+ def on_pretrain_routine_start(self, trainer: BaseTrainer) -> None:
+ """Starts a new wandb run to track the training process and log to Weights & Biases.
+
+ Args:
+ trainer: A task trainer that's inherited from `:class:ultralytics.yolo.engine.trainer.BaseTrainer`
+ that contains the model training and optimization routine.
+ """
+ if wandb.run is None:
+ self.run = wandb.init(
+ name=self.run_name if self.run_name else trainer.args.name,
+ project=self.project
+ if self.project
+ else trainer.args.project or "YOLOv8",
+ tags=self.tags if self.tags else ["YOLOv8"],
+ config=vars(trainer.args),
+ resume=self.resume if self.resume else None,
+ **self.kwargs,
+ )
+ else:
+ self.run = wandb.run
+ assert self.run is not None
+ self.run.define_metric("epoch", hidden=True)
+ self.run.define_metric(
+ "train/*", step_metric="epoch", step_sync=True, summary="min"
+ )
+
+ self.run.define_metric(
+ "val/*", step_metric="epoch", step_sync=True, summary="min"
+ )
+
+ self.run.define_metric(
+ "metrics/*", step_metric="epoch", step_sync=True, summary="max"
+ )
+ self.run.define_metric(
+ "lr/*", step_metric="epoch", step_sync=True, summary="last"
+ )
+
+ with telemetry.context(run=wandb.run) as tel:
+ tel.feature.ultralytics_yolov8 = True
+
+ def on_pretrain_routine_end(self, trainer: BaseTrainer) -> None:
+ assert self.run is not None
+ self.run.summary.update(
+ {
+ "model/parameters": get_num_params(trainer.model),
+ "model/GFLOPs": round(get_flops(trainer.model), 3),
+ }
+ )
+
+ def on_train_epoch_start(self, trainer: BaseTrainer) -> None:
+ """On train epoch start we only log epoch number to the Weights & Biases run."""
+ # We log the epoch number here to commit the previous step,
+ assert self.run is not None
+ self.run.log({"epoch": trainer.epoch + 1})
+
+ def on_train_epoch_end(self, trainer: BaseTrainer) -> None:
+ """On train epoch end we log all the metrics to the Weights & Biases run."""
+ assert self.run is not None
+ self.run.log(
+ {
+ **trainer.metrics,
+ **trainer.label_loss_items(trainer.tloss, prefix="train"),
+ **trainer.lr,
+ },
+ )
+ # Currently only the detection and segmentation trainers save images to the save_dir
+ if not isinstance(trainer, ClassificationTrainer):
+ self.run.log(
+ {
+ "train_batch_images": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.save_dir.glob("train_batch*.jpg")
+ ]
+ }
+ )
+
+ def on_fit_epoch_end(self, trainer: BaseTrainer) -> None:
+ """On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary."""
+ assert self.run is not None
+ if trainer.epoch == 0:
+ speeds = [
+ trainer.validator.speed.get(
+ key,
+ )
+ for key in (1, "inference")
+ ]
+ speed = speeds[0] if speeds[0] else speeds[1]
+ if speed:
+ self.run.summary.update(
+ {
+ "model/speed(ms/img)": round(speed, 3),
+ }
+ )
+ if trainer.best_fitness == trainer.fitness:
+ self.run.summary.update(
+ {
+ "best/epoch": trainer.epoch + 1,
+ **{f"best/{key}": val for key, val in trainer.metrics.items()},
+ }
+ )
+
+ def on_train_end(self, trainer: BaseTrainer) -> None:
+ """On train end we log all the media, including plots, images and best model artifact to Weights & Biases."""
+ # Currently only the detection and segmentation trainers save images to the save_dir
+ assert self.run is not None
+ if not isinstance(trainer, ClassificationTrainer):
+ assert self.run is not None
+ self.run.log(
+ {
+ "plots": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.save_dir.glob("*.png")
+ ],
+ "val_images": [
+ wandb.Image(str(image_path), caption=image_path.stem)
+ for image_path in trainer.validator.save_dir.glob("val*.jpg")
+ ],
+ },
+ )
+
+ if trainer.best.exists():
+ assert self.run is not None
+ self.run.log_artifact(
+ str(trainer.best),
+ type="model",
+ name=f"{self.run.name}_{trainer.args.task}.pt",
+ aliases=["best", f"epoch_{trainer.epoch + 1}"],
+ )
+
+ def on_model_save(self, trainer: BaseTrainer) -> None:
+ """On model save we log the model as an artifact to Weights & Biases."""
+ assert self.run is not None
+ self.run.log_artifact(
+ str(trainer.last),
+ type="model",
+ name=f"{self.run.name}_{trainer.args.task}.pt",
+ aliases=["last", f"epoch_{trainer.epoch + 1}"],
+ )
+
+ def teardown(self, _trainer: BaseTrainer) -> None:
+ """On teardown, we finish the Weights & Biases run and set it to None."""
+ assert self.run is not None
+ self.run.finish()
+ self.run = None
+
+ @property
+ def callbacks(
+ self,
+ ) -> Dict[str, Callable]:
+ """Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging."""
+ return {
+ "on_pretrain_routine_start": self.on_pretrain_routine_start,
+ "on_pretrain_routine_end": self.on_pretrain_routine_end,
+ "on_train_epoch_start": self.on_train_epoch_start,
+ "on_train_epoch_end": self.on_train_epoch_end,
+ "on_fit_epoch_end": self.on_fit_epoch_end,
+ "on_train_end": self.on_train_end,
+ "on_model_save": self.on_model_save,
+ "teardown": self.teardown,
+ }
+
+
+def add_callbacks(
+ yolo: YOLO,
+ run_name: Optional[str] = None,
+ project: Optional[str] = None,
+ tags: Optional[List[str]] = None,
+ resume: Optional[str] = None,
+ **kwargs: Optional[Any],
+) -> YOLO:
+ """A YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.
+
+ Args:
+ yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO`
+ run_name, str: The name of the Weights & Biases run, defaults to an auto generated name if `trainer.args.name` is not defined.
+ project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined.
+ tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`.
+ resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`.
+ **kwargs: Additional arguments to be passed to `wandb.init()`.
+
+ Usage:
+ ```python
+ from wandb.integration.yolov8 import add_callbacks as add_wandb_callbacks
+
+ model = YOLO("yolov8n.pt")
+ add_wandb_callbacks(
+ model,
+ )
+ model.train(
+ data="coco128.yaml",
+ epochs=3,
+ imgsz=640,
+ )
+ ```
+ """
+ wandb.termwarn(
+ """The wandb callback is currently in beta and is subject to change based on updates to `ultralytics yolov8`.
+ The callback is tested and supported for ultralytics v8.0.43 and above.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
+ """,
+ repeat=False,
+ )
+ wandb.termwarn(
+ """This wandb callback is no longer functional and would be deprecated in the near future.
+ We recommend you to use the updated callback using `from wandb.integration.ultralytics import add_wandb_callback`.
+ The updated callback is tested and supported for ultralytics 8.0.167 and above.
+ You can refer to https://docs.wandb.ai/guides/integrations/ultralytics for the updated documentation.
+ Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`.
+ """,
+ repeat=False,
+ )
+
+ if RANK in [-1, 0]:
+ wandb_logger = WandbCallback(
+ yolo, run_name=run_name, project=project, tags=tags, resume=resume, **kwargs
+ )
+ for event, callback_fn in wandb_logger.callbacks.items():
+ yolo.add_callback(event, callback_fn)
+ return yolo
+ else:
+ wandb.termerror(
+ "The RANK of the process to add the callbacks was neither 0 or -1."
+ "No Weights & Biases callbacks were added to this instance of the YOLO model."
+ )
+ return yolo
diff --git a/venv/lib/python3.10/site-packages/wandb/mpmain/__init__.py b/venv/lib/python3.10/site-packages/wandb/mpmain/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/wandb/mpmain/__main__.py b/venv/lib/python3.10/site-packages/wandb/mpmain/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02e8a24d9fbce482e31cde126d8407586a61b3fd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/mpmain/__main__.py
@@ -0,0 +1 @@
+# This module is initialized after multiprocessing spawn
diff --git a/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..faf7b796d6d3427338a26dd975e04f8765cb1c4e
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0947f209dd3d3c254bff7198d47e2f380655f904
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/mpmain/__pycache__/__main__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbf6bf22f42d91b1f989c4eec981eb0bb9460940
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/bar.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/bar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..890bfd7fc77fb25224378f54e2f93403efb15b28
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/bar.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/custom_chart.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/custom_chart.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8964f962111c30adbebb72d1c7c6ba1f91cc908
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/custom_chart.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58022ff7783206f4ef623ef71daeb7218c0e7902
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/histogram.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6126bfaae951aed4e7065fa1fba0eef2bb09efc9
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line_series.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line_series.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ede76681d40851c8dcc90d7d620353d7e3cd99aa
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/line_series.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/pr_curve.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/pr_curve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e87f4a871f74db6cd29625dec8f3b69a67914f5
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/pr_curve.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/roc_curve.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/roc_curve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f08fcda07c634f8e655f6c65d2a083fdf55652db
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/roc_curve.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..212fe30edbc81be92dcfdf8b02cb251fc93a8886
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/scatter.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41c4a0323bfe762ed48a1882f0e5ce2d2904e076
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/utils.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/viz.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/viz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..451e1f033e31b08ed9397a986d5d91f548c332d8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/plot/__pycache__/viz.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/custom_chart.py b/venv/lib/python3.10/site-packages/wandb/plot/custom_chart.py
new file mode 100644
index 0000000000000000000000000000000000000000..62cd8784cdc63b2af264cd51ae7ebb80e7bddbbc
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/plot/custom_chart.py
@@ -0,0 +1,147 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+import wandb
+
+
+@dataclass
+class CustomChartSpec:
+ spec_name: str
+ fields: dict[str, Any]
+ string_fields: dict[str, Any]
+ key: str = ""
+ panel_type: str = "Vega2"
+ split_table: bool = False
+
+ @property
+ def table_key(self) -> str:
+ if not self.key:
+ raise wandb.Error("Key for the custom chart spec is not set.")
+ if self.split_table:
+ return f"Custom Chart Tables/{self.key}_table"
+ return f"{self.key}_table"
+
+ @property
+ def config_value(self) -> dict[str, Any]:
+ return {
+ "panel_type": self.panel_type,
+ "panel_config": {
+ "panelDefId": self.spec_name,
+ "fieldSettings": self.fields,
+ "stringSettings": self.string_fields,
+ "transform": {"name": "tableWithLeafColNames"},
+ "userQuery": {
+ "queryFields": [
+ {
+ "name": "runSets",
+ "args": [{"name": "runSets", "value": "${runSets}"}],
+ "fields": [
+ {"name": "id", "fields": []},
+ {"name": "name", "fields": []},
+ {"name": "_defaultColorIndex", "fields": []},
+ {
+ "name": "summaryTable",
+ "args": [
+ {
+ "name": "tableKey",
+ "value": self.table_key,
+ }
+ ],
+ "fields": [],
+ },
+ ],
+ }
+ ],
+ },
+ },
+ }
+
+ @property
+ def config_key(self) -> tuple[str, str, str]:
+ return ("_wandb", "visualize", self.key)
+
+
+@dataclass
+class CustomChart:
+ table: wandb.Table
+ spec: CustomChartSpec
+
+ def set_key(self, key: str):
+ """Sets the key for the spec and updates dependent configurations."""
+ self.spec.key = key
+
+
+def plot_table(
+ vega_spec_name: str,
+ data_table: wandb.Table,
+ fields: dict[str, Any],
+ string_fields: dict[str, Any] | None = None,
+ split_table: bool = False,
+) -> CustomChart:
+ """Creates a custom charts using a Vega-Lite specification and a `wandb.Table`.
+
+ This function creates a custom chart based on a Vega-Lite specification and
+ a data table represented by a `wandb.Table` object. The specification needs
+ to be predefined and stored in the W&B backend. The function returns a custom
+ chart object that can be logged to W&B using `wandb.Run.log()`.
+
+ Args:
+ vega_spec_name: The name or identifier of the Vega-Lite spec
+ that defines the visualization structure.
+ data_table: A `wandb.Table` object containing the data to be
+ visualized.
+ fields: A mapping between the fields in the Vega-Lite spec and the
+ corresponding columns in the data table to be visualized.
+ string_fields: A dictionary for providing values for any string constants
+ required by the custom visualization.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass the chart object as argument to `wandb.Run.log()`.
+
+ Raises:
+ wandb.Error: If `data_table` is not a `wandb.Table` object.
+
+ Example:
+ ```python
+ # Create a custom chart using a Vega-Lite spec and the data table.
+ import wandb
+
+ data = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
+ table = wandb.Table(data=data, columns=["x", "y"])
+ fields = {"x": "x", "y": "y", "title": "MY TITLE"}
+
+ with wandb.init() as run:
+ # Training code goes here
+
+ # Create a custom title with `string_fields`.
+ my_custom_chart = wandb.plot_table(
+ vega_spec_name="wandb/line/v0",
+ data_table=table,
+ fields=fields,
+ string_fields={"title": "Title"},
+ )
+
+ run.log({"custom_chart": my_custom_chart})
+ ```
+ """
+
+ if not isinstance(data_table, wandb.Table):
+ raise wandb.Error(
+ f"Expected `data_table` to be `wandb.Table` type, instead got {type(data_table).__name__}"
+ )
+
+ return CustomChart(
+ table=data_table,
+ spec=CustomChartSpec(
+ spec_name=vega_spec_name,
+ fields=fields,
+ string_fields=string_fields or {},
+ split_table=split_table,
+ ),
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/roc_curve.py b/venv/lib/python3.10/site-packages/wandb/plot/roc_curve.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce42232a9d0a3a91ed0017a3c126b4acc7063402
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/plot/roc_curve.py
@@ -0,0 +1,163 @@
+from __future__ import annotations
+
+import numbers
+from typing import TYPE_CHECKING, Sequence
+
+import wandb
+from wandb import util
+from wandb.plot.custom_chart import plot_table
+from wandb.plot.utils import test_missing, test_types
+
+if TYPE_CHECKING:
+ from wandb.plot.custom_chart import CustomChart
+
+
+def roc_curve(
+ y_true: Sequence[numbers.Number],
+ y_probas: Sequence[Sequence[float]] | None = None,
+ labels: list[str] | None = None,
+ classes_to_plot: list[numbers.Number] | None = None,
+ title: str = "ROC Curve",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs Receiver Operating Characteristic (ROC) curve chart.
+
+ Args:
+ y_true: The true class labels (ground truth)
+ for the target variable. Shape should be (num_samples,).
+ y_probas: The predicted probabilities or
+ decision scores for each class. Shape should be (num_samples, num_classes).
+ labels: Human-readable labels corresponding to the class
+ indices in `y_true`. For example, if `labels=['dog', 'cat']`,
+ class 0 will be displayed as 'dog' and class 1 as 'cat' in the plot.
+ If None, the raw class indices from `y_true` will be used.
+ Default is None.
+ classes_to_plot: A subset of unique class labels
+ to include in the ROC curve. If None, all classes in `y_true` will
+ be plotted. Default is None.
+ title: Title of the ROC curve plot. Default is "ROC Curve".
+ split_table: Whether the table should be split into a separate
+ section in the W&B UI. If `True`, the table will be displayed in a
+ section named "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+
+ Raises:
+ wandb.Error: If numpy, pandas, or scikit-learn are not found.
+
+ Example:
+ ```python
+ import numpy as np
+ import wandb
+
+ # Simulate a medical diagnosis classification problem with three diseases
+ n_samples = 200
+ n_classes = 3
+
+ # True labels: assign "Diabetes", "Hypertension", or "Heart Disease" to
+ # each sample
+ disease_labels = ["Diabetes", "Hypertension", "Heart Disease"]
+ # 0: Diabetes, 1: Hypertension, 2: Heart Disease
+ y_true = np.random.choice([0, 1, 2], size=n_samples)
+
+ # Predicted probabilities: simulate predictions, ensuring they sum to 1
+ # for each sample
+ y_probas = np.random.dirichlet(np.ones(n_classes), size=n_samples)
+
+ # Specify classes to plot (plotting all three diseases)
+ classes_to_plot = [0, 1, 2]
+
+ # Initialize a W&B run and log a ROC curve plot for disease classification
+ with wandb.init(project="medical_diagnosis") as run:
+ roc_plot = wandb.plot.roc_curve(
+ y_true=y_true,
+ y_probas=y_probas,
+ labels=disease_labels,
+ classes_to_plot=classes_to_plot,
+ title="ROC Curve for Disease Classification",
+ )
+ run.log({"roc-curve": roc_plot})
+ ```
+ """
+ np = util.get_module(
+ "numpy",
+ required="roc requires the numpy library, install with `pip install numpy`",
+ )
+ pd = util.get_module(
+ "pandas",
+ required="roc requires the pandas library, install with `pip install pandas`",
+ )
+ sklearn_metrics = util.get_module(
+ "sklearn.metrics",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+ sklearn_utils = util.get_module(
+ "sklearn.utils",
+ "roc requires the scikit library, install with `pip install scikit-learn`",
+ )
+
+ y_true = np.array(y_true)
+ y_probas = np.array(y_probas)
+
+ if not test_missing(y_true=y_true, y_probas=y_probas):
+ return
+ if not test_types(y_true=y_true, y_probas=y_probas):
+ return
+
+ classes = np.unique(y_true)
+ if classes_to_plot is None:
+ classes_to_plot = classes
+
+ fpr = {}
+ tpr = {}
+ indices_to_plot = np.where(np.isin(classes, classes_to_plot))[0]
+ for i in indices_to_plot:
+ if labels is not None and (
+ isinstance(classes[i], int) or isinstance(classes[0], np.integer)
+ ):
+ class_label = labels[classes[i]]
+ else:
+ class_label = classes[i]
+
+ fpr[class_label], tpr[class_label], _ = sklearn_metrics.roc_curve(
+ y_true, y_probas[..., i], pos_label=classes[i]
+ )
+
+ df = pd.DataFrame(
+ {
+ "class": np.hstack([[k] * len(v) for k, v in fpr.items()]),
+ "fpr": np.hstack(list(fpr.values())),
+ "tpr": np.hstack(list(tpr.values())),
+ }
+ ).round(3)
+
+ if len(df) > wandb.Table.MAX_ROWS:
+ wandb.termwarn(
+ f"wandb uses only {wandb.Table.MAX_ROWS} data points to create the plots."
+ )
+ # different sampling could be applied, possibly to ensure endpoints are kept
+ df = sklearn_utils.resample(
+ df,
+ replace=False,
+ n_samples=wandb.Table.MAX_ROWS,
+ random_state=42,
+ stratify=df["class"],
+ ).sort_values(["fpr", "tpr", "class"])
+
+ return plot_table(
+ data_table=wandb.Table(dataframe=df),
+ vega_spec_name="wandb/area-under-curve/v0",
+ fields={
+ "x": "fpr",
+ "y": "tpr",
+ "class": "class",
+ },
+ string_fields={
+ "title": title,
+ "x-axis-title": "False positive rate",
+ "y-axis-title": "True positive rate",
+ },
+ split_table=split_table,
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/plot/scatter.py b/venv/lib/python3.10/site-packages/wandb/plot/scatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..40e3d8033e2d6249554e3de56904add3ef30ffbd
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/plot/scatter.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from wandb.plot.custom_chart import plot_table
+
+if TYPE_CHECKING:
+ import wandb
+ from wandb.plot.custom_chart import CustomChart
+
+
+def scatter(
+ table: wandb.Table,
+ x: str,
+ y: str,
+ title: str = "",
+ split_table: bool = False,
+) -> CustomChart:
+ """Constructs a scatter plot from a wandb.Table of data.
+
+ Args:
+ table: The W&B Table containing the data to visualize.
+ x: The name of the column used for the x-axis.
+ y: The name of the column used for the y-axis.
+ title: The title of the scatter chart.
+ split_table: Whether the table should be split into a separate section
+ in the W&B UI. If `True`, the table will be displayed in a section named
+ "Custom Chart Tables". Default is `False`.
+
+ Returns:
+ CustomChart: A custom chart object that can be logged to W&B. To log the
+ chart, pass it to `wandb.log()`.
+ Example:
+ ```python
+ import math
+ import random
+ import wandb
+
+ # Simulate temperature variations at different altitudes over time
+ data = [
+ [i, random.uniform(-10, 20) - 0.005 * i + 5 * math.sin(i / 50)]
+ for i in range(300)
+ ]
+
+ # Create W&B table with altitude (m) and temperature (°C) columns
+ table = wandb.Table(data=data, columns=["altitude (m)", "temperature (°C)"])
+
+ # Initialize W&B run and log the scatter plot
+ with wandb.init(project="temperature-altitude-scatter") as run:
+ # Create and log the scatter plot
+ scatter_plot = wandb.plot.scatter(
+ table=table,
+ x="altitude (m)",
+ y="temperature (°C)",
+ title="Altitude vs Temperature",
+ )
+ run.log({"altitude-temperature-scatter": scatter_plot})
+ ```
+ """
+ return plot_table(
+ data_table=table,
+ vega_spec_name="wandb/scatter/v0",
+ fields={"x": x, "y": y},
+ string_fields={"title": title},
+ split_table=split_table,
+ )
diff --git a/venv/lib/python3.10/site-packages/wandb/sync/__init__.py b/venv/lib/python3.10/site-packages/wandb/sync/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92213239a7fd075123dfe49928241b99640abc0b
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/sync/__init__.py
@@ -0,0 +1,3 @@
+"""module sync."""
+
+from .sync import SyncManager, get_run_from_path, get_runs
diff --git a/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..837f882e1edb3d8efca54dfd90ab44e32408eeb0
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/sync.cpython-310.pyc b/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/sync.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67c344f8bd6c24e5de0a27bc46c0f9b795cd2c78
Binary files /dev/null and b/venv/lib/python3.10/site-packages/wandb/sync/__pycache__/sync.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/wandb/sync/sync.py b/venv/lib/python3.10/site-packages/wandb/sync/sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..822746c21f9cb7afafe7529f238a858ce5eb8a54
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/wandb/sync/sync.py
@@ -0,0 +1,452 @@
+"""sync."""
+
+import atexit
+import datetime
+import fnmatch
+import os
+import queue
+import sys
+import tempfile
+import threading
+import time
+from typing import List, Optional
+from urllib.parse import quote as url_quote
+
+import wandb
+from wandb.proto import wandb_internal_pb2 # type: ignore
+from wandb.sdk.interface.interface_queue import InterfaceQueue
+from wandb.sdk.internal import context, datastore, handler, sender, tb_watcher
+from wandb.sdk.internal.settings_static import SettingsStatic
+from wandb.sdk.lib import filesystem
+from wandb.util import check_and_warn_old
+
+WANDB_SUFFIX = ".wandb"
+SYNCED_SUFFIX = ".synced"
+TFEVENT_SUBSTRING = ".tfevents."
+
+
+class _LocalRun:
+ def __init__(self, path, synced=None):
+ self.path = path
+ self.synced = synced
+ self.offline = os.path.basename(path).startswith("offline-")
+ self.datetime = datetime.datetime.strptime(
+ os.path.basename(path).split("run-")[1].split("-")[0], "%Y%m%d_%H%M%S"
+ )
+
+ def __str__(self):
+ return self.path
+
+
+class SyncThread(threading.Thread):
+ def __init__(
+ self,
+ sync_list,
+ project=None,
+ entity=None,
+ run_id=None,
+ job_type=None,
+ view=None,
+ verbose=None,
+ mark_synced=None,
+ app_url=None,
+ sync_tensorboard=None,
+ log_path=None,
+ append=None,
+ skip_console=None,
+ replace_tags=None,
+ ):
+ threading.Thread.__init__(self)
+ # mark this process as internal
+ wandb._set_internal_process(disable=True)
+ self._sync_list = sync_list
+ self._project = project
+ self._entity = entity
+ self._run_id = run_id
+ self._job_type = job_type
+ self._view = view
+ self._verbose = verbose
+ self._mark_synced = mark_synced
+ self._app_url = app_url
+ self._sync_tensorboard = sync_tensorboard
+ self._log_path = log_path
+ self._append = append
+ self._skip_console = skip_console
+ self._replace_tags = replace_tags or {}
+
+ self._tmp_dir = tempfile.TemporaryDirectory()
+ atexit.register(self._tmp_dir.cleanup)
+
+ def _parse_pb(self, data, exit_pb=None):
+ pb = wandb_internal_pb2.Record()
+ pb.ParseFromString(data)
+ record_type = pb.WhichOneof("record_type")
+ if self._view:
+ if self._verbose:
+ print("Record:", pb) # noqa: T201
+ else:
+ print("Record:", record_type) # noqa: T201
+ return pb, exit_pb, True
+ if record_type == "run":
+ if self._run_id:
+ pb.run.run_id = self._run_id
+ if self._project:
+ pb.run.project = self._project
+ if self._entity:
+ pb.run.entity = self._entity
+ if self._job_type:
+ pb.run.job_type = self._job_type
+ # Replace tags if specified
+ if self._replace_tags:
+ new_tags = [self._replace_tags.get(tag, tag) for tag in pb.run.tags]
+ pb.run.ClearField("tags")
+ pb.run.tags.extend(new_tags)
+ pb.control.req_resp = True
+ elif record_type in ("output", "output_raw") and self._skip_console:
+ return pb, exit_pb, True
+ elif record_type == "exit":
+ exit_pb = pb
+ return pb, exit_pb, True
+ elif record_type == "final":
+ assert exit_pb, "final seen without exit"
+ pb = exit_pb
+ exit_pb = None
+ return pb, exit_pb, False
+
+ def _find_tfevent_files(self, sync_item):
+ tb_event_files = 0
+ tb_logdirs = []
+ tb_root = None
+ if self._sync_tensorboard:
+ if os.path.isdir(sync_item):
+ files = []
+ for dirpath, _, _files in os.walk(sync_item):
+ for f in _files:
+ if TFEVENT_SUBSTRING in f:
+ files.append(os.path.join(dirpath, f))
+ for tfevent in files:
+ tb_event_files += 1
+ tb_dir = os.path.dirname(os.path.abspath(tfevent))
+ if tb_dir not in tb_logdirs:
+ tb_logdirs.append(tb_dir)
+ if len(tb_logdirs) > 0:
+ tb_root = os.path.dirname(os.path.commonprefix(tb_logdirs))
+
+ elif TFEVENT_SUBSTRING in sync_item:
+ tb_root = os.path.dirname(os.path.abspath(sync_item))
+ tb_logdirs.append(tb_root)
+ tb_event_files = 1
+ return tb_event_files, tb_logdirs, tb_root
+
+ def _setup_tensorboard(self, tb_root, tb_logdirs, tb_event_files, sync_item):
+ """Return true if this sync item can be synced as tensorboard."""
+ if tb_root is not None:
+ if tb_event_files > 0 and sync_item.endswith(WANDB_SUFFIX):
+ wandb.termwarn("Found .wandb file, not streaming tensorboard metrics.")
+ else:
+ print(f"Found {tb_event_files} tfevent files in {tb_root}") # noqa: T201
+ if len(tb_logdirs) > 3:
+ wandb.termwarn(
+ f"Found {len(tb_logdirs)} directories containing tfevent files. "
+ "If these represent multiple experiments, sync them "
+ "individually or pass a list of paths."
+ )
+ return True
+ return False
+
+ def _send_tensorboard(self, tb_root, tb_logdirs, send_manager):
+ if self._entity is None:
+ viewer, _ = send_manager._api.viewer_server_info()
+ self._entity = viewer.get("entity")
+ proto_run = wandb_internal_pb2.RunRecord()
+ proto_run.run_id = self._run_id or wandb.util.generate_id()
+ proto_run.project = self._project or wandb.util.auto_project_name(None)
+ proto_run.entity = self._entity
+ proto_run.telemetry.feature.sync_tfevents = True
+
+ url = (
+ f"{self._app_url}"
+ f"/{url_quote(proto_run.entity)}"
+ f"/{url_quote(proto_run.project)}"
+ f"/runs/{url_quote(proto_run.run_id)}"
+ )
+ print(f"Syncing: {url} ...") # noqa: T201
+ sys.stdout.flush()
+ # using a handler here automatically handles the step
+ # logic, adds summaries to the run, and handles different
+ # file types (like images)... but we need to remake the send_manager
+ record_q = queue.Queue()
+ sender_record_q = queue.Queue()
+ new_interface = InterfaceQueue(record_q)
+ context_keeper = context.ContextKeeper()
+ send_manager = sender.SendManager(
+ settings=send_manager._settings,
+ record_q=sender_record_q,
+ result_q=queue.Queue(),
+ interface=new_interface,
+ context_keeper=context_keeper,
+ )
+ record = send_manager._interface._make_record(run=proto_run)
+ settings = wandb.Settings(
+ root_dir=self._tmp_dir.name,
+ run_id=proto_run.run_id,
+ x_start_time=time.time(),
+ )
+
+ settings_static = SettingsStatic(settings.to_proto())
+
+ handle_manager = handler.HandleManager(
+ settings=settings_static,
+ record_q=record_q,
+ result_q=None,
+ stopped=False,
+ writer_q=sender_record_q,
+ interface=new_interface,
+ context_keeper=context_keeper,
+ )
+
+ filesystem.mkdir_exists_ok(settings.files_dir)
+ send_manager.send_run(record, file_dir=settings.files_dir)
+ watcher = tb_watcher.TBWatcher(settings, proto_run, new_interface, True)
+
+ for tb in tb_logdirs:
+ watcher.add(tb, True, tb_root)
+ sys.stdout.flush()
+ watcher.finish()
+
+ # send all of our records like a boss
+ progress_step = 0
+ spinner_states = ["-", "\\", "|", "/"]
+ line = " Uploading data to wandb\r"
+ while len(handle_manager) > 0:
+ data = next(handle_manager)
+ handle_manager.handle(data)
+ while len(send_manager) > 0:
+ data = next(send_manager)
+ send_manager.send(data)
+
+ print_line = spinner_states[progress_step % 4] + line
+ wandb.termlog(print_line, newline=False, prefix=True)
+ progress_step += 1
+
+ # finish sending any data
+ while len(send_manager) > 0:
+ data = next(send_manager)
+ send_manager.send(data)
+ sys.stdout.flush()
+ handle_manager.finish()
+ send_manager.finish()
+
+ def _robust_scan(self, ds):
+ """Attempt to scan data, handling incomplete files."""
+ try:
+ return ds.scan_data()
+ except AssertionError as e:
+ if ds.in_last_block():
+ wandb.termwarn(
+ f".wandb file is incomplete ({e}), be sure to sync this run again once it's finished"
+ )
+ return None
+ else:
+ raise
+
+ def run(self):
+ if self._log_path is not None:
+ print(f"Find logs at: {self._log_path}") # noqa: T201
+ for sync_item in self._sync_list:
+ tb_event_files, tb_logdirs, tb_root = self._find_tfevent_files(sync_item)
+ if os.path.isdir(sync_item):
+ files = os.listdir(sync_item)
+ filtered_files = list(filter(lambda f: f.endswith(WANDB_SUFFIX), files))
+ if tb_root is None and (
+ check_and_warn_old(files) or len(filtered_files) != 1
+ ):
+ print(f"Skipping directory: {sync_item}") # noqa: T201
+ continue
+ if len(filtered_files) > 0:
+ sync_item = os.path.join(sync_item, filtered_files[0])
+ sync_tb = self._setup_tensorboard(
+ tb_root, tb_logdirs, tb_event_files, sync_item
+ )
+ # If we're syncing tensorboard, let's use a tmp dir for images etc.
+ root_dir = self._tmp_dir.name if sync_tb else os.path.dirname(sync_item)
+
+ # When appending we are allowing a possible resume, ie the run
+ # does not have to exist already
+ resume = "allow" if self._append else None
+
+ sm = sender.SendManager.setup(root_dir, resume=resume)
+ if sync_tb:
+ self._send_tensorboard(tb_root, tb_logdirs, sm)
+ continue
+
+ ds = datastore.DataStore()
+ try:
+ ds.open_for_scan(sync_item)
+ except AssertionError as e:
+ print(f".wandb file is empty ({e}), skipping: {sync_item}") # noqa: T201
+ continue
+
+ # save exit for final send
+ exit_pb = None
+ finished = False
+ shown = False
+ while True:
+ data = self._robust_scan(ds)
+ if data is None:
+ break
+ pb, exit_pb, cont = self._parse_pb(data, exit_pb)
+ if exit_pb is not None:
+ finished = True
+ if cont:
+ continue
+ sm.send(pb)
+ # send any records that were added in previous send
+ while not sm._record_q.empty():
+ data = sm._record_q.get(block=True)
+ sm.send(data)
+
+ if pb.control.req_resp:
+ result = sm._result_q.get(block=True)
+ result_type = result.WhichOneof("result_type")
+ if not shown and result_type == "run_result":
+ r = result.run_result.run
+ # TODO(jhr): hardcode until we have settings in sync
+ url = (
+ f"{self._app_url}"
+ f"/{url_quote(r.entity)}"
+ f"/{url_quote(r.project)}"
+ f"/runs/{url_quote(r.run_id)}"
+ )
+ print(f"Syncing: {url} ... ", end="") # noqa: T201
+ sys.stdout.flush()
+ shown = True
+ sm.finish()
+ # Only mark synced if the run actually finished
+ if self._mark_synced and not self._view and finished:
+ synced_file = f"{sync_item}{SYNCED_SUFFIX}"
+ with open(synced_file, "w"):
+ pass
+ print("done.") # noqa: T201
+
+
+class SyncManager:
+ def __init__(
+ self,
+ project=None,
+ entity=None,
+ run_id=None,
+ job_type=None,
+ mark_synced=None,
+ app_url=None,
+ view=None,
+ verbose=None,
+ sync_tensorboard=None,
+ log_path=None,
+ append=None,
+ skip_console=None,
+ replace_tags=None,
+ ):
+ self._sync_list = []
+ self._thread = None
+ self._project = project
+ self._entity = entity
+ self._run_id = run_id
+ self._job_type = job_type
+ self._mark_synced = mark_synced
+ self._app_url = app_url
+ self._view = view
+ self._verbose = verbose
+ self._sync_tensorboard = sync_tensorboard
+ self._log_path = log_path
+ self._append = append
+ self._skip_console = skip_console
+ self._replace_tags = replace_tags or {}
+
+ def status(self):
+ pass
+
+ def add(self, p):
+ self._sync_list.append(os.path.abspath(str(p)))
+
+ def start(self):
+ # create a thread for each file?
+ self._thread = SyncThread(
+ sync_list=self._sync_list,
+ project=self._project,
+ entity=self._entity,
+ run_id=self._run_id,
+ job_type=self._job_type,
+ view=self._view,
+ verbose=self._verbose,
+ mark_synced=self._mark_synced,
+ app_url=self._app_url,
+ sync_tensorboard=self._sync_tensorboard,
+ log_path=self._log_path,
+ append=self._append,
+ skip_console=self._skip_console,
+ replace_tags=self._replace_tags,
+ )
+ self._thread.start()
+
+ def is_done(self):
+ return not self._thread.is_alive()
+
+ def poll(self):
+ time.sleep(1)
+ return False
+
+
+def get_runs(
+ include_offline: bool = True,
+ include_online: bool = True,
+ include_synced: bool = False,
+ include_unsynced: bool = True,
+ exclude_globs: Optional[List[str]] = None,
+ include_globs: Optional[List[str]] = None,
+):
+ # TODO(jhr): grab dir info from settings
+ base = ".wandb" if os.path.exists(".wandb") else "wandb"
+ if not os.path.exists(base):
+ return ()
+ all_dirs = os.listdir(base)
+ dirs = []
+ if include_offline:
+ dirs += filter(lambda _d: _d.startswith("offline-run-"), all_dirs)
+ if include_online:
+ dirs += filter(lambda _d: _d.startswith("run-"), all_dirs)
+ # find run file in each dir
+ fnames = []
+ dirs.sort()
+ for d in dirs:
+ paths = os.listdir(os.path.join(base, d))
+ if exclude_globs:
+ paths = set(paths)
+ for g in exclude_globs:
+ paths = paths - set(fnmatch.filter(paths, g))
+ paths = list(paths)
+ if include_globs:
+ new_paths = set()
+ for g in include_globs:
+ new_paths = new_paths.union(fnmatch.filter(paths, g))
+ paths = list(new_paths)
+ for f in paths:
+ if f.endswith(WANDB_SUFFIX):
+ fnames.append(os.path.join(base, d, f))
+ filtered = []
+ for f in fnames:
+ dname = os.path.dirname(f)
+ # TODO(frz): online runs are assumed to be synced, verify from binary log.
+ if os.path.exists(f"{f}{SYNCED_SUFFIX}") or os.path.basename(dname).startswith(
+ "run-"
+ ):
+ if include_synced:
+ filtered.append(_LocalRun(dname, True))
+ else:
+ if include_unsynced:
+ filtered.append(_LocalRun(dname, False))
+ return tuple(filtered)
+
+
+def get_run_from_path(path):
+ return _LocalRun(path)
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/METADATA b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..1640d911c8a23ed7dca476ed58a962b1923e4473
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/METADATA
@@ -0,0 +1,70 @@
+Metadata-Version: 2.1
+Name: xgrammar
+Version: 0.1.18
+Summary: Efficient, Flexible and Portable Structured Generation
+Keywords: machine learning,inference
+Author: MLC Team
+License: Apache 2.0
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Education
+Classifier: Intended Audience :: Science/Research
+Project-URL: Homepage, https://xgrammar.mlc.ai/
+Project-URL: GitHub, https://github.com/mlc-ai/xgrammar
+Requires-Python: <4,>=3.8
+Requires-Dist: pydantic
+Requires-Dist: sentencepiece
+Requires-Dist: tiktoken
+Requires-Dist: torch>=1.10.0
+Requires-Dist: transformers>=4.38.0
+Requires-Dist: triton; platform_system == "Linux" and platform_machine == "x86_64"
+Requires-Dist: mlx-lm; platform_system == "Darwin" and platform_machine == "arm64"
+Requires-Dist: ninja
+Provides-Extra: test
+Requires-Dist: pytest; extra == "test"
+Requires-Dist: protobuf; extra == "test"
+Requires-Dist: huggingface-hub[cli]; extra == "test"
+Requires-Dist: transformers<4.50.0; platform_system == "Darwin" and extra == "test"
+Description-Content-Type: text/markdown
+
+
+
+# XGrammar
+
+[](https://xgrammar.mlc.ai/docs/)
+[](https://github.com/mlc-ai/xgrammar/blob/main/LICENSE)
+[](https://pypi.org/project/xgrammar)
+[](https://pepy.tech/projects/xgrammar)
+
+**Efficient, Flexible and Portable Structured Generation**
+
+
+[Get Started](#get-started) | [Documentation](https://xgrammar.mlc.ai/docs/) | [Blogpost](https://blog.mlc.ai/2024/11/22/achieving-efficient-flexible-portable-structured-generation-with-xgrammar) | [Technical Report](https://arxiv.org/abs/2411.15100)
+
+
+
+## News
+- [2025/02] XGrammar has been officially integrated into [Modular's MAX](https://docs.modular.com/max/serve/structured-output)
+- [2025/01] XGrammar has been officially integrated into [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM).
+- [2024/12] XGrammar has been officially integrated into [vLLM](https://github.com/vllm-project/vllm).
+- [2024/12] We presented research talks on XGrammar at CMU Catalyst, Berkeley SkyLab, MIT HANLAB, THU IIIS, SJTU, Ant Group, SGLang Meetup, Qingke AI, Camel AI. The slides can be found [here](https://docs.google.com/presentation/d/1iS7tu2EV4IKRWDaR0F3YD7ubrNqtGYUStSskceneelc/edit?usp=sharing).
+- [2024/11] XGrammar has been officially integrated into [SGLang](https://github.com/sgl-project/sglang).
+- [2024/11] XGrammar has been officially integrated into [MLC-LLM](https://github.com/mlc-ai/mlc-llm).
+- [2024/11] We officially released XGrammar v0.1.0!
+
+## Overview
+
+
+XGrammar is an open-source library for efficient, flexible, and portable structured generation.
+It supports general context-free grammar to enable a broad range of structures while bringing careful system optimizations to enable fast executions.
+XGrammar features a minimal and portable C++ backend that can be easily integrated into multiple environments and frameworks,
+and is co-designed with the LLM inference engine and enables zero-overhead structured generation in LLM inference.
+
+
+
+## Get Started
+
+Please visit our [documentation](https://xgrammar.mlc.ai/docs/) to get started with XGrammar.
+- [Installation](https://xgrammar.mlc.ai/docs/start/install)
+- [Quick start](https://xgrammar.mlc.ai/docs/start/quick_start)
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/RECORD b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..c26be7a7809eb11b21343594ed3fc53fa6a6e43f
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/RECORD
@@ -0,0 +1,46 @@
+xgrammar-0.1.18.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+xgrammar-0.1.18.dist-info/METADATA,sha256=gknu2i0vD8g7MaC-gSTwOdDxJcyjPDRFVKjel1izUq0,3584
+xgrammar-0.1.18.dist-info/RECORD,,
+xgrammar-0.1.18.dist-info/WHEEL,sha256=eyOW1G9YDUewwwRJOGy55SqofaokBV2FtqXqzhzU_cA,156
+xgrammar-0.1.18.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
+xgrammar-0.1.18.dist-info/licenses/NOTICE,sha256=dpxpBwc8ZYAb_P484cDoC_CuThJOJ2nU8CbAOK1YPA8,54
+xgrammar/__init__.py,sha256=vr-8u4CcpaFRx89GPv1Y2Pyjzudo6zDuwYs9Dz0ZVP8,375
+xgrammar/__pycache__/__init__.cpython-310.pyc,,
+xgrammar/__pycache__/base.cpython-310.pyc,,
+xgrammar/__pycache__/compiler.cpython-310.pyc,,
+xgrammar/__pycache__/grammar.cpython-310.pyc,,
+xgrammar/__pycache__/matcher.cpython-310.pyc,,
+xgrammar/__pycache__/testing.cpython-310.pyc,,
+xgrammar/__pycache__/tokenizer_info.cpython-310.pyc,,
+xgrammar/__pycache__/version.cpython-310.pyc,,
+xgrammar/base.py,sha256=P1vjpdTGijQGy25bKiawFCqMcxYm_HqAO7WFUjiiuJ8,2360
+xgrammar/compiler.py,sha256=UCb9Fol_NBCFTDXhimc-J3P2X8kgkNrNWVflBoL1TqA,7728
+xgrammar/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+xgrammar/contrib/__pycache__/__init__.cpython-310.pyc,,
+xgrammar/contrib/__pycache__/hf.cpython-310.pyc,,
+xgrammar/contrib/__pycache__/mlxlm.cpython-310.pyc,,
+xgrammar/contrib/hf.py,sha256=nAoqTdxWhP7uWEba1HAsSyrn1MYZYvKRudDkrerIH-k,4614
+xgrammar/contrib/mlxlm.py,sha256=eoZ5baxaIJplP0ohiBY6AjofHbjfn6J5v9sFWi-lwpw,2812
+xgrammar/grammar.py,sha256=VgyNnAZFhLHHejO2W9OgWtn7ON5l7iitpBVxyestL3Y,13072
+xgrammar/kernels/__init__.py,sha256=Rz8sBcZMbQeYZiKoxvG1u7jteQj0S7gOJ3MCOfJWRX0,259
+xgrammar/kernels/__pycache__/__init__.cpython-310.pyc,,
+xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cpu.cpython-310.pyc,,
+xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cuda.cpython-310.pyc,,
+xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_torch_compile.cpython-310.pyc,,
+xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_triton.cpython-310.pyc,,
+xgrammar/kernels/__pycache__/apply_token_bitmask_mlx.cpython-310.pyc,,
+xgrammar/kernels/apply_token_bitmask_inplace_cpu.py,sha256=HOxSWkD4IZ3ikKDYKUPsaz-DL2LU8-69y_msX5tpf9k,1512
+xgrammar/kernels/apply_token_bitmask_inplace_cuda.cu,sha256=jEEl3KqavKcPDsRkf1AcPVwlaTUeVO8oOT7EX7rdQbU,10015
+xgrammar/kernels/apply_token_bitmask_inplace_cuda.py,sha256=m5bLvWDtXQG0t4FTY8akh_6NOD0hDTyp7ENN1Smrvk8,4049
+xgrammar/kernels/apply_token_bitmask_inplace_torch_compile.py,sha256=m2-wTBVvSyi-sebEgSKRfQIhg8_0jt5ZhgW-dPKWjs4,2138
+xgrammar/kernels/apply_token_bitmask_inplace_triton.py,sha256=a4STzJf7CKLZayqsz_Hqyo-zlqXkdk2Fmuqc6BZi73A,3810
+xgrammar/kernels/apply_token_bitmask_mlx.py,sha256=N1hbWiCyc0eOuK0R2Cj9LHWVi1DnOqZjWVP5TvQlgsU,883
+xgrammar/matcher.py,sha256=HrVDW_IDIl2OTV8N7TKED0Ez9uc4lTIEfs7jfBxP4Rg,13017
+xgrammar/support/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+xgrammar/support/__pycache__/__init__.cpython-310.pyc,,
+xgrammar/support/__pycache__/logging.cpython-310.pyc,,
+xgrammar/support/logging.py,sha256=8jmO9FAVVJpgbLOwclXpAowOe2vjdbtjk3Ryitphl9U,594
+xgrammar/testing.py,sha256=bOYvVYCfVBbAYWWmcc9SJF8zgy7UiEL72B7juaDxhDI,10867
+xgrammar/tokenizer_info.py,sha256=348J7MkyEBtvTUcyE4diby0xPM0U-kGeN9glu7M787Q,15734
+xgrammar/version.py,sha256=7VtgdhF7CEhyWBFHSaTl_LXmNFhWTvlSu3U4f222M_0,4296
+xgrammar/xgrammar_bindings.cpython-310-x86_64-linux-gnu.so,sha256=6YOnnwN5gmowvKM0dvD7-6HEr5su6wfcwD4r2UBL8CI,17243960
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/WHEEL b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..f4b427693f086609b0ceab2de98bd44912d9bf21
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: scikit-build-core 0.11.1
+Root-Is-Purelib: false
+Tag: cp310-cp310-manylinux_2_17_x86_64
+Tag: cp310-cp310-manylinux2014_x86_64
+
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/NOTICE b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..2d56df4754f7ebeba356393e69df5e2eef265232
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar-0.1.18.dist-info/licenses/NOTICE
@@ -0,0 +1,3 @@
+XGrammar
+
+Copyright (c) 2024 by XGrammar Contributors
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__init__.py b/venv/lib/python3.10/site-packages/xgrammar/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f77e36f074136980ff68bff42f2f30201f2788ec
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/__init__.py
@@ -0,0 +1,13 @@
+from . import testing
+from .compiler import CompiledGrammar, GrammarCompiler
+from .contrib import hf
+from .grammar import Grammar, StructuralTagItem
+from .matcher import (
+ GrammarMatcher,
+ allocate_token_bitmask,
+ apply_token_bitmask_inplace,
+ bitmask_dtype,
+ get_bitmask_shape,
+ reset_token_bitmask,
+)
+from .tokenizer_info import TokenizerInfo, VocabType
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5cf0d6150c7f8540282cd8c0d8f7163e6d872e7
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f00a8ef66e9709a4255cccb350b02255594ef258
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/base.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/compiler.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/compiler.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56ba804d027a1f26acd4c04e203db3b48acfcbd1
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/compiler.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/grammar.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/grammar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f981c938e5e2d93857802e7b91ce2f8c1dcb5092
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/grammar.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/matcher.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/matcher.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..602630fcc8c28aaa125ca2a5633fe87ad4d3cfb4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/matcher.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/testing.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/testing.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b607691514bb927158d68a6652c1d7215eb6d20
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/testing.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/tokenizer_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/tokenizer_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0138f8874502b27eea177a475a2655a5e284967f
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/tokenizer_info.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/version.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6db8d29d2e0a978b7c70ee65c0b4c302499d189
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/__pycache__/version.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/base.py b/venv/lib/python3.10/site-packages/xgrammar/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..08748daf981932be02f179066355c106a561515c
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/base.py
@@ -0,0 +1,82 @@
+"""This module provides classes to handle C++ objects from nanobind."""
+
+import os
+
+if os.environ.get("XGRAMMAR_BUILD_DOCS") != "1":
+ from . import xgrammar_bindings as _core
+else:
+ _core = "dummy namespace"
+
+
+class XGRObject:
+ """The base class for all objects in XGrammar. This class provides methods to handle the
+ C++ handle from nanobind.
+
+ In subclasses, the handle should be initialized via the the _create_from_handle, or via
+ the _init_handle method called within the __init__ method, and should not be modified
+ afterwards. Subclasses should use the _handle property to access the handle. When comparing
+ two objects, the equality is checked by comparing the C++ handles.
+
+ For performance considerations, objects in XGrammar should be lightweight and only maintain
+ a handle to the C++ objects. Heavy operations should be performed on the C++ side.
+ """
+
+ @classmethod
+ def _create_from_handle(cls, handle) -> "XGRObject":
+ """Construct an object of the class from a C++ handle.
+
+ Parameters
+ ----------
+ cls
+ The class of the object.
+
+ handle
+ The C++ handle.
+
+ Returns
+ -------
+ obj : XGRObject
+ An object of type cls.
+ """
+ obj = cls.__new__(cls)
+ obj.__handle = handle
+ return obj
+
+ def _init_handle(self, handle):
+ """Initialize an object with a handle. This method should be called in the __init__
+ method of the subclasses of XGRObject to initialize the C++ handle.
+
+ Parameters
+ ----------
+ handle
+ The C++ handle.
+ """
+ self.__handle = handle
+
+ @property
+ def _handle(self):
+ """Get the C++ handle of the object.
+
+ Returns
+ -------
+ handle
+ The C++ handle.
+ """
+ return self.__handle
+
+ def __eq__(self, other: object) -> bool:
+ """Compare two XGrammar objects by comparing their C++ handles.
+
+ Parameters
+ ----------
+ other : object
+ The other object to compare with.
+
+ Returns
+ -------
+ equal : bool
+ Whether the two objects have the same C++ handle.
+ """
+ if not isinstance(other, XGRObject):
+ return NotImplemented
+ return self._handle == other._handle
diff --git a/venv/lib/python3.10/site-packages/xgrammar/compiler.py b/venv/lib/python3.10/site-packages/xgrammar/compiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..38228ba40ed155a9beaf8e867473fdb4d9ef5225
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/compiler.py
@@ -0,0 +1,228 @@
+"""Compiling grammar for efficient token mask generation."""
+
+from typing import Any, Dict, List, Optional, Tuple, Type, Union, overload
+
+from pydantic import BaseModel
+
+from .base import XGRObject, _core
+from .grammar import Grammar, StructuralTagItem, _convert_schema_to_str
+from .tokenizer_info import TokenizerInfo
+
+
+class CompiledGrammar(XGRObject):
+ """This is the primary object to store compiled grammar.
+
+ A CompiledGrammar can be used to construct GrammarMatcher
+ to generate token masks efficiently.
+
+ Note
+ ----
+ Do not construct this class directly, instead
+ use :class:`GrammarCompiler` to construct the object.
+ """
+
+ @property
+ def grammar(self) -> Grammar:
+ """The original grammar."""
+ return Grammar._create_from_handle(self._handle.grammar)
+
+ @property
+ def tokenizer_info(self) -> TokenizerInfo:
+ """The tokenizer info associated with the compiled grammar."""
+ return TokenizerInfo._create_from_handle(self._handle.tokenizer_info)
+
+ @property
+ def memory_size_bytes(self) -> int:
+ """The approximate memory usage of the compiled grammar in bytes."""
+ return self._handle.memory_size_bytes
+
+
+class GrammarCompiler(XGRObject):
+ """The compiler for grammars. It is associated with a certain tokenizer info, and compiles
+ grammars into CompiledGrammar with the tokenizer info. It allows parallel compilation with
+ multiple threads, and has a cache to store the compilation result, avoiding compiling the
+ same grammar multiple times.
+
+ Parameters
+ ----------
+ tokenizer_info : TokenizerInfo
+ The tokenizer info.
+
+ max_threads : int, default: 8
+ The maximum number of threads used to compile the grammar.
+
+ cache_enabled : bool, default: True
+ Whether to enable the cache.
+
+ cache_limit_bytes : int, default: -1
+ The maximum memory usage for the cache in the specified unit.
+ Note that the actual memory usage may slightly exceed this value.
+ """
+
+ def __init__(
+ self,
+ tokenizer_info: TokenizerInfo,
+ *,
+ max_threads: int = 8,
+ cache_enabled: bool = True,
+ cache_limit_bytes: int = -1,
+ ):
+ if not isinstance(tokenizer_info, TokenizerInfo):
+ raise ValueError(
+ "Please convert the tokenizer to TokenizerInfo before passing it "
+ "to GrammarCompiler."
+ )
+
+ self._init_handle(
+ _core.GrammarCompiler(
+ tokenizer_info._handle, max_threads, cache_enabled, cache_limit_bytes
+ )
+ )
+
+ def compile_json_schema(
+ self,
+ schema: Union[str, Type[BaseModel], Dict[str, Any]],
+ *,
+ any_whitespace: bool = True,
+ indent: Optional[int] = None,
+ separators: Optional[Tuple[str, str]] = None,
+ strict_mode: bool = True,
+ ) -> CompiledGrammar:
+ """Get CompiledGrammar from the specified JSON schema and format. The indent
+ and separators parameters follow the same convention as in json.dumps().
+
+ Parameters
+ ----------
+ schema : Union[str, Type[BaseModel], Dict[str, Any]]
+ The schema string or Pydantic model or JSON schema dict.
+
+ indent : Optional[int], default: None
+ The number of spaces for indentation. If None, the output will be in one line.
+
+ separators : Optional[Tuple[str, str]], default: None
+ Two separators used in the schema: comma and colon. Examples: (",", ":"), (", ", ": ").
+ If None, the default separators will be used: (",", ": ") when the indent is not None,
+ and (", ", ": ") otherwise.
+
+ strict_mode : bool, default: True
+ Whether to use strict mode. In strict mode, the generated grammar will not allow
+ properties and items that is not specified in the schema. This is equivalent to
+ setting unevaluatedProperties and unevaluatedItems to false.
+
+ This helps LLM to generate accurate output in the grammar-guided generation with JSON
+ schema.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ schema_str = _convert_schema_to_str(schema)
+ return CompiledGrammar._create_from_handle(
+ self._handle.compile_json_schema(
+ schema_str, any_whitespace, indent, separators, strict_mode
+ )
+ )
+
+ def compile_builtin_json_grammar(self) -> CompiledGrammar:
+ """Get CompiledGrammar from the standard JSON.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ return CompiledGrammar._create_from_handle(self._handle.compile_builtin_json_grammar())
+
+ def compile_regex(self, regex: str) -> CompiledGrammar:
+ """Get CompiledGrammar from the specified regex.
+
+ Parameters
+ ----------
+ regex : str
+ The regex string.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ return CompiledGrammar._create_from_handle(self._handle.compile_regex(regex))
+
+ def compile_structural_tag(
+ self, tags: List[StructuralTagItem], triggers: List[str]
+ ) -> CompiledGrammar:
+ """Compile a grammar from structural tags. See Grammar.from_structural_tag() for more
+ details.
+
+ Parameters
+ ----------
+ tags : List[StructuralTagItem]
+ The structural tags.
+
+ triggers : List[str]
+ The triggers.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ tags_tuple = [(tag.begin, _convert_schema_to_str(tag.schema_), tag.end) for tag in tags]
+ return CompiledGrammar._create_from_handle(
+ self._handle.compile_structural_tag(tags_tuple, triggers)
+ )
+
+ @overload
+ def compile_grammar(self, ebnf_string: str, *, root_rule_name: str = "root") -> CompiledGrammar:
+ """Compile a grammar from EBNF string. The EBNF string should follow the format
+ in https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md.
+
+ Parameters
+ ----------
+ ebnf_string : str
+ The grammar string in EBNF format.
+
+ root_rule_name : str, default: "root"
+ The name of the root rule in the grammar.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ ...
+
+ @overload
+ def compile_grammar(self, grammar: Grammar) -> CompiledGrammar:
+ """Compile a grammar object.
+
+ Returns
+ -------
+ compiled_grammar : CompiledGrammar
+ The compiled grammar.
+ """
+ ...
+
+ def compile_grammar(
+ self, grammar: Union[str, Grammar], *, root_rule_name: str = "root"
+ ) -> CompiledGrammar:
+ if isinstance(grammar, str):
+ grammar = Grammar.from_ebnf(grammar, root_rule_name=root_rule_name)
+ return CompiledGrammar._create_from_handle(self._handle.compile_grammar(grammar._handle))
+
+ def clear_cache(self) -> None:
+ """Clear all cached compiled grammars."""
+ self._handle.clear_cache()
+
+ def get_cache_size_bytes(self) -> int:
+ """The approximate memory usage of the cache in bytes."""
+ return self._handle.get_cache_size_bytes()
+
+ @property
+ def cache_limit_bytes(self) -> int:
+ """
+ The maximum memory usage for the cache in bytes.
+ Returns -1 if the cache has no memory limit.
+ """
+ return self._handle.cache_limit_bytes
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/__init__.py b/venv/lib/python3.10/site-packages/xgrammar/contrib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e65fbd210f39cba3cf31abbe78475dbba3b9fe4
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/hf.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/hf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e16c5641e417a2af09f044b7f3ca5848ec1df01
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/hf.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/mlxlm.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/mlxlm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64e25ab0a52621ce7978c7e36039ba9d96d849dc
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/contrib/__pycache__/mlxlm.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/hf.py b/venv/lib/python3.10/site-packages/xgrammar/contrib/hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..380469bc8fe3f5d13f675dff47858cb7698f58ea
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/contrib/hf.py
@@ -0,0 +1,114 @@
+"""
+This file helps integrate xgrammar in HF transformers package by extending
+transformers.LogitsProcessor, which is to be fed to `model.generate()`.
+"""
+
+from typing import List, Union
+
+import torch
+import transformers
+
+import xgrammar as xgr
+
+
+class LogitsProcessor(transformers.LogitsProcessor):
+ """
+ LogitsProcessor for processing logits in transformers' generate() method.
+
+ Example usage
+ -------------
+ .. code:: python
+
+ model_name = "Qwen/Qwen2.5-0.5B-Instruct"
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ config = AutoConfig.from_pretrained(model_name)
+ # This can be larger than tokenizer.vocab_size due to paddings
+ full_vocab_size = config.vocab_size
+ tokenizer_info = xgr.TokenizerInfo.from_huggingface(tokenizer, vocab_size=full_vocab_size)
+
+ grammar_compiler = xgr.GrammarCompiler(tokenizer_info)
+ compiled_grammar = grammar_compiler.compile_builtin_json_grammar()
+ xgr_logits_processor = xgr.contrib.hf.LogitsProcessor(compiled_grammar)
+ model.generate(prompt, logits_processor=[xgr_logits_processor])
+
+ For an end-to-end example, see folder `examples/hf_transformers/`.
+
+ Notes
+ -----
+ - Note that this LogitsProcessor can only be used once. For each `generate()` call,
+ instantiate a new one.
+ - Note that this implementation may contain extra overhead.
+ """
+
+ def __init__(self, compiled_grammar: Union[xgr.CompiledGrammar, List[xgr.CompiledGrammar]]):
+ """Initialize the LogitsProcessor.
+
+ Parameters
+ ----------
+ compiled_grammar : xgr.CompiledGrammar | List[xgr.CompiledGrammar]
+ One or more grammars compiled according to the given grammar and the model's tokenizer_info.
+ """
+ self.matchers: List[xgr.GrammarMatcher] = []
+ self.compiled_grammars: List[xgr.CompiledGrammar] = (
+ compiled_grammar if isinstance(compiled_grammar, list) else [compiled_grammar]
+ )
+ self.full_vocab_size = self.compiled_grammars[0].tokenizer_info.vocab_size
+ self.token_bitmask = None
+ self.prefilled = False
+ self.batch_size = 0
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ """
+ Accept token sampled in the last iteration, fill in bitmask, and apply bitmask to logits.
+
+ Returns:
+ scores: Logits modified with bitmask.
+ """
+ # Lazily initialize GrammarMatchers and bitmask
+ if len(self.matchers) == 0:
+ self.batch_size = input_ids.shape[0]
+ self.compiled_grammars = (
+ self.compiled_grammars
+ if len(self.compiled_grammars) > 1
+ else self.compiled_grammars * self.batch_size
+ )
+ assert (
+ len(self.compiled_grammars) == self.batch_size
+ ), "The number of compiled grammars must be equal to the batch size."
+ self.matchers = [
+ xgr.GrammarMatcher(self.compiled_grammars[i]) for i in range(self.batch_size)
+ ]
+ self.token_bitmask = xgr.allocate_token_bitmask(self.batch_size, self.full_vocab_size)
+
+ if input_ids.shape[0] != self.batch_size:
+ raise RuntimeError(
+ "Expect input_ids.shape[0] to be LogitsProcessor.batch_size."
+ + f"Got {input_ids.shape[0]} for the former, and {self.batch_size} for the latter."
+ )
+
+ if not self.prefilled:
+ # Have not sampled a token yet
+ self.prefilled = True
+ else:
+ for i in range(self.batch_size):
+ if not self.matchers[i].is_terminated():
+ sampled_token = input_ids[i][-1]
+ assert self.matchers[i].accept_token(sampled_token)
+
+ for i in range(self.batch_size):
+ if not self.matchers[i].is_terminated():
+ self.matchers[i].fill_next_token_bitmask(self.token_bitmask, i)
+
+ # We only support masking logits on CUDA or CPU
+ device_type = scores.device.type
+ if device_type != "cuda":
+ scores = scores.to("cpu")
+ xgr.apply_token_bitmask_inplace(scores, self.token_bitmask.to(scores.device))
+ if device_type != "cuda":
+ scores = scores.to(device_type)
+
+ # NOTE: Cannot reset here because __call__ is not invoked when stop token
+ # is sampled. This is why each `generate()` call needs to instantiate an
+ # LogitsProcessor
+
+ return scores
diff --git a/venv/lib/python3.10/site-packages/xgrammar/contrib/mlxlm.py b/venv/lib/python3.10/site-packages/xgrammar/contrib/mlxlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..84b05b0247438258f04f51d079545993dfda0677
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/contrib/mlxlm.py
@@ -0,0 +1,81 @@
+"""
+Usage:
+ python mlxlm.py --model mlx-community/Qwen2.5-Coder-32B-Instruct-3bit
+"""
+
+import argparse
+
+import mlx.core as mx
+from mlx_lm.generate import generate as mlx_generate
+from mlx_lm.utils import load as mlx_load
+from transformers import AutoTokenizer
+
+import xgrammar
+from xgrammar.kernels import apply_token_bitmask_inplace_kernels
+
+
+class XGrammarLogitsProcessor:
+ def __init__(self, grammar: xgrammar.CompiledGrammar, max_rollback_tokens: int = 16):
+ self.matcher = xgrammar.GrammarMatcher(grammar, max_rollback_tokens=max_rollback_tokens)
+ self.vocab_size = grammar.tokenizer_info.vocab_size
+ self.bitmask = xgrammar.allocate_token_bitmask(1, self.vocab_size)
+
+ def __call__(self, tokens: mx.array, logits: mx.array) -> mx.array:
+ assert tokens.size > 0 # In the first call, tokens.size == #tokens in prompt
+ last_token = tokens[-1].item()
+ acc = self.matcher.accept_token(last_token) if not self.matcher.is_terminated() else False
+ if not acc:
+ self.matcher.reset()
+ self.matcher.accept_token(last_token)
+ if not self.matcher.is_terminated():
+ self.matcher.fill_next_token_bitmask(self.bitmask)
+ return apply_token_bitmask_inplace_kernels["metal"](
+ mx.array(self.bitmask.numpy()), logits, self.vocab_size
+ )
+ return logits
+
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--model", type=str, required=True)
+ parser.add_argument(
+ "--prompt", type=str, default="Generate a simple example JSON. No text. Only the JSON"
+ )
+ parser.add_argument("--seed", type=int, default=42)
+ return parser.parse_args()
+
+
+def main():
+ args = parse_args()
+ model, _ = mlx_load(args.model)
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
+ mx.random.seed(args.seed)
+ with_logits_processor = mlx_generate(
+ model=model,
+ tokenizer=tokenizer,
+ prompt=tokenizer.apply_chat_template(
+ [{"role": "user", "content": args.prompt}], add_generation_prompt=True
+ ),
+ verbose=False,
+ logits_processors=[
+ XGrammarLogitsProcessor(
+ grammar=xgrammar.GrammarCompiler(
+ tokenizer_info=xgrammar.TokenizerInfo.from_huggingface(tokenizer)
+ ).compile_builtin_json_grammar()
+ )
+ ],
+ )
+ without_logits_processor = mlx_generate(
+ model=model,
+ tokenizer=tokenizer,
+ prompt=tokenizer.apply_chat_template(
+ [{"role": "user", "content": args.prompt}], add_generation_prompt=True
+ ),
+ verbose=False,
+ )
+ assert without_logits_processor == with_logits_processor
+ print(without_logits_processor)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/venv/lib/python3.10/site-packages/xgrammar/grammar.py b/venv/lib/python3.10/site-packages/xgrammar/grammar.py
new file mode 100644
index 0000000000000000000000000000000000000000..822bba9968bd3cd0367d390cb44ca348235e8e98
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/grammar.py
@@ -0,0 +1,321 @@
+"""This module provides classes representing grammars."""
+
+import json
+from typing import Any, Dict, List, Optional, Tuple, Type, Union
+
+from pydantic import BaseModel, Field
+
+from .base import XGRObject, _core
+
+
+class StructuralTagItem(BaseModel):
+ """A structural tag item. See Grammar.from_structural_tag() for more details.
+
+ Attributes
+ ----------
+ begin : str
+ The begin tag.
+
+ schema_ : Union[str, Type[BaseModel]]
+ The schema.
+
+ end : str
+ The end tag.
+ """
+
+ begin: str
+ schema_: Union[str, Type[BaseModel], Dict[str, Any]] = Field(alias="schema")
+ end: str
+
+
+def _convert_schema_to_str(schema: Union[str, Type[BaseModel], Dict[str, Any]]) -> str:
+ """Convert a schema to a string representation.
+
+ This function handles different schema input types and converts them to a JSON string:
+ - Pydantic models are converted using their schema methods
+ - String inputs are returned as-is (assumed to be valid JSON)
+ - Dictionary inputs are converted to JSON strings
+
+ Parameters
+ ----------
+ schema : Union[str, Type[BaseModel], Dict[str, Any]]
+ The schema to convert, which can be a Pydantic model class,
+ a JSON schema string, or a dictionary representing a JSON schema.
+
+ Returns
+ -------
+ str
+ The JSON schema as a string.
+
+ Raises
+ ------
+ ValueError, TypeError
+ If the schema type is not supported, or the dictionary is not serializable.
+ """
+ if isinstance(schema, type) and issubclass(schema, BaseModel):
+ if hasattr(schema, "model_json_schema"):
+ return json.dumps(schema.model_json_schema())
+ if hasattr(schema, "schema_json"):
+ return json.dumps(schema.schema_json())
+ else:
+ raise ValueError("The schema should have a model_json_schema or json_schema method.")
+ elif isinstance(schema, str):
+ return schema
+ elif isinstance(schema, dict):
+ return json.dumps(schema)
+ else:
+ raise ValueError("The schema should be a string or a Pydantic model.")
+
+
+class Grammar(XGRObject):
+ """This class represents a grammar object in XGrammar, and can be used later in the
+ grammar-guided generation.
+
+ The Grammar object supports context-free grammar (CFG). EBNF (extended Backus-Naur Form) is
+ used as the format of the grammar. There are many specifications for EBNF in the literature,
+ and we follow the specification of GBNF (GGML BNF) in
+ https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md.
+
+ When printed, the grammar will be converted to GBNF format.
+ """
+
+ def __str__(self) -> str:
+ """Print the BNF grammar to a string, in EBNF format.
+
+ Returns
+ -------
+ grammar_string : str
+ The BNF grammar string.
+ """
+ return self._handle.to_string()
+
+ @staticmethod
+ def from_ebnf(ebnf_string: str, *, root_rule_name: str = "root") -> "Grammar":
+ """Construct a grammar from EBNF string. The EBNF string should follow the format
+ in https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md.
+
+ Parameters
+ ----------
+ ebnf_string : str
+ The grammar string in EBNF format.
+
+ root_rule_name : str, default: "root"
+ The name of the root rule in the grammar.
+
+ Raises
+ ------
+ RuntimeError
+ When converting the regex pattern fails, with details about the parsing error.
+ """
+ return Grammar._create_from_handle(_core.Grammar.from_ebnf(ebnf_string, root_rule_name))
+
+ @staticmethod
+ def from_json_schema(
+ schema: Union[str, Type[BaseModel], Dict[str, Any]],
+ *,
+ any_whitespace: bool = True,
+ indent: Optional[int] = None,
+ separators: Optional[Tuple[str, str]] = None,
+ strict_mode: bool = True,
+ print_converted_ebnf: bool = False,
+ ) -> "Grammar":
+ """Construct a grammar from JSON schema. Pydantic model or JSON schema string can be
+ used to specify the schema.
+
+ It allows any whitespace by default. If user want to specify the format of the JSON,
+ set `any_whitespace` to False and use the `indent` and `separators` parameters. The
+ meaning and the default values of the parameters follows the convention in json.dumps().
+
+ It internally converts the JSON schema to a EBNF grammar.
+
+ Parameters
+ ----------
+ schema : Union[str, Type[BaseModel], Dict[str, Any]]
+ The schema string or Pydantic model or JSON schema dict.
+
+ any_whitespace : bool, default: True
+ Whether to use any whitespace. If True, the generated grammar will ignore the
+ indent and separators parameters, and allow any whitespace.
+
+ indent : Optional[int], default: None
+ The number of spaces for indentation. If None, the output will be in one line.
+
+ Note that specifying the indentation means forcing the LLM to generate JSON strings
+ strictly formatted. However, some models may tend to generate JSON strings that
+ are not strictly formatted. In this case, forcing the LLM to generate strictly
+ formatted JSON strings may degrade the generation quality. See
+ for more
+ details.
+
+ separators : Optional[Tuple[str, str]], default: None
+ Two separators used in the schema: comma and colon. Examples: (",", ":"), (", ", ": ").
+ If None, the default separators will be used: (",", ": ") when the indent is not None,
+ and (", ", ": ") otherwise.
+
+ strict_mode : bool, default: True
+ Whether to use strict mode. In strict mode, the generated grammar will not allow
+ properties and items that is not specified in the schema. This is equivalent to
+ setting unevaluatedProperties and unevaluatedItems to false.
+
+ This helps LLM to generate accurate output in the grammar-guided generation with JSON
+ schema.
+
+ print_converted_ebnf : bool, default: False
+ If True, the converted EBNF string will be printed. For debugging purposes.
+
+ Returns
+ -------
+ grammar : Grammar
+ The constructed grammar.
+
+ Raises
+ ------
+ RuntimeError
+ When converting the json schema fails, with details about the parsing error.
+ """
+ schema_str = _convert_schema_to_str(schema)
+ return Grammar._create_from_handle(
+ _core.Grammar.from_json_schema(
+ schema_str, any_whitespace, indent, separators, strict_mode, print_converted_ebnf
+ )
+ )
+
+ @staticmethod
+ def from_regex(regex_string: str, *, print_converted_ebnf: bool = False) -> "Grammar":
+ """Create a grammar from a regular expression string.
+
+ Parameters
+ ----------
+ regex_string : str
+ The regular expression pattern to create the grammar from.
+
+ print_converted_ebnf : bool, default: False
+ This method will convert the regex pattern to EBNF first. If this is true, the converted
+ EBNF string will be printed. For debugging purposes. Default: False.
+
+ Returns
+ -------
+ grammar : Grammar
+ The constructed grammar from the regex pattern.
+
+ Raises
+ ------
+ RuntimeError
+ When parsing the regex pattern fails, with details about the parsing error.
+ """
+ return Grammar._create_from_handle(
+ _core.Grammar.from_regex(regex_string, print_converted_ebnf)
+ )
+
+ @staticmethod
+ def from_structural_tag(tags: List[StructuralTagItem], triggers: List[str]) -> "Grammar":
+ """Create a grammar from structural tags. The structural tag handles the dispatching
+ of different grammars based on the tags and triggers: it initially allows any output,
+ until a trigger is encountered, then dispatch to the corresponding tag; when the end tag
+ is encountered, the grammar will allow any following output, until the next trigger is
+ encountered.
+
+ The tags parameter is used to specify the output pattern. It is especially useful for LLM
+ function calling, where the pattern is:
+ {"arg1": ..., "arg2": ...} .
+ This pattern consists of three parts: a begin tag (), a parameter list
+ according to some schema ({"arg1": ..., "arg2": ...}), and an end tag ( ). This
+ pattern can be described in a StructuralTagItem with a begin tag, a schema, and an end tag.
+ The structural tag is able to handle multiple such patterns by passing them into multiple
+ tags.
+
+ The triggers parameter is used to trigger the dispatching of different grammars. The trigger
+ should be a prefix of a provided begin tag. When the trigger is encountered, the
+ corresponding tag should be used to constrain the following output. There can be multiple
+ tags matching the same trigger. Then if the trigger is encountered, the following output
+ should match one of the tags. For example, in function calling, the triggers can be
+ ["{"city": "Beijing"} ).
+
+ The corrrespondence of tags and triggers is automatically determined: all tags with the
+ same trigger will be grouped together. User should make sure any trigger is not a prefix
+ of another trigger: then the corrrespondence of tags and triggers will be ambiguous.
+
+ To use this grammar in grammar-guided generation, the GrammarMatcher constructed from
+ structural tag will generate a mask for each token. When the trigger is not encountered,
+ the mask will likely be all-1 and not have to be used (fill_next_token_bitmask returns
+ False, meaning no token is masked). When a trigger is encountered, the mask should be
+ enforced (fill_next_token_bitmask will return True, meaning some token is masked) to the
+ output logits.
+
+ The benefit of this method is the token boundary between tags and triggers is automatically
+ handled. The user does not need to worry about the token boundary.
+
+ Parameters
+ ----------
+ tags : List[StructuralTagItem]
+ The structural tags.
+
+ triggers : List[str]
+ The triggers.
+
+ Examples
+ --------
+ >>> class Schema1(BaseModel):
+ >>> arg1: str
+ >>> arg2: int
+ >>> class Schema2(BaseModel):
+ >>> arg3: float
+ >>> arg4: List[str]
+ >>> tags = [
+ >>> StructuralTagItem(begin="", schema=Schema1, end=" "),
+ >>> StructuralTagItem(begin="", schema=Schema2, end=" "),
+ >>> ]
+ >>> triggers = [">> grammar = Grammar.from_structural_tag(tags, triggers)
+ """
+ tags_tuple = [(tag.begin, _convert_schema_to_str(tag.schema_), tag.end) for tag in tags]
+ return Grammar._create_from_handle(_core.Grammar.from_structural_tag(tags_tuple, triggers))
+
+ @staticmethod
+ def builtin_json_grammar() -> "Grammar":
+ """Get the grammar of standard JSON. This is compatible with the official JSON grammar
+ specification in https://www.json.org/json-en.html.
+
+ Returns
+ -------
+ grammar : Grammar
+ The JSON grammar.
+ """
+ return Grammar._create_from_handle(_core.Grammar.builtin_json_grammar())
+
+ @staticmethod
+ def concat(*grammars: "Grammar") -> "Grammar":
+ """Create a grammar that matches the concatenation of the grammars in the list. That is
+ equivalent to using the `+` operator to concatenate the grammars in the list.
+
+ Parameters
+ ----------
+ grammars : List[Grammar]
+ The grammars to create the concatenation of.
+
+ Returns
+ -------
+ grammar : Grammar
+ The concatenation of the grammars.
+ """
+ grammar_handles = [grammar._handle for grammar in grammars]
+ return Grammar._create_from_handle(_core.Grammar.concat(grammar_handles))
+
+ @staticmethod
+ def union(*grammars: "Grammar") -> "Grammar":
+ """Create a grammar that matches any of the grammars in the list. That is equivalent to
+ using the `|` operator to concatenate the grammars in the list.
+
+ Parameters
+ ----------
+ grammars : List[Grammar]
+ The grammars to create the union of.
+
+ Returns
+ -------
+ grammar : Grammar
+ The union of the grammars.
+ """
+ grammar_handles = [grammar._handle for grammar in grammars]
+ return Grammar._create_from_handle(_core.Grammar.union(grammar_handles))
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__init__.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..16c36cb1abc5bb1346c43933e8db9d24a063e4a6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/__init__.py
@@ -0,0 +1,8 @@
+"""The kernels for XGrammar. There are 5 implementations:
+
+- CPU: used for CPU tensors
+- CUDA: not used in the current implementation
+- Triton: used for CUDA GPU tensors
+- MLX: used for MLX tensors
+- Torch Compile: used for torch tensors on other devices
+"""
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b264e861983828746ab96fa27f9d06137c4664a2
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cpu.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cpu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b84076c27bb9c130c6a36a4a19f676b1648c4d17
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cpu.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cuda.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cuda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c93c59e7da73b47e62f5c4038624efafe6fc837
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_cuda.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_torch_compile.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_torch_compile.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7dd20f1997fbf2eb88bfbb94723a35533f25b99
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_torch_compile.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_triton.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_triton.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4f8dcc25086841b7928950c78f9d06c34c94098
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_inplace_triton.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_mlx.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_mlx.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45b03bbfd58d5cc5be940d63e9f1111926d7c953
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/kernels/__pycache__/apply_token_bitmask_mlx.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cpu.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..bce5eded5f380b345294186d2a93441c1c700f30
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cpu.py
@@ -0,0 +1,38 @@
+"""CPU implementation for in-place applying token mask."""
+
+from typing import List, Optional, Union
+
+import torch
+
+from ..base import _core
+
+
+def apply_token_bitmask_inplace_cpu(
+ logits: torch.Tensor,
+ bitmask: torch.Tensor,
+ vocab_size: Optional[int] = None,
+ indices: Optional[Union[List[int], torch.Tensor]] = None,
+) -> None:
+ """Apply token bitmask in-place on CPU."""
+ if logits.device.type != "cpu":
+ raise ValueError("logits must be on CPU")
+ if bitmask.device.type != "cpu":
+ raise ValueError("bitmask must be on CPU")
+ if logits.dtype != torch.float32:
+ raise ValueError("logits must be of type float32")
+ if bitmask.dtype != torch.int32:
+ raise ValueError("bitmask must be of type int32")
+ if logits.dim() != 1 and logits.dim() != 2:
+ raise ValueError("logits should be 1D or 2D, but got {}D".format(logits.dim()))
+ if bitmask.dim() != 1 and bitmask.dim() != 2:
+ raise ValueError("bitmask should be 1D or 2D, but got {}D".format(bitmask.dim()))
+
+ logits_shape = (1, logits.shape[0]) if logits.dim() == 1 else (logits.shape[0], logits.shape[1])
+ bitmask_shape = (
+ (1, bitmask.shape[0]) if bitmask.dim() == 1 else (bitmask.shape[0], bitmask.shape[1])
+ )
+ vocab_size = min(logits.shape[-1], bitmask.shape[-1] * 32) if vocab_size is None else vocab_size
+
+ _core.kernels.apply_token_bitmask_inplace_cpu(
+ logits.data_ptr(), logits_shape, bitmask.data_ptr(), bitmask_shape, vocab_size, indices
+ )
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.cu b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..3f58ab4362f72eae3f8ec0658d8f791c2699faf9
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.cu
@@ -0,0 +1,285 @@
+/*
+ * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// clang-format off
+#include
+#include
+#include
+#include
+#include
+// clang-format on
+
+#ifndef CUDART_INF_FP16
+#define CUDART_INF_FP16 __ushort_as_half((unsigned short)0x7C00U)
+#endif
+
+#ifndef CUDART_INF_BF16
+#define CUDART_INF_BF16 __ushort_as_bfloat16((unsigned short)0x7F80U)
+#endif
+
+constexpr int32_t BITS_PER_BLOCK = 32;
+constexpr int32_t THREADS_PER_THREAD_BLOCK = 256;
+
+template
+__device__ T NegativeInfinity() {
+ return -INFINITY;
+}
+
+template <>
+__device__ __half NegativeInfinity<__half>() {
+ return -CUDART_INF_FP16;
+}
+
+template <>
+__device__ __nv_bfloat16 NegativeInfinity<__nv_bfloat16>() {
+ return -CUDART_INF_BF16;
+}
+
+template
+__device__ PackedT PackedNegativeInfinity() {
+ constexpr int kAlignment = sizeof(PackedT) / sizeof(T);
+ T packed[kAlignment];
+#pragma unroll
+ for (int i = 0; i < kAlignment; i++) {
+ packed[i] = NegativeInfinity();
+ }
+ return *reinterpret_cast(packed);
+}
+
+template
+__global__ void __launch_bounds__(THREADS_PER_THREAD_BLOCK) LogitsBitmaskKernel(
+ T* __restrict__ logits,
+ const int32_t* __restrict__ bitmask,
+ const int32_t* __restrict__ indices,
+ int32_t vocab_size,
+ int32_t logits_stride,
+ int32_t bitmask_stride
+) {
+ constexpr int kAlignment = sizeof(PackedT) / sizeof(T);
+ constexpr uint32_t kPackedMask = (1 << kAlignment) - 1;
+
+ const int batch_idx = (indices == nullptr) ? blockIdx.y : indices[blockIdx.y];
+
+ const int block_offset = blockIdx.x * THREADS_PER_THREAD_BLOCK * kBitsPerThread;
+ T* logits_gmem_ptr = logits + batch_idx * logits_stride + block_offset;
+ const int32_t* bitmask_gmem_ptr =
+ bitmask + batch_idx * bitmask_stride + block_offset / BITS_PER_BLOCK;
+ const int bitmask_inner_idx = threadIdx.x % (BITS_PER_BLOCK / kAlignment);
+ T logits_reg[kAlignment];
+
+#pragma unroll
+ for (int offset = threadIdx.x * kAlignment; offset < THREADS_PER_THREAD_BLOCK * kBitsPerThread;
+ offset += THREADS_PER_THREAD_BLOCK * kAlignment) {
+ if (block_offset + offset >= vocab_size) {
+ break;
+ }
+
+ const uint32_t bitmask_val =
+ (~bitmask_gmem_ptr[offset / BITS_PER_BLOCK] >> (bitmask_inner_idx * kAlignment)) &
+ kPackedMask;
+
+ if (bitmask_val == 0) {
+ continue;
+ }
+
+ if (bitmask_val == kPackedMask) {
+ *reinterpret_cast(logits_gmem_ptr + offset) = PackedNegativeInfinity();
+ continue;
+ }
+
+ *reinterpret_cast(logits_reg) = *reinterpret_cast(logits_gmem_ptr + offset);
+#pragma unroll
+ for (int i = 0; i < kAlignment; i++) {
+ if (((bitmask_val >> i) & 1)) {
+ logits_reg[i] = NegativeInfinity();
+ }
+ }
+ *reinterpret_cast(logits_gmem_ptr + offset) = *reinterpret_cast(logits_reg);
+ }
+}
+
+template ::value>>
+constexpr auto CeilDiv(T numerator, T denominator) {
+ return (numerator + denominator - 1) / denominator;
+}
+
+template
+void ApplyTokenBitmaskInplaceDispatchToBitsPerThread(
+ T* __restrict__ logits,
+ const int32_t* __restrict__ bitmask,
+ const int32_t* __restrict__ indices,
+ int32_t vocab_size,
+ int32_t logits_stride,
+ int32_t bitmask_stride,
+ int32_t num_rows
+) {
+ constexpr int kAlignment = sizeof(PackedT) / sizeof(T);
+ const int32_t num_blocks_per_row = CeilDiv(2048 / THREADS_PER_THREAD_BLOCK * 128, num_rows);
+ const int32_t num_bits_per_thread =
+ CeilDiv(vocab_size, THREADS_PER_THREAD_BLOCK * num_blocks_per_row);
+
+ const dim3 block(THREADS_PER_THREAD_BLOCK);
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream();
+
+ if (num_bits_per_thread <= 4 && kAlignment <= 4) {
+ const dim3 grid(CeilDiv(vocab_size, THREADS_PER_THREAD_BLOCK * 4), num_rows);
+ LogitsBitmaskKernel<<>>(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride
+ );
+ } else if (num_bits_per_thread <= 8 && kAlignment <= 8) {
+ const dim3 grid(CeilDiv(vocab_size, THREADS_PER_THREAD_BLOCK * 8), num_rows);
+ LogitsBitmaskKernel<<>>(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride
+ );
+ } else if (num_bits_per_thread <= 16 && kAlignment <= 16) {
+ const dim3 grid(CeilDiv(vocab_size, THREADS_PER_THREAD_BLOCK * 16), num_rows);
+ LogitsBitmaskKernel<<>>(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride
+ );
+ } else {
+ const dim3 grid(CeilDiv(vocab_size, THREADS_PER_THREAD_BLOCK * 32), num_rows);
+ LogitsBitmaskKernel<<>>(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride
+ );
+ }
+}
+
+template
+void ApplyTokenBitmaskInplaceDispatchToPackedT(
+ T* __restrict__ logits,
+ const int32_t* __restrict__ bitmask,
+ const int32_t* __restrict__ indices,
+ int32_t vocab_size,
+ int32_t logits_stride,
+ int32_t bitmask_stride,
+ int32_t num_rows
+) {
+ if (logits_stride % (sizeof(float4) / sizeof(T)) == 0) {
+ ApplyTokenBitmaskInplaceDispatchToBitsPerThread(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride, num_rows
+ );
+ } else {
+ ApplyTokenBitmaskInplaceDispatchToBitsPerThread(
+ logits, bitmask, indices, vocab_size, logits_stride, bitmask_stride, num_rows
+ );
+ }
+}
+
+void ApplyTokenBitmaskInplace(
+ at::Tensor logits, at::Tensor bitmask, at::optional indices = at::nullopt
+) {
+ TORCH_CHECK(logits.is_cuda(), "logits must be a CUDA tensor.");
+ TORCH_CHECK(logits.is_contiguous(), "logits must be contiguous.");
+ TORCH_CHECK(logits.dim() == 1 || logits.dim() == 2, "logits must be a 1D or 2D tensor.");
+ std::pair logits_shape =
+ logits.dim() == 2
+ ? std::make_pair(
+ static_cast(logits.size(0)), static_cast(logits.size(1))
+ )
+ : std::make_pair(1, static_cast(logits.size(0)));
+
+ TORCH_CHECK(bitmask.is_cuda(), "bitmask must be a CUDA tensor.");
+ TORCH_CHECK(bitmask.is_contiguous(), "bitmask must be contiguous.");
+ TORCH_CHECK(bitmask.dim() == 1 || bitmask.dim() == 2, "bitmask must be a 1D or 2D tensor.");
+ std::pair bitmask_shape =
+ bitmask.dim() == 2
+ ? std::make_pair(
+ static_cast(bitmask.size(0)), static_cast(bitmask.size(1))
+ )
+ : std::make_pair(1, static_cast(bitmask.size(0)));
+
+ TORCH_CHECK(bitmask.dtype() == torch::kInt32, "bitmask must be of type int32.");
+
+ TORCH_CHECK(
+ (logits_shape.second + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK >= bitmask_shape.second,
+ "The provided logits's vocab size should be no less than the bitmask's vocab size "
+ "(converted from bitmask size). But got vocab size ",
+ logits_shape.second,
+ " vs bitmask size ",
+ bitmask_shape.second
+ );
+
+ int vocab_size = std::min(logits_shape.second, bitmask_shape.second * BITS_PER_BLOCK);
+
+ int32_t num_rows = logits_shape.first;
+ int32_t* indices_ptr = nullptr;
+ if (indices) {
+ TORCH_CHECK(indices->is_cuda(), "indices must be a CUDA tensor.");
+ TORCH_CHECK(indices->is_contiguous(), "indices must be contiguous.");
+ TORCH_CHECK(indices->dim() == 1, "indices must be a 1D tensor.");
+ TORCH_CHECK(indices->dtype() == torch::kInt32, "indices must be of type int32.");
+ num_rows = indices->size(0);
+ indices_ptr = indices->data_ptr();
+ } else {
+ TORCH_CHECK(
+ logits_shape.first == bitmask_shape.first,
+ "logits and bitmask must have the same batch size."
+ );
+ }
+
+ switch (logits.scalar_type()) {
+ case torch::kFloat32: {
+ ApplyTokenBitmaskInplaceDispatchToPackedT(
+ logits.data_ptr(),
+ bitmask.data_ptr(),
+ indices_ptr,
+ vocab_size,
+ logits_shape.second,
+ bitmask_shape.second,
+ num_rows
+ );
+ break;
+ }
+ case torch::kFloat16: {
+ ApplyTokenBitmaskInplaceDispatchToPackedT(
+ reinterpret_cast<__half*>(logits.data_ptr()),
+ bitmask.data_ptr(),
+ indices_ptr,
+ vocab_size,
+ logits_shape.second,
+ bitmask_shape.second,
+ num_rows
+ );
+ break;
+ }
+ case torch::kBFloat16: {
+ ApplyTokenBitmaskInplaceDispatchToPackedT(
+ reinterpret_cast<__nv_bfloat16*>(logits.data_ptr()),
+ bitmask.data_ptr(),
+ indices_ptr,
+ vocab_size,
+ logits_shape.second,
+ bitmask_shape.second,
+ num_rows
+ );
+ break;
+ }
+ default:
+ TORCH_CHECK(false, "logits dtype must be float, half or bfloat16.");
+ break;
+ }
+}
+
+TORCH_LIBRARY_FRAGMENT(TORCH_EXTENSION_NAME, m) {
+ m.def(
+ "apply_token_bitmask_inplace_cuda(Tensor logits, Tensor bitmask, Tensor? indices=None) -> ()"
+ );
+}
+
+TORCH_LIBRARY_IMPL(TORCH_EXTENSION_NAME, CUDA, m) {
+ m.impl("apply_token_bitmask_inplace_cuda", &ApplyTokenBitmaskInplace);
+}
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.py
new file mode 100644
index 0000000000000000000000000000000000000000..2635c64b717aea5a630a0c1747540b62d53186b6
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_cuda.py
@@ -0,0 +1,116 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from contextlib import suppress
+from typing import List, Optional, Union
+
+import torch
+import torch.utils.cpp_extension
+
+
+def _check_cuda_toolchain() -> None:
+ """check if nvcc is available and if pytorch will likely find it"""
+ import glob
+ import os
+ import shutil
+ from pathlib import Path
+
+ # First check if CUDA is available in PyTorch
+ if not torch.cuda.is_available():
+ raise ImportError("CUDA is not available in PyTorch")
+
+ # This is similar logic to what pytorch does to find the nvcc compiler
+ nvcc_path = shutil.which("nvcc")
+ if nvcc_path is None:
+ cuda_home = os.environ.get("CUDA_HOME", os.environ.get("CUDA_PATH", None))
+ if cuda_home is None:
+ if os.name == "nt":
+ # This is a very hardcoded asumption about install directories but pytorch does this.
+ cuda_homes = glob.glob("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*")
+
+ if len(cuda_homes) == 0:
+ cuda_home = ""
+ else:
+ cuda_home = cuda_homes[0]
+ else:
+ cuda_home = "/usr/local/cuda"
+
+ if cuda_home is None:
+ raise ImportError("No CUDA toolchain found")
+
+ nvcc_path = str(Path(cuda_home) / "bin" / "nvcc")
+
+ if not os.path.exists(nvcc_path):
+ raise ImportError(f"nvcc compiler not found at {nvcc_path}")
+
+
+def _remove_torch_nvcc_flags() -> None:
+ REMOVE_NVCC_FLAGS = [
+ "-D__CUDA_NO_HALF_OPERATORS__",
+ "-D__CUDA_NO_HALF_CONVERSIONS__",
+ "-D__CUDA_NO_BFLOAT16_CONVERSIONS__",
+ "-D__CUDA_NO_HALF2_OPERATORS__",
+ ]
+ for flag in REMOVE_NVCC_FLAGS:
+ with suppress(ValueError):
+ torch.utils.cpp_extension.COMMON_NVCC_FLAGS.remove(flag)
+
+
+def _load_torch_ops() -> None:
+ from pathlib import Path
+
+ torch_op_file_path = Path(__file__).with_suffix(".cu")
+ with open(torch_op_file_path) as f:
+ source = f.read()
+ cflags = ["-O3", "-Wno-switch-bool"]
+ cuda_cflags = ["-O3", "-std=c++17", "--threads", "4", "-use_fast_math"]
+ # Use the safer cpp_extension.load_inline instead of cpp_extension.load
+ torch.utils.cpp_extension.load_inline(
+ name="xgrammar",
+ cpp_sources=[], # No C++ sources
+ cuda_sources=[source],
+ extra_cflags=cflags,
+ extra_cuda_cflags=cuda_cflags,
+ with_cuda=True,
+ is_python_module=False,
+ )
+
+
+_check_cuda_toolchain()
+_remove_torch_nvcc_flags()
+_load_torch_ops()
+
+
+_is_register_fake_available = hasattr(torch, "library") and hasattr(torch.library, "register_fake")
+
+if _is_register_fake_available:
+ # To support torch.compile with fullgraph=True, a fake kernel is needed.
+ @torch.library.register_fake("xgrammar::apply_token_bitmask_inplace_cuda")
+ def _(
+ logits: torch.Tensor, bitmask: torch.Tensor, indices: Optional[torch.Tensor] = None
+ ) -> None:
+ pass
+
+
+def apply_token_bitmask_inplace_cuda(
+ logits: torch.Tensor,
+ bitmask: torch.Tensor,
+ indices: Optional[Union[List[int], torch.Tensor]] = None,
+) -> None:
+ if isinstance(indices, list):
+ indices = torch.tensor(indices, dtype=torch.int32, device=logits.device)
+ if indices is not None:
+ indices = indices.to(logits.device)
+ torch.ops.xgrammar.apply_token_bitmask_inplace_cuda(logits, bitmask, indices)
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_torch_compile.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_torch_compile.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e34f789cc04914467d1d3b3edd730731980db3a
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_torch_compile.py
@@ -0,0 +1,55 @@
+from typing import List, Optional
+
+import torch
+
+
+@torch.compile(dynamic=True)
+def apply_token_bitmask_inplace_kernel_no_indices_torch_compile(
+ logits: torch.Tensor, bitmask: torch.Tensor, vocab_size: int
+) -> None:
+ # logits: (batch_size, vocab_size)
+ # bitmask: (batch_size, bitmask_size)
+ # mask_expanded: (batch_size, 32 * bitmask_size)
+ mask_expanded = torch.repeat_interleave(bitmask, 32, dim=-1)
+ # bit_indices: (32 * bitmask_size,)
+ bit_indices = torch.arange(32, device=logits.device, dtype=torch.int32).repeat(
+ bitmask.shape[-1]
+ )
+ # bit_masks: (batch_size, 32 * bitmask_size)
+ bit_masks = (mask_expanded >> bit_indices) & 1
+ bit_masks = bit_masks[..., :vocab_size]
+ logits[..., :vocab_size] = logits[..., :vocab_size].masked_fill_(bit_masks == 0, float("-inf"))
+
+
+@torch.compile(dynamic=True)
+def apply_token_bitmask_inplace_kernel_indices_torch_compile(
+ logits: torch.Tensor, bitmask: torch.Tensor, vocab_size: int, indices: List[int]
+) -> None:
+ # logits: (batch_size, vocab_size)
+ # bitmask: (batch_size, bitmask_size)
+ # mask_expanded: (batch_size, 32 * bitmask_size)
+ mask_expanded = torch.repeat_interleave(bitmask[indices], 32, dim=-1)
+ # bit_indices: (32 * bitmask_size,)
+ bit_indices = torch.arange(32, device=logits.device, dtype=torch.int32).repeat(
+ bitmask.shape[-1]
+ )
+ bit_masks = (mask_expanded >> bit_indices) & 1
+ bit_masks = bit_masks[..., :vocab_size]
+ logits[indices, :vocab_size] = logits[indices, :vocab_size].masked_fill_(
+ bit_masks == 0, float("-inf")
+ )
+
+
+def apply_token_bitmask_inplace_torch_compile(
+ logits: torch.Tensor,
+ bitmask: torch.Tensor,
+ vocab_size: Optional[int] = None,
+ indices: Optional[List[int]] = None,
+) -> None:
+ vocab_size = min(logits.shape[-1], bitmask.shape[-1] * 32) if vocab_size is None else vocab_size
+ if indices is None:
+ apply_token_bitmask_inplace_kernel_no_indices_torch_compile(logits, bitmask, vocab_size)
+ else:
+ apply_token_bitmask_inplace_kernel_indices_torch_compile(
+ logits, bitmask, vocab_size, indices
+ )
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_triton.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_triton.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8cdfcaf95447ad62f39925d48614c1686995c8e
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_inplace_triton.py
@@ -0,0 +1,118 @@
+from typing import List, Optional
+
+import torch
+
+try:
+ import triton
+ import triton.language as tl
+except ImportError as err:
+ raise ImportError("Triton is not installed") from err
+
+
+@triton.jit
+def apply_token_bitmask_inplace_kernel(
+ logits_ptr,
+ bitmask_ptr,
+ indices_ptr,
+ num_rows,
+ vocab_size,
+ logits_strides,
+ bitmask_strides,
+ NUM_SMS: tl.constexpr,
+ BLOCK_SIZE: tl.constexpr,
+):
+ """Apply a bitmask to logits in-place using Triton. The bitmask is a 01 bitwise compressed tensor,
+ where 0 means the token is masked and 1 means the token is not masked. After applying the bitmask,
+ the masked logits will be set to -inf.
+
+ Parameters
+ ----------
+ logits_ptr : tl.tensor
+ Pointer to the logits tensor to apply the bitmask to.
+
+ bitmask_ptr : tl.tensor
+ Pointer to the bitmask tensor to apply.
+
+ indices_ptr : Optional[tl.tensor]
+ Optional pointer to indices tensor specifying which rows to apply the mask to.
+
+ num_rows : int
+ Number of rows to process. If indices_ptr is provided, this is the number of unique indices.
+
+ vocab_size : int
+ Size of the vocabulary dimension. If the logits does not have a vocab padding, this is the
+ same as the logits's second dimension. Otherwise, this is the actual size of the vocabulary.
+
+ logits_strides : int
+ Stride between rows in the logits tensor.
+
+ bitmask_strides : int
+ Stride between rows in the bitmask tensor.
+
+ NUM_SMS : int
+ Number of streaming multiprocessors to use.
+
+ BLOCK_SIZE : int
+ Size of processing blocks.
+ """
+
+ pid = tl.program_id(0)
+ num_blocks = tl.cdiv(vocab_size, BLOCK_SIZE)
+ for work_id in tl.range(pid, num_rows * num_blocks, NUM_SMS):
+ row_id = work_id // num_blocks
+ block_offset = (work_id % num_blocks) * BLOCK_SIZE
+ batch_id = row_id if indices_ptr is None else tl.load(indices_ptr + row_id)
+ offsets = block_offset + tl.arange(0, BLOCK_SIZE)
+ bitmask_offsets = block_offset // 32 + tl.arange(0, BLOCK_SIZE // 32)
+ vocab_mask = offsets < vocab_size
+ packed_bitmask_mask = bitmask_offsets < bitmask_strides
+ packed_bitmask = tl.load(
+ bitmask_ptr + batch_id * bitmask_strides + bitmask_offsets, packed_bitmask_mask
+ )
+ bitmask = ((packed_bitmask[:, None] >> (tl.arange(0, 32)[None, :])) & 1) == 0
+ bitmask = bitmask.reshape(BLOCK_SIZE)
+
+ tl.store(
+ logits_ptr + batch_id * logits_strides + offsets, -float("inf"), vocab_mask & bitmask
+ )
+
+
+def apply_token_bitmask_inplace_triton(
+ logits: torch.Tensor,
+ bitmask: torch.Tensor,
+ vocab_size: Optional[int] = None,
+ indices: Optional[List[int]] = None,
+):
+ NUM_SMS = torch.cuda.get_device_properties("cuda").multi_processor_count
+ BLOCK_SIZE = 4096
+
+ assert bitmask.dtype == torch.int32, "bitmask must be of type int32"
+
+ detected_vocab_size = min(logits.shape[-1], bitmask.shape[-1] * 32)
+ if vocab_size is None:
+ vocab_size = detected_vocab_size
+ else:
+ assert (
+ vocab_size <= detected_vocab_size
+ ), f"vocab_size {vocab_size} is larger than the detected vocab_size {detected_vocab_size}"
+
+ num_rows = len(indices) if indices is not None else logits.shape[0] if logits.ndim == 2 else 1
+
+ if indices is not None:
+ indices = torch.tensor(indices, dtype=torch.int32, device=logits.device)
+
+ grid = (NUM_SMS,)
+
+ apply_token_bitmask_inplace_kernel[grid](
+ logits,
+ bitmask,
+ indices,
+ num_rows,
+ vocab_size,
+ logits.shape[-1],
+ bitmask.shape[-1],
+ NUM_SMS,
+ BLOCK_SIZE,
+ num_warps=BLOCK_SIZE // 32 // (16 // logits.element_size()),
+ num_stages=3,
+ )
diff --git a/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_mlx.py b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_mlx.py
new file mode 100644
index 0000000000000000000000000000000000000000..8033e33849db60991e2848084a702400a0c2c834
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/kernels/apply_token_bitmask_mlx.py
@@ -0,0 +1,25 @@
+"""MLX kernel for applying token bitmasks."""
+
+import itertools
+
+import mlx.core as mx
+
+
+@mx.compile
+def apply_token_bitmask_mlx(bitmask: mx.array, logits: mx.array, vocab_size: int):
+ """Apply a token bitmask to logits using MLX for Metal GPUs.
+
+ Args:
+ bitmask: A tensor of shape (batch_size, (vocab_size + 31) // 32) containing
+ the bitmask. Each bit in the bitmask determines whether the corresponding
+ token is allowed (1) or not (0).
+ logits: A tensor of shape (batch_size, vocab_size) containing the logits.
+
+ Returns:
+ The logits with -inf for tokens that are not allowed.
+ """
+ bitmap = mx.array(
+ [l[::-1] for l in itertools.product(*[[float("-inf"), 0]] * 8)], dtype=logits.dtype
+ )
+ bitmask = bitmask.view(mx.uint8)
+ return logits[..., :vocab_size] + bitmap[bitmask].flatten(-2)[..., :vocab_size]
diff --git a/venv/lib/python3.10/site-packages/xgrammar/matcher.py b/venv/lib/python3.10/site-packages/xgrammar/matcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d0e260118c688b299e4772b289aef31894dab34
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/matcher.py
@@ -0,0 +1,348 @@
+"""Match the output of the LLM to the specified grammar, then generate the mask for the next
+token.
+"""
+
+import math
+from typing import List, Optional, Tuple, Union
+
+import torch
+
+from .base import XGRObject, _core
+from .compiler import CompiledGrammar
+
+"""The dtype of the bitmask: int32."""
+bitmask_dtype = torch.int32
+
+
+def get_bitmask_shape(batch_size: int, vocab_size: int) -> Tuple[int, int]:
+ """Return the shape of the bitmask: (batch_size, ceil(vocab_size / 32))."""
+ return (batch_size, math.ceil(vocab_size / 32))
+
+
+_FULL_MASK = torch.tensor(-1, dtype=bitmask_dtype)
+
+
+def allocate_token_bitmask(batch_size: int, vocab_size: int) -> torch.Tensor:
+ """Allocate the bitmask for the next token prediction. The bitmask is an int32 tensor on
+ CPU with shape (batch_size, ceil(vocab_size / 32)). Users who have their own needs to
+ manage CUDA memory can construct the tensor with get_bitmask_shape and bitmask_dtype
+ themselves.
+
+ The reason why we use int32 instead of uint32 is that old versions of PyTorch do not support
+ uint32.
+
+ Parameters
+ ----------
+ batch_size : int
+ The batch size of the bitmask.
+
+ vocab_size : int
+ The size of the vocabulary.
+
+ Returns
+ -------
+ bitmask : torch.Tensor
+ The shape of the bitmask.
+ """
+ # In CUDA, use pinned memory to speed up data transfer from CPU to GPU
+ return torch.full(get_bitmask_shape(batch_size, vocab_size), _FULL_MASK, dtype=bitmask_dtype)
+
+
+def reset_token_bitmask(bitmask: torch.Tensor) -> None:
+ """Reset the bitmask to the full mask."""
+ bitmask.fill_(_FULL_MASK)
+
+
+def apply_token_bitmask_inplace(
+ logits: torch.Tensor,
+ bitmask: torch.Tensor,
+ *,
+ vocab_size: Optional[int] = None,
+ indices: Optional[List[int]] = None,
+) -> None:
+ """Apply the bitmask to the logits in-place. The bitmask is a 01 bitwise compressed tensor,
+ where 0 means the token is masked and 1 means the token is not masked. It can be generated by
+ allocate_token_bitmask and filled by fill_next_token_bitmask. After applying the bitmask, the
+ masked logits will be set to -inf.
+
+ The shape of logits and bitmask should be (batch_size, vocab_size) and
+ (batch_size, bitmask_size) respectively. bitmask_size = ceil(vocab_size / 32). The operation is:
+
+ .. code:: python
+
+ for i in range(batch_size):
+ for j in range(vocab_size):
+ if get_bitmask_value(bitmask, i, j) == 0:
+ logits[i, j] = -inf
+
+ get_bitmask_value(bitmask, i, j) gets the j-th bit of the i-th row of the bitmask.
+
+ ## Padding
+
+ This method allows additional padding on the vocabulary dimension of logits or bitmask. If
+ padding exists, provide the real vocab size to the vocab_size parameter, and the operation
+ will be applied to logits[..., :vocab_size] and bitmask[..., :ceil(vocab_size / 32)].
+
+ If vocab_size is not provided, the vocab size will be detected as min(logits.shape[-1],
+ bitmask.shape[-1] * 32).
+
+ ## Indices
+
+ Indices can be used to specify which logits in the batch to apply the bitmask to. It is
+ especially useful when there are structured requests and unstructured requests mixed in the
+ same batch by skipping masking the logits in the unstructured requests. When specified, the
+ operation will be
+
+ .. code:: python
+
+ for batch_id in indices:
+ for j in range(vocab_size):
+ if get_bitmask_value(bitmask, batch_id, j) == 0:
+ logits[batch_id, j] = -inf
+
+ When indices is specified, the batch sizes of logits and bitmask do not need to be the same.
+ As long as the indices are valid, the operation will be performed.
+
+ ## Device
+
+ The logits and bitmask should be on the same device. If both them are on GPU, we launch a GPU
+ kernel to apply bitmask. If both them are on CPU, we use a CPU implementation. The GPU kernel
+ is optimized and should be preferred.
+
+ In practice, the bitmask is allocated on CPU, and the logits is usually on GPU, so users should
+ manually copy the bitmask to GPU before calling this function.
+
+ Parameters
+ ----------
+ logits : torch.Tensor
+ The tensor to apply the bitmask to.
+
+ bitmask : torch.Tensor
+ The bitmask to apply.
+
+ vocab_size : Optional[int], default: None
+ The size of the vocabulary. If not provided, the vocab size will be detected as
+ min(logits.shape[-1], bitmask.shape[-1] * 32).
+
+ indices : Optional[List[int]], default: None
+ A list of indices to specify which logits in the batch to apply the bitmask to. Should be
+ unique. If None, apply the bitmask to all logits in the batch.
+ """
+ if bitmask.device != logits.device:
+ raise ValueError(
+ "logits and bitmask should be on the same device. "
+ + f"But got logits.device: {logits.device}, bitmask.device: {bitmask.device}"
+ )
+
+ # dispatch to different implementations based on the device
+ if logits.device.type == "cpu":
+ from .kernels.apply_token_bitmask_inplace_cpu import apply_token_bitmask_inplace_cpu
+
+ apply_token_bitmask_inplace_cpu(logits, bitmask, vocab_size, indices)
+
+ elif logits.device.type == "cuda":
+ from .kernels.apply_token_bitmask_inplace_triton import apply_token_bitmask_inplace_triton
+
+ apply_token_bitmask_inplace_triton(logits, bitmask, vocab_size, indices)
+ else:
+ from .kernels.apply_token_bitmask_inplace_torch_compile import (
+ apply_token_bitmask_inplace_torch_compile,
+ )
+
+ apply_token_bitmask_inplace_torch_compile(logits, bitmask, vocab_size, indices)
+
+
+class GrammarMatcher(XGRObject):
+ """Match the output of the LLM to the specified grammar, then generate the mask for the next
+ token. This is the core class in the grammar-guided generation.
+
+ This class maintains a stateful matcher that can accept tokens and strings, then match them
+ to the specified grammar. The matcher can provide a bitmask for the next token prediction,
+ so that the output of the LLM follows the specified grammar. Its state can be reset and
+ rolled back by tokens. It also provides utilities for jump-forward decoding.
+
+ After matching the whole grammar, the matcher will accept a stop token. The token mask at
+ this time will only allow stop tokens. After accepting the stop token, the matcher will
+ terminate, then it cannot accept any new token or generate a new token mask, meaning the
+ generation is finished.
+
+ Under the hood, it utilizes a pushdown automaton with backtracking to match the grammar,
+ with optimizations specific to LLM token mask generation.
+
+ Parameters
+ ----------
+ compiled_grammar : CompiledGrammar
+ The initialization context for the grammar matcher.
+
+ override_stop_tokens : Optional[Union[int, List[int]]], default: None
+ If not None, the stop tokens to override the ones in the grammar.
+
+ terminate_without_stop_token : bool, default: False
+ Whether to terminate the matcher without accepting a stop token.
+
+ max_rollback_tokens : int, default: 0
+ The maximum number of rollback tokens allowed. The rollback operation is useful for
+ jump-forward decoding and speculative decoding.
+ """
+
+ def __init__(
+ self,
+ compiled_grammar: CompiledGrammar,
+ *,
+ override_stop_tokens: Optional[Union[int, List[int]]] = None,
+ terminate_without_stop_token: bool = False,
+ max_rollback_tokens: int = 0,
+ ) -> None:
+ if not isinstance(compiled_grammar, CompiledGrammar):
+ raise ValueError("The grammar should be compiled before passing it to GrammarMatcher.")
+
+ if isinstance(override_stop_tokens, int):
+ override_stop_tokens = [override_stop_tokens]
+
+ self._init_handle(
+ _core.GrammarMatcher(
+ compiled_grammar._handle,
+ override_stop_tokens,
+ terminate_without_stop_token,
+ max_rollback_tokens,
+ )
+ )
+
+ def accept_token(self, token_id: int, *, debug_print: bool = False) -> bool:
+ """Accept one token and update the state of the matcher.
+
+ Parameters
+ ----------
+ token_id : int
+ The id of the token to accept.
+
+ debug_print : bool, default: False
+ Whether to print information about the internal state of the matcher. Helpful
+ for debugging.
+
+ Returns
+ -------
+ accepted : bool
+ Whether the token is accepted.
+ """
+ return self._handle.accept_token(token_id, debug_print)
+
+ def fill_next_token_bitmask(
+ self, bitmask: torch.Tensor, index: int = 0, *, debug_print: bool = False
+ ) -> bool:
+ """Fill the bitmask for the next token prediction. The input bitmask can be generated
+ by allocate_token_bitmask, and must be on CPU. bitmask[index] will be filled with the
+ next token bitmask.
+
+ This method does not change the matcher state.
+
+ Parameters
+ ----------
+ bitmask : torch.Tensor
+ The bitmask for the next token prediction.
+
+ index : int, default: 0
+ The batch id of the bitmask.
+
+ debug_print : bool, default: False
+ Whether to print information about generated bitmask. Helpful for debugging.
+
+ Returns
+ -------
+ need_apply : bool
+ Whether the bitmask need to be applied (not all-true). An optimization: if False,
+ this means the bitmask is already all-true, so no need to apply it.
+ """
+ if bitmask.device.type != "cpu":
+ raise ValueError("bitmask should be on CPU.")
+ if bitmask.dtype != bitmask_dtype:
+ raise ValueError(f"bitmask should be of type {bitmask_dtype}.")
+ return self._handle.fill_next_token_bitmask(
+ bitmask.data_ptr(), list(bitmask.shape), index, debug_print
+ )
+
+ def find_jump_forward_string(self) -> str:
+ """Find the jump-forward string for jump-forward decoding. This is the longest string that
+ certainly conforms with the current grammar from the current matcher state. This string
+ can become the output of the LLM without requiring LLM decoding.
+
+ This method does not change the matcher state.
+
+ Returns
+ -------
+ jump_forward_string : str
+ The jump-forward string.
+ """
+ return self._handle.find_jump_forward_string()
+
+ def rollback(self, num_tokens: int = 1) -> None:
+ """Rollback the matcher to a previous state by several tokens.
+
+ Parameters
+ ----------
+ num_tokens : int, default: 1
+ The number of tokens to rollback. It cannot exceed the current number of steps, nor can
+ it exceed the specified maximum number of rollback tokens.
+ """
+ self._handle.rollback(num_tokens)
+
+ def is_terminated(self) -> bool:
+ """Check if the matcher has terminated. If terminate_without_stop_token is False, the
+ matcher will terminate if it has accepted the stop token. Otherwise, the matcher will
+ terminate after matching the whole grammar.
+
+ Returns
+ -------
+ terminated : bool
+ Whether the matcher has terminated.
+ """
+ return self._handle.is_terminated()
+
+ def reset(self) -> None:
+ """Reset the matcher to the initial state."""
+ return self._handle.reset()
+
+ @property
+ def max_rollback_tokens(self) -> int:
+ """Get the maximum number of rollback tokens allowed.
+
+ Returns
+ -------
+ max_rollback_tokens : int
+ The maximum number of rollback tokens.
+ """
+ return self._handle.max_rollback_tokens
+
+ @property
+ def stop_token_ids(self) -> List[int]:
+ """The ids of the stop tokens used in the matcher. If specified, the provided stop tokens
+ will be used. Otherwise, the stop tokens will be detected from the vocabulary.
+
+ Returns
+ -------
+ stop_token_ids : List[int]
+ The ids of the stop tokens.
+ """
+ return self._handle.stop_token_ids
+
+ def _debug_accept_string(
+ self, input_str: Union[str, bytes], *, debug_print: bool = False
+ ) -> bool:
+ """Accept a string and update the state of the matcher. The whole string is considered
+ as one step in rollback. It is only used to complement the functionality of accept_token.
+
+ Parameters
+ ----------
+ input_str : Union[str, bytes]
+ The string to be accepted.
+
+ debug_print : bool, default: False
+ Whether to print information about the internal state of the matcher. Helpful for
+ debugging.
+
+ Returns
+ -------
+ accepted : bool
+ Whether the string is accepted.
+ """
+ return self._handle._debug_accept_string(input_str, debug_print)
diff --git a/venv/lib/python3.10/site-packages/xgrammar/support/__init__.py b/venv/lib/python3.10/site-packages/xgrammar/support/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..635b7837dbe347f2f8a6a0b5ac07070c207caea8
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/__init__.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/logging.cpython-310.pyc b/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/logging.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8eeed46a3190d35899ea14aa2351f8e562a3d41
Binary files /dev/null and b/venv/lib/python3.10/site-packages/xgrammar/support/__pycache__/logging.cpython-310.pyc differ
diff --git a/venv/lib/python3.10/site-packages/xgrammar/support/logging.py b/venv/lib/python3.10/site-packages/xgrammar/support/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..7059b122c05f0dc1bc2d185cdc01eb2daebda744
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/support/logging.py
@@ -0,0 +1,21 @@
+"""
+Logging support for XGrammar. It derives from Python's logging module, and in the future,
+it can be easily replaced by other logging modules such as structlog.
+"""
+
+import logging
+
+
+def enable_logging():
+ """Enable XGrammar's default logging formpat"""
+ logging.basicConfig(
+ level=logging.INFO,
+ style="{",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ format="[{asctime}] {levelname} {filename}:{lineno}: {message}",
+ )
+
+
+def getLogger(name: str): # pylint: disable=invalid-name
+ """Get a logger according to the given name"""
+ return logging.getLogger(name)
diff --git a/venv/lib/python3.10/site-packages/xgrammar/testing.py b/venv/lib/python3.10/site-packages/xgrammar/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..7481b10fa5c15bc882dc9b400fb5ce16fe15f9fe
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/testing.py
@@ -0,0 +1,310 @@
+"""Testing utilities."""
+
+import time
+from typing import Any, Dict, List, Optional, Tuple, Type, Union
+
+import torch
+from pydantic import BaseModel
+
+from .base import _core
+from .compiler import CompiledGrammar, GrammarCompiler
+from .grammar import Grammar, _convert_schema_to_str
+from .matcher import GrammarMatcher, bitmask_dtype
+from .tokenizer_info import TokenizerInfo
+
+
+def _json_schema_to_ebnf(
+ schema: Union[str, Type[BaseModel], Dict[str, Any]],
+ *,
+ any_whitespace: bool = True,
+ indent: Optional[int] = None,
+ separators: Optional[Tuple[str, str]] = None,
+ strict_mode: bool = True,
+) -> str:
+ """Convert JSON schema string to BNF grammar string. For test purposes.
+
+ Parameters
+ ----------
+ schema : Union[str, Type[BaseModel], Dict[str, Any]]
+ The schema string or Pydantic model or JSON schema dict.
+
+ indent : Optional[int], default: None
+ The number of spaces for indentation. If None, the output will be in one line.
+
+ separators : Optional[Tuple[str, str]], default: None
+ Two separators used in the schema: comma and colon. Examples: (",", ":"), (", ", ": ").
+ If None, the default separators will be used: (",", ": ") when the indent is not None,
+ and (", ", ": ") otherwise.
+
+ strict_mode : bool, default: True
+ Whether to use strict mode. In strict mode, the generated grammar will not allow
+ properties and items that is not specified in the schema. This is equivalent to
+ setting unevaluatedProperties and unevaluatedItems to false.
+
+ This helps LLM to generate accurate output in the grammar-guided generation with JSON
+ schema.
+
+ Returns
+ -------
+ bnf_string : str
+ The BNF grammar string.
+ """
+ schema_str = _convert_schema_to_str(schema)
+ return _core.testing._json_schema_to_ebnf(
+ schema_str, any_whitespace, indent, separators, strict_mode
+ )
+
+
+def _regex_to_ebnf(regex: str, with_rule_name: bool = True) -> str:
+ r"""Convert a regex string to BNF grammar string. For test purposes. The regex grammar
+ follows the syntax in JavaScript (ECMA 262). Check
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions
+ for a tutorial. Currently the following features are not supported:
+ 1. Backreference (\1)
+ 2. non-capturing group, naming capture groups and assertions ((?...))
+ 3. Unicode character class escape (\p{...})
+ 4. Word boundary (\b)
+ 5. Unicode property escapes (\p{...})
+ 6. Quantifier with range {x,y}. Now user can just repeat the element as a workaround.
+
+ This method is primarily intended for testing and debugging purposes.
+
+ Parameters
+ ----------
+ regex : str
+ The regex string to be converted.
+
+ Returns
+ -------
+ bnf_string : str
+ The BNF grammar string converted from the input regex.
+ """
+ return _core.testing._regex_to_ebnf(regex, with_rule_name)
+
+
+def _ebnf_to_grammar_no_normalization(ebnf_string: str, root_rule_name: str = "root") -> Grammar:
+ """Convert a BNF grammar string to a Grammar object without normalization. For test
+ purposes. The result grammar cannot be compiled / used in GrammarMatcher.
+
+ Parameters
+ ----------
+ ebnf_string : str
+ The BNF grammar string to be converted.
+
+ Returns
+ -------
+ grammar : Grammar
+ The unnormalized Grammar object converted from the input BNF grammar string.
+ """
+ return Grammar._create_from_handle(
+ _core.testing._ebnf_to_grammar_no_normalization(ebnf_string, root_rule_name)
+ )
+
+
+def _is_grammar_accept_string(
+ grammar: Union[Grammar, str],
+ input_str: str,
+ *,
+ debug_print: bool = False,
+ print_time: bool = False,
+) -> bool:
+ """Check if a grammar accepts a string. For test purposes.
+
+ Parameters
+ ----------
+ grammar : Union[Grammar, str]
+ The grammar to check. Can be either a Grammar object or a BNF grammar string.
+ input_str : str
+ The input string to check.
+ debug_print : bool, default: False
+ Whether to print debug information during matching.
+ print_time : bool, default: False
+ Whether to print timing information.
+
+ Returns
+ -------
+ bool
+ True if the grammar accepts the string, False otherwise.
+ """
+
+ if isinstance(grammar, str):
+ grammar = Grammar.from_ebnf(grammar)
+ grammar_compiler = GrammarCompiler(TokenizerInfo([]), cache_enabled=False)
+ compiled_grammar = grammar_compiler.compile_grammar(grammar)
+ matcher = GrammarMatcher(compiled_grammar, terminate_without_stop_token=True)
+
+ if print_time:
+ start = time.monotonic_ns()
+ accepted = matcher._debug_accept_string(input_str, debug_print=debug_print)
+
+ if print_time:
+ end = time.monotonic_ns()
+ print(f"Accepting {input_str}, result: {accepted}, time: {(end - start) / 1e3} us")
+
+ if not accepted:
+ return False
+ return matcher.is_terminated()
+
+
+def _get_masked_tokens_from_bitmask(
+ bitmask: torch.Tensor, vocab_size: int, index: int = 0
+) -> List[int]:
+ """Get the ids of the rejected tokens from the bitmask. Mainly for debug purposes.
+
+ Parameters
+ ----------
+ bitmask : torch.Tensor
+ The rejected token bitmask. Should be generated by allocate_token_bitmask and
+ filled by fill_next_token_bitmask. Should be on CPU.
+
+ index : int, default: 0
+ The batch index of the bitmask. For batch inference, bitmask[index] will be used.
+ Otherwise is ignored.
+
+ Returns
+ -------
+ rejected_token_ids : List[int]
+ A list of rejected token ids.
+ """
+ if bitmask.device.type != "cpu":
+ raise ValueError("bitmask should be on CPU.")
+ if bitmask.dtype != bitmask_dtype:
+ raise ValueError(f"bitmask should be of type {bitmask_dtype}.")
+ return _core.testing._get_masked_tokens_from_bitmask(
+ bitmask.data_ptr(), list(bitmask.shape), vocab_size, index
+ )
+
+
+def _is_single_token_bitmask(
+ bitmask: torch.Tensor, vocab_size: int, index: int = 0
+) -> Tuple[bool, int]:
+ """Check if the bitmask is a single token bitmask.
+
+ Parameters
+ ----------
+ bitmask : torch.Tensor
+ The bitmask to check. Should be on CPU.
+ vocab_size : int
+ The size of the vocabulary.
+ index : int, default: 0
+ The index of the bitmask.
+
+ Returns
+ -------
+ is_single_token : bool
+ True if the bitmask is a single token bitmask, False otherwise.
+ token_id : int
+ The id of the token if the bitmask is a single token bitmask, -1 otherwise.
+ """
+ return _core.testing._is_single_token_bitmask(
+ bitmask.data_ptr(), list(bitmask.shape), vocab_size, index
+ )
+
+
+def _bool_mask_to_bitmask(bool_mask: torch.Tensor) -> torch.Tensor:
+ """Get the bitmask from bool mask. If the bool mask does not align with the 32-bit block
+ size, it will add extra 1 paddings.
+
+ Parameters
+ ----------
+ bool_mask : torch.Tensor
+ The rejected token bool mask. For each element value, True means the token is allowed,
+ while False means the token is rejected.
+
+ Returns
+ -------
+ bitmask : torch.Tensor
+ The rejected token bitmask.
+ """
+ bool_mask_int32 = bool_mask.to(torch.int32)
+ # Pad to multiple of 32
+ pad_size = (32 - bool_mask.shape[1] % 32) % 32
+ if pad_size > 0:
+ bool_mask_int32 = torch.nn.functional.pad(bool_mask_int32, (0, pad_size), value=1)
+ bool_mask_view = bool_mask_int32.view(bool_mask.shape[0], -1, 32)
+ # To avoid error for overflow, we construct int64 weights and convert to int32
+ weights = torch.tensor(
+ [1 << i for i in range(32)], device=bool_mask.device, dtype=torch.int64
+ ).to(torch.int32)
+ bitmask = (bool_mask_view * weights).sum(dim=2)
+ return bitmask.to(torch.int32)
+
+
+def _get_matcher_from_grammar_and_tokenizer_info(
+ grammar: Union[Grammar, str], tokenizer_info: Optional[TokenizerInfo] = None, **kwargs
+) -> GrammarMatcher:
+ """Create a GrammarMatcher from a grammar and tokenizer info.
+
+ Parameters
+ ----------
+ grammar : Union[Grammar, str]
+ The grammar to create the matcher from. Can be either a Grammar object or a string
+ containing EBNF grammar.
+ tokenizer_info : Optional[TokenizerInfo], default: None
+ Information about the tokenizer to use with this grammar. If None, an empty
+ TokenizerInfo will be created.
+ **kwargs
+ Additional keyword arguments to pass to the GrammarMatcher constructor.
+
+ Returns
+ -------
+ matcher : GrammarMatcher
+ The created grammar matcher.
+ """
+ if tokenizer_info is None:
+ tokenizer_info = TokenizerInfo([])
+ grammar_compiler = GrammarCompiler(tokenizer_info, cache_enabled=False)
+ compiled_grammar = grammar_compiler.compile_grammar(grammar)
+ return GrammarMatcher(compiled_grammar, **kwargs)
+
+
+def _get_allow_empty_rule_ids(compiled_grammar: CompiledGrammar) -> List[int]:
+ return _core.testing._get_allow_empty_rule_ids(compiled_grammar._handle)
+
+
+def _generate_range_regex(start: Optional[int] = None, end: Optional[int] = None) -> str:
+ return _core.testing._generate_range_regex(start, end)
+
+
+def _generate_float_regex(start: Optional[float] = None, end: Optional[float] = None) -> str:
+ return _core.testing._generate_float_regex(start, end)
+
+
+class GrammarFunctor:
+ """A utility class for transforming grammars. These methods are called during grammar parsing.
+ For test purposes."""
+
+ @staticmethod
+ def structure_normalizer(grammar: Grammar) -> Grammar:
+ """Normalize the structure of the grammar."""
+ return Grammar._create_from_handle(
+ _core.testing.grammar_functor.structure_normalizer(grammar._handle)
+ )
+
+ @staticmethod
+ def rule_inliner(grammar: Grammar) -> Grammar:
+ """Inline some rule references in the grammar."""
+ return Grammar._create_from_handle(
+ _core.testing.grammar_functor.rule_inliner(grammar._handle)
+ )
+
+ @staticmethod
+ def byte_string_fuser(grammar: Grammar) -> Grammar:
+ """Fuse the byte string elements in the grammar."""
+ return Grammar._create_from_handle(
+ _core.testing.grammar_functor.byte_string_fuser(grammar._handle)
+ )
+
+ @staticmethod
+ def dead_code_eliminator(grammar: Grammar) -> Grammar:
+ """Eliminate the not referenced rules in the grammar."""
+ return Grammar._create_from_handle(
+ _core.testing.grammar_functor.dead_code_eliminator(grammar._handle)
+ )
+
+ @staticmethod
+ def lookahead_assertion_analyzer(grammar: Grammar) -> Grammar:
+ """Analyze and add lookahead assertions in the grammar."""
+ return Grammar._create_from_handle(
+ _core.testing.grammar_functor.lookahead_assertion_analyzer(grammar._handle)
+ )
diff --git a/venv/lib/python3.10/site-packages/xgrammar/tokenizer_info.py b/venv/lib/python3.10/site-packages/xgrammar/tokenizer_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd2ab396d40ad643460e12a77165e42a9a99f0a3
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/tokenizer_info.py
@@ -0,0 +1,370 @@
+"""This module provides the tokenizer info class to handle the tokenizer information."""
+
+import json
+from enum import Enum
+from typing import Any, Dict, List, Optional, Union
+
+import sentencepiece
+import tiktoken
+from transformers import PreTrainedTokenizerBase, PreTrainedTokenizerFast
+
+from .base import XGRObject, _core
+from .support import logging
+
+logging.enable_logging()
+logger = logging.getLogger(__name__)
+
+
+class VocabType(Enum):
+ """The type of the vocabulary. Used in TokenizerInfo. XGrammar supports three types of
+ vocabularies:
+
+ RAW
+ The vocabulary is in the raw format. The tokens in the vocabulary are kept in their
+ original form without any processing. This kind of tokenizer includes the tiktoken
+ tokenizer, e.g. microsoft/Phi-3-small-8k-instruct, Qwen/Qwen-7B-Chat, etc.
+
+ BYTE_FALLBACK
+ The vocabulary used in the byte fallback BPE tokenizer. The tokens are encoded through
+ the byte-fallback conversion. E.g. "\u001b" -> "<0x1B>", " apple" -> "▁apple". This kind of
+ tokenizer includes meta-llama/Llama-2-7b-chat, microsoft/Phi-3.5-mini-instruct, etc.
+
+ BYTE_LEVEL
+ The vocabulary used in the byte level BPE tokenizer. The tokens are encoded through
+ the byte-to-unicode conversion, as in
+ https://github.com/huggingface/transformers/blob/87be06ca77166e6a6215eee5a990ab9f07238a18/src/transformers/models/gpt2/tokenization_gpt2.py#L38-L59
+
+ This kind of tokenizer includes meta-llama/Meta-Llama-3-8B-Instruct,
+ meta-llama/Meta-Llama-3.1-8B-Instruct, etc.
+ """
+
+ RAW = 0
+ BYTE_FALLBACK = 1
+ BYTE_LEVEL = 2
+
+
+class TokenizerInfo(XGRObject):
+ """The tokenizer info contains the vocabulary, the type of the vocabulary, and necessary
+ information for the grammar-guided generation.
+
+ Note that although some tokenizers will encode the tokens in a special format, e.g.
+ "<0x1B>" for "\u001b" in the ByteFallback tokenizer, and "Ġ" for " " in the Byte-Level BPE
+ tokenizer, TokenizerInfo always decodes the vocabulary to the original format (e.g. "\u001b"
+ and " ").
+
+ Also note that some models (e.g. Phi-3 and Deepseek-V2) may pad the vocabulary to a multiple
+ of 32. In this case, the model's vocab_size is larger than the tokenizer's vocabulary size.
+ Please pass the model's vocab_size to the vocab_size parameter in the constructor, because
+ this information is used to determine the size of the token mask.
+
+ Parameters
+ ----------
+ encoded_vocab : Union[List[bytes], List[str]]
+ The encoded vocabulary of the tokenizer.
+
+ vocab_type : VocabType, default: VocabType.RAW
+ The type of the vocabulary. See also VocabType.
+
+ vocab_size : Optional[int], default: None
+ The size of the vocabulary. If not provided, the vocabulary size will be len(encoded_vocab).
+
+ stop_token_ids : Optional[List[int]], default: None
+ The stop token ids. If not provided, the stop token ids will be auto detected (but may not
+ be correct).
+
+ add_prefix_space : bool, default: False
+ Whether the tokenizer will prepend a space before the text in the tokenization process.
+ """
+
+ def __init__(
+ self,
+ encoded_vocab: Union[List[bytes], List[str]],
+ vocab_type: VocabType = VocabType.RAW,
+ *,
+ vocab_size: Optional[int] = None,
+ stop_token_ids: Optional[Union[List[int], int]] = None,
+ add_prefix_space: bool = False,
+ ) -> None:
+ if isinstance(stop_token_ids, int):
+ stop_token_ids = [stop_token_ids]
+ self._init_handle(
+ _core.TokenizerInfo(
+ encoded_vocab, vocab_type.value, vocab_size, stop_token_ids, add_prefix_space
+ )
+ )
+
+ @staticmethod
+ def _is_tiktoken_tokenizer(tokenizer: PreTrainedTokenizerBase) -> bool:
+ # helper to check if tokenizer is a tiktoken tokenizer
+ has_tiktoken_encoding = hasattr(tokenizer, "tokenizer") and isinstance(
+ tokenizer.tokenizer, tiktoken.Encoding
+ )
+
+ filename_pattern = (
+ hasattr(tokenizer, "vocab_files_names")
+ and "vocab_file" in tokenizer.vocab_files_names
+ and "tiktoken" in tokenizer.vocab_files_names["vocab_file"]
+ )
+
+ return has_tiktoken_encoding or filename_pattern
+
+ @staticmethod
+ def _is_sentencepiece_tokenizer(tokenizer: PreTrainedTokenizerBase) -> bool:
+ # helper to check if tokenizer is a sentence piece tokenizer
+ has_sp_model_attr = hasattr(tokenizer, "sp_model") and isinstance(
+ tokenizer.sp_model, sentencepiece.SentencePieceProcessor
+ )
+
+ has_nested_sp_model_attr = (
+ hasattr(tokenizer, "tokenizer")
+ and hasattr(tokenizer.tokenizer, "sp_model")
+ and isinstance(tokenizer.tokenizer.sp_model, sentencepiece.SentencePieceProcessor)
+ )
+
+ return has_sp_model_attr or has_nested_sp_model_attr
+
+ @staticmethod
+ def from_huggingface(
+ tokenizer: PreTrainedTokenizerBase,
+ *,
+ vocab_size: Optional[int] = None,
+ stop_token_ids: Optional[Union[List[int], int]] = None,
+ ) -> "TokenizerInfo":
+ """Construct the tokenizer info from the huggingface tokenizer. This constructor supports
+ various tokenizer backends, including the huggingface fast tokenizer and tiktoken tokenizer.
+ Necessary information is automatically detected from the tokenizer.
+
+ The vocab_size parameter is introduced to handle the misalignment between the model's
+ vocab_size and the tokenizer's vocabulary size. User should pass the model's vocab_size
+ (could be defined in the model config) here. See docs of vocab_size for more details.
+
+ The stop token ids is by default the eos_token_id of the tokenizer. If there are other
+ stop tokens, you can specify them manually.
+
+ Parameters
+ ----------
+ tokenizer : PreTrainedTokenizerBase
+ The huggingface tokenizer.
+
+ vocab_size : Optional[int], default: None
+ The vocabulary size **defined by the model** (**not the tokenizer**). This equals to the
+ vocab dimention of the model's lm_head. This is the size of the token mask.
+
+ It can be:
+ 1. the same as the tokenizer's vocabulary size. This is the most common case.
+ 2. larger than the tokenizer's vocabulary size. This happens when the model has padding
+ to lm_head, possibly due to aligning lm_head to the power of 2.
+ E.g. Phi-3 and Deepseek-V2.
+ 3. smaller than the tokenizer's vocabulary size. This happens when the tokenizer has
+ some added tokens that will not supported by the model. E.g.
+ Llama-3.2 Vision and Molmo-72B-0924 has padded <|image|> tokens, but they will not
+ be considered in lm_head or generated by the model.
+
+ model_vocab_size need to be provided for case 2 and 3. If not provided, it will be
+ set to the tokenizer's vocabulary size.
+
+ stop_token_ids : Optional[List[int]], default: None
+ The stop token ids. If not provided, the eos_token_id of the tokenizer will be used.
+
+ Returns
+ -------
+ tokenizer_info : TokenizerInfo
+ The tokenizer info.
+ """
+ if isinstance(stop_token_ids, int):
+ stop_token_ids = [stop_token_ids]
+ if isinstance(stop_token_ids, list) and len(stop_token_ids) == 0:
+ raise ValueError("stop_token_ids cannot be empty")
+
+ try:
+ vocab_dict = tokenizer.get_vocab()
+ except AttributeError as e:
+ msg = (
+ f"Cannot get the vocabulary of the tokenizer {type(tokenizer)}. The tokenizer "
+ "should have a get_vocab method."
+ )
+ raise ValueError(msg) from e
+
+ # Some tokenizer don't have token id 0 or 1 or 2. So the max_id could be larger than the
+ # number of tokens.
+ max_id = max(vocab_dict.values())
+ tokenizer_vocab_size = max(len(vocab_dict), max_id + 1)
+
+ vocab_size = vocab_size or tokenizer_vocab_size
+
+ # maintain tokenizer's indexing
+ encoded_vocab = [""] * vocab_size
+ for token, idx in vocab_dict.items():
+ if idx < vocab_size:
+ encoded_vocab[idx] = token
+
+ if isinstance(tokenizer, PreTrainedTokenizerFast):
+ # huggingface fast tokenizer
+ # - the vocabulary is directly obtained from tokenizer.get_vocab()
+ # (tokenizer.backend_tokenizer.to_str() may not contain the full vocab, special
+ # tokens may be omitted)
+ # - the vocab size is obtained from len(tokenizer.get_vocab()) or provided by user
+ # - the vocab type and add_prefix_space are obtained from
+ # tokenizer.backend_tokenizer.to_str()
+ # - stop token id is provided by user, or auto detected.
+ backend_str = tokenizer.backend_tokenizer.to_str()
+ if stop_token_ids is None:
+ if hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None:
+ stop_token_ids = [tokenizer.eos_token_id]
+ else:
+ logger.warning(
+ "When constructing TokenizerInfo from a huggingface tokenizer, "
+ "stop_token_ids is neither provided by user nor found from the tokenizer. "
+ "It will be automatically detected."
+ )
+ metadata = TokenizerInfo._detect_metadata_from_hf(backend_str)
+ return TokenizerInfo(
+ encoded_vocab,
+ vocab_type=metadata["vocab_type"],
+ vocab_size=vocab_size,
+ stop_token_ids=stop_token_ids,
+ add_prefix_space=metadata["add_prefix_space"],
+ )
+
+ elif TokenizerInfo._is_tiktoken_tokenizer(tokenizer):
+ # tiktoken tokenizer
+ # e.g. Phi-3-small-8k-instruct, Qwen-7B-Chat, stablelm-2-12b-chat (previously)
+ if stop_token_ids is None:
+ if hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None:
+ stop_token_ids = [tokenizer.eos_token_id]
+ else:
+ logger.warning(
+ "When constructing TokenizerInfo from a huggingface tokenizer, "
+ "stop_token_ids is neither provided by user nor found from the tokenizer. "
+ "It will be automatically detected."
+ )
+ return TokenizerInfo(
+ encoded_vocab,
+ VocabType.RAW,
+ vocab_size=vocab_size,
+ stop_token_ids=stop_token_ids,
+ add_prefix_space=False,
+ )
+
+ elif TokenizerInfo._is_sentencepiece_tokenizer(tokenizer):
+ # sentencepiece tokenizer
+ # e.g. Chatglm3-6b
+ if hasattr(tokenizer, "sp_model"):
+ sp_model = tokenizer.sp_model
+ elif hasattr(tokenizer, "tokenizer") and hasattr(tokenizer.tokenizer, "sp_model"):
+ sp_model = tokenizer.tokenizer.sp_model
+
+ if stop_token_ids is None:
+ if hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None:
+ stop_token_ids = [tokenizer.eos_token_id]
+ else:
+ eos_id = sp_model.eos_id()
+ if eos_id != -1:
+ stop_token_ids = [eos_id]
+ else:
+ logger.warning(
+ "When constructing TokenizerInfo from a huggingface tokenizer, "
+ "stop_token_ids is neither provided by user nor found from the tokenizer. "
+ "It will be automatically detected."
+ )
+ # detect vocab_type of tokenizer
+ if "<0x0A>" in vocab_dict:
+ vocab_type = VocabType.BYTE_FALLBACK
+ else:
+ vocab_type = VocabType.RAW
+
+ return TokenizerInfo(
+ encoded_vocab,
+ vocab_type=vocab_type,
+ vocab_size=vocab_size,
+ stop_token_ids=stop_token_ids,
+ add_prefix_space=True,
+ )
+
+ else:
+ # TODO(yixin): unsupported tokenizer
+ raise ValueError(f"Unsupported tokenizer type: {type(tokenizer)}")
+
+ @property
+ def vocab_type(self) -> VocabType:
+ """The type of the vocabulary."""
+ return VocabType(self._handle.vocab_type)
+
+ @property
+ def vocab_size(self) -> int:
+ """The size of the vocabulary."""
+ return self._handle.vocab_size
+
+ @property
+ def add_prefix_space(self) -> bool:
+ """Whether the tokenizer will prepend a space before the text in the tokenization
+ process."""
+ return self._handle.add_prefix_space
+
+ @property
+ def prepend_space_in_tokenization(self) -> bool:
+ """Whether the tokenizer will prepend a space before the text in the tokenization
+ process.
+
+ This property is deprecated. Use add_prefix_space instead.
+ """
+ logger.warning("prepend_space_in_tokenization is deprecated. Use add_prefix_space instead.")
+ return self.add_prefix_space
+
+ @property
+ def decoded_vocab(self) -> List[bytes]:
+ """The decoded vocabulary of the tokenizer. This converts the tokens in the LLM's
+ vocabulary back to the original format of the input text. E.g. for type ByteFallback,
+ the token <0x1B> is converted back to "\u001b".
+ """
+ return self._handle.decoded_vocab
+
+ @property
+ def stop_token_ids(self) -> List[int]:
+ """The stop token ids."""
+ return self._handle.stop_token_ids
+
+ @property
+ def special_token_ids(self) -> List[int]:
+ """The special token ids. Special tokens include control tokens, reserved tokens,
+ padded tokens, etc. Now it is automatically detected from the vocabulary."""
+ return self._handle.special_token_ids
+
+ def dump_metadata(self) -> str:
+ """Dump the metadata of the tokenizer to a json string. It can be used to construct the
+ tokenizer info from the vocabulary and the metadata string."""
+ return self._handle.dump_metadata()
+
+ @staticmethod
+ def from_vocab_and_metadata(
+ encoded_vocab: List[Union[bytes, str]], metadata: str
+ ) -> "TokenizerInfo":
+ """Construct the tokenizer info from the vocabulary and the metadata string in json
+ format.
+
+ Parameters
+ ----------
+ encoded_vocab : List[Union[bytes, str]]
+ The encoded vocabulary of the tokenizer.
+
+ metadata : str
+ The metadata string in json format.
+ """
+ return TokenizerInfo._create_from_handle(
+ _core.TokenizerInfo.from_vocab_and_metadata(encoded_vocab, metadata)
+ )
+
+ @staticmethod
+ def _detect_metadata_from_hf(backend_str: str) -> Dict[str, Any]:
+ """Detect the metadata from the huggingface tokenizer backend string. For implementation
+ use only.
+
+ It returns {"vocab_type": VocabType, "add_prefix_space": bool}.
+ """
+ # the metadata_str should in the format of {"vocab_type": int, "add_prefix_space": bool}
+ metadata_str = _core.TokenizerInfo._detect_metadata_from_hf(backend_str)
+ metadata = json.loads(metadata_str)
+ return {
+ "vocab_type": VocabType(metadata["vocab_type"]),
+ "add_prefix_space": metadata["add_prefix_space"],
+ }
diff --git a/venv/lib/python3.10/site-packages/xgrammar/version.py b/venv/lib/python3.10/site-packages/xgrammar/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..837eab85208b21ea2d9a32d4f84bd98e610f0a19
--- /dev/null
+++ b/venv/lib/python3.10/site-packages/xgrammar/version.py
@@ -0,0 +1,141 @@
+# pylint: disable=missing-docstring
+import argparse
+import logging
+import os
+import subprocess
+
+# Modify the following value during release
+# ---------------------------------------------------
+# Current version:
+# We use the version of the incoming release for code
+# that is under development.
+#
+# It is also fallback version to be used when --git-describe
+# is not invoked, or when the repository does not present the
+# git tags in a format that this script can use.
+#
+# Two tag formats are supported:
+# - vMAJ.MIN.PATCH (e.g. v0.8.0) or
+# - vMAJ.MIN.devN (e.g. v0.8.dev0)
+
+# ---------------------------------------------------
+
+__version__ = "0.1.18"
+PROJ_ROOT = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
+
+
+def py_str(cstr):
+ return cstr.decode("utf-8")
+
+
+def git_describe_version():
+ """Get PEP-440 compatible public and local version using git describe.
+
+ Returns
+ -------
+ pub_ver: str
+ Public version.
+
+ local_ver: str
+ Local version (with additional label appended to pub_ver).
+
+ Notes
+ -----
+ - We follow PEP 440's convention of public version
+ and local versions.
+ - Only tags conforming to vMAJOR.MINOR.REV (e.g. "v0.7.0")
+ are considered in order to generate the version string.
+ See the use of `--match` in the `git` command below.
+
+ Here are some examples:
+
+ - pub_ver = '0.7.0', local_ver = '0.7.0':
+ We are at the 0.7.0 release.
+ - pub_ver = '0.8.dev94', local_ver = '0.8.dev94+g0d07a329e':
+ We are at the 0.8 development cycle.
+ The current source contains 94 additional commits
+ after the most recent tag(v0.7.0),
+ the git short hash tag of the current commit is 0d07a329e.
+ """
+ cmd = [
+ "git",
+ "describe",
+ "--tags",
+ "--match",
+ "v[0-9]*.[0-9]*.[0-9]*",
+ "--match",
+ "v[0-9]*.[0-9]*.dev[0-9]*",
+ ]
+ with subprocess.Popen(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=PROJ_ROOT
+ ) as proc:
+ (out, _) = proc.communicate()
+
+ if proc.returncode != 0:
+ msg = py_str(out)
+ logging.warning("git describe: %s", msg)
+ return None, None
+ describe = py_str(out).strip()
+ arr_info = describe.split("-")
+
+ # Remove the v prefix, mainly to be robust
+ # to the case where v is not presented as well.
+ if arr_info[0].startswith("v"):
+ arr_info[0] = arr_info[0][1:]
+
+ # hit the exact tag
+ if len(arr_info) == 1:
+ return arr_info[0], arr_info[0]
+
+ if len(arr_info) != 3:
+ logging.warning("Invalid output from git describe %s", describe)
+ return None, None
+
+ dev_pos = arr_info[0].find(".dev")
+
+ # Development versions:
+ # The code will reach this point in case it can't match a full release version, such as v0.7.0.
+ #
+ # 1. in case the last known label looks like vMAJ.MIN.devN e.g. v0.8.dev0, we use
+ # the current behavior of just using vMAJ.MIN.devNNNN+gGIT_REV
+ if dev_pos != -1:
+ dev_version = arr_info[0][: arr_info[0].find(".dev")]
+ # 2. in case the last known label looks like vMAJ.MIN.PATCH e.g. v0.8.0
+ # then we just carry on with a similar version to what git describe provides, which is
+ # vMAJ.MIN.PATCH.devNNNN+gGIT_REV
+ else:
+ dev_version = arr_info[0]
+
+ pub_ver = f"{dev_version}.dev{arr_info[1]}"
+ local_ver = f"{pub_ver}+{arr_info[2]}"
+ return pub_ver, local_ver
+
+
+def main():
+ logging.basicConfig(level=logging.INFO)
+ parser = argparse.ArgumentParser(description="Detect and synchronize version.")
+ parser.add_argument(
+ "--print-version",
+ action="store_true",
+ help="Print version to the command line. No changes is applied to files.",
+ )
+ parser.add_argument(
+ "--git-describe",
+ action="store_true",
+ help="Use git describe to generate development version.",
+ )
+ parser.add_argument("--dry-run", action="store_true")
+ opt = parser.parse_args()
+ pub_ver, local_ver = None, None
+ if opt.git_describe:
+ pub_ver, local_ver = git_describe_version()
+ if pub_ver is None:
+ pub_ver = __version__
+ if local_ver is None:
+ local_ver = __version__
+ if opt.print_version:
+ print(local_ver)
+
+
+if __name__ == "__main__":
+ main()