Repository navigation
feat(python): matrixone.vecblock and PyTorch examples for vecf8/vecf4 (#20567) - #32166
Conversation
…rixorigin#20567) Add the low-precision float value types for the new scalar bf16/float16/float8/ float4 SQL columns. Float8 is OCP/NVIDIA FP8 e4m3 (1-byte, no Inf, max 448); Float4 is OCP MXFP4 e2m1 (1-byte, magnitudes {0,.5,1,1.5,2,3,4,6}, NVIDIA-bit-compatible). Both convert to/from float32 (round-to-nearest-even, saturating overflow) so all arithmetic runs on the existing float32 kernels. Reference-value + full round-trip unit tests included. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rixorigin#20567) Add T_bf16=73, T_float16=74, T_float8=75, T_float4=76 to the type system: SQL names, sizes (2/2/1/1 bytes), FixedLength/TypeLen, ToType, String/OidString, and IsFloat classification. They satisfy FixedSizeT already via ~uint16/~uint8, so the vector container generics accept them without constraint changes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…origin#20567) Add BF16/FLOAT16/FLOAT8/FLOAT4 keyword tokens and no-length column_type grammar rules (float4/float8 were reserved-but-UNUSED), regenerate the mysql parser, and map them in getTypeFromAst (MYSQL_TYPE_FLOAT disambiguated by FamilyString) to T_bf16/T_float16/T_float8/T_float4. Fixes the issue's 1064 on CREATE TABLE. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rt (matrixorigin#20567) Start Layer 4 (vector container): GetAny dispatches the four new scalar float type IDs to their value types. Remaining container switches (Append/Shrink/Shuffle/ String/min-max/compare/sort) still to do -- sort/min-max must compare by float value, not raw bits. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tches (matrixorigin#20567) Add the four scalar float type IDs to the value-access (GetAny/AppendAny/String/ RowToString) and movement (Shrink/ShrinkByMask/Shuffle/ShuffleWithBuf) container switches. Union/const-set and the compare/sort/min-max/sum switches (which must order by float value, not raw bits) still to do. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…oat4 (matrixorigin#20567) Contract, format decisions (FP8 e4m3, FP4 e2m1/MXFP4), and invariants (float32 bridge arithmetic, value-order comparison, saturating RNE narrowing). sparsevec deferred to a separate design. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…float4 (matrixorigin#20567) The four new scalar float types are byte-identical to uint16 (bf16/float16) and uint8 (float8/float4) for the value-agnostic union-all and const-set copy paths, so add them to those case labels. Remaining container work: compare/sort/min-max/sum must order by float value. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…float16/float8/float4 (matrixorigin#20567) The container ordering and aggregation paths fell through to raw-bit handling for the low-precision float types, which is wrong: a float's sign bit makes raw uint order disagree with value order (negatives sort as large positives). Route them through ToFloat32: - compareVectorRows: add bf16/float16/float8/float4 via new compareFloatRows. - InplaceSort / InplaceSortAndCompact: sort (and value-dedup) via ToFloat32; add the four types to supportsInplaceSort. - GetSumValue / GetMinMaxValue: widen via new LowPrecFloatGetSum / LowPrecFloatGetMinAndMax; min/max skips NaN like the float32/64 path. - typeCompatible: recognize the four named types for type-checked column access (needed by appendList in the compact path). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…32 bridge (matrixorigin#20567) Casts to/from the low-precision float types bridge through float32: any source widens to float32 then rounds to the target format via FromFloat32, and any low-precision source widens to float32 then reuses the float32 target machinery (inheriting exact integer-rounding, decimal, and string-formatting semantics). - func_cast_lowprec_float.go: castToLowPrecFloat (X->newtype), lowPrecFloatToOthers (newtype->X), string parse, decimal256 routed to castToDecimal256; init() wires the supportedTypeCast gate for all numeric/string sources and targets. - func_cast.go: route low-precision source/target ahead of the integer/decimal fast-paths so a low-precision operand is never misdispatched. - functionTools.go: NewFunctionResultWrapper builds result vectors for the 4 types (was panicking). - func_testcase.go: test framework builds and compares the 4 types. - func_cast_test.go: TestCastLowPrecFloat covers float64<->each, a cross-cast, and string<->float8. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…16/float16/float8/float4 (matrixorigin#20567) Binary operators and aggregates treat the low-precision float types as float32, which holds every bf16/float16/float8/float4 value losslessly: - type_check.go: fixedTypeCastRule1 (arithmetic + comparison) and fixedTypeCastRule2 (div) normalize a low-precision operand to float32 before selecting the coercion rule, mirroring the existing T_enum->uint16 treatment. float32 has no diagonal cast rule (equal types need none), so a low-precision pair that both normalize to float32 forces the cast to float32 explicitly. - list_agg.go: sumAvgTypeCheck and a new minMaxTypeCheck widen a low-precision input to float32 (SUM/AVG return float64; MIN/MAX return float32) -- newGenericMinMaxExec compares raw uint bits, which do not order floats, so native support is unsafe. The operand cast itself uses the float32 bridge added for CAST. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t8/float4 (matrixorigin#20567) The storage/zonemap comparators must order these types by float VALUE, not the raw uint bits (a negative float's bits exceed a positive's), and several switches panicked on the unregistered types: - types.EncodeValue/DecodeValue: register the four types (were panicking in the zonemap value path, e.g. UpdateZMAny). - compute.Compare/CompareGeneric: compare via ToFloat32 (drives zonemap min/max maintenance in UpdateZM and Contains/containsBytes pruning). - zm.getValue: decode the four types (MO_TABLE_COL_MAX read path panicked otherwise). - zm.SubVecIn: value-aware bound search on a value-sorted column (subVecInLowPrecFloat); BatchUpdateZM already feeds value-correct min/max from vector.GetMinMaxValue. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…oat8/float4 (matrixorigin#20567) Result-set output and CSV/LOAD parsing for the low-precision float types, presenting them as float32 (they widen losslessly): - frontend: column type maps to MYSQL_TYPE_FLOAT; the colSlices path widens the column into arrFloat32 at build time (lowPrecFloatVecToFloat32Slice) so GetFloat32/GetFloat64 and the row extractors read it as float32; the legacy any-row and ExtractRowFromEveryVector paths return .ToFloat32(). - external LOAD: parse the field as float32 then round to the target format; the empty zero-fill and the row-validity predicate accept the four types. Strict finite/range checking on the string-parse boundary (LOAD + CAST-from-string): types.RejectNonFiniteNarrowFloat rejects NaN/Inf and out-of-range values instead of silently saturating, mirroring the narrow-vector element parser (rejectNonFiniteArrayElem). bf16/float16 overflow is detected as Inf after narrowing; float8/float4 saturate, so their input magnitude is range-checked (448 / 6). Numeric CAST keeps the saturating constructor, matching the documented vecint8 precedent (string parse strict, CAST clamps). Tests: RejectNonFiniteNarrowFloat, Inf conversion (bf16/float16 preserve, float8/float4 saturate), subnormals for all four, and the frontend colSlices output path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…f coverage to ~87% Add unit tests for the new-code paths that the feature tests did not reach, so the PR's aggregate diff coverage clears the 75% gate: - vector: GetAny/AppendAny/String/RowToString/Shrink/ShrinkByMask/Shuffle/ShuffleWithBuf and NewFunctionResultWrapper for all four types. - types: type-registration switches (TypeLen/FixedLength/String/OidString/IsFloat/ToType), EncodeValue/DecodeValue, and the slice converters. - compute: Compare and CompareGeneric order by float value (negative discriminator). - tae/index: fix TestZonemapLowPrecFloat to use >3 rows so SubVecIn reaches the per-type bound search instead of the small-vector early return. - external: getColData LOAD parse (valid rounds, empty zero-fills, out-of-range/non-finite rejected) and appendLoadEmptyNumericZero. - frontend: getValueFromVector, extractRowFromVector (legacy any-row), and convertEngineTypeToMysqlType present the types as FLOAT. - plan: getTypeFromAst disambiguates the four via FamilyString. - function: broaden the cast matrix across source types -> bf16 and float8 -> targets. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…float16/float8/float4; add BVT BVT (test/distributed/cases/dtype/lowprec_float) surfaced two gaps beyond the earlier per-layer work: - pkg/sort: ORDER BY did not sort these columns -- IsSupportedType and the comparator switch omitted them, and the sortType constraint lacked the scalar slice types, so the order operator treated them as equal (stable -> insertion order). Add the four types to the constraint, IsSupportedType, and the switch with value-aware comparators (widen via ToFloat32, reusing the float32 SQL NaN-aware ordering). - function: inserting a negative literal (e.g. -2.0) into such a column failed with 'unary_minus bad value [BF16]'. unaryMinusMatch and UNARY_PLUS (new unaryPlusMatch) now cast a low-precision operand to float32, mirroring the binary-operator coercion. BVT covers DDL, insert (incl. negatives/NULL), value-ordered ORDER BY, comparison, arithmetic, SUM/AVG/MIN/MAX, CAST both ways, out-of-range reject, and INSERT..SELECT round-trip; validated 27/27 on a live cluster. Unit tests: TestSortLowPrecFloat and unary coverage in the ops test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts: # pkg/sql/plan/function/list_agg.go # pkg/sql/plan/function/type_check.go
…256 cast, non-finite persistence Three defects found by the self-review gate: - types/float8.go: Float8FromFloat32 subnormal->normal round-up silently returned ZERO. roundMantissaRNE masks its result and signals the boundary overflow only via its carry, but the subnormal branch dropped the carry (mant, _ :=) and its mant>=8 guard was therefore dead. Every value in (0.013671875, 0.015625) narrowed to 0 instead of the smallest normal 0x08 -- silent data loss. Honor the carry. - function/func_cast_lowprec_float.go: decimal256 was registered in supportedTypeCast but anyToLowPrecFloat lacked the case, so a planned CAST(decimal256 AS bf16/...) failed at execution with an internal error. Add the decimal256 case (types.Decimal256ToFloat64). - function/func_cast_lowprec_float.go: the numeric cast path applied no finite check, so an overflowing float64/decimal source persisted +Inf for bf16/float16 (and NaN for float8), violating the repo-wide never-persist-non-finite invariant (matrixorigin#29084) and diverging from the string path. Route the numeric path through opUnaryFixedToFixedWithErrorCheck + RejectNonFiniteNarrowFloat so NaN/Inf/out-of-range errors uniformly, matching the string cast and matrixorigin#29084's rejectNonFiniteVectorElems. - tae/index/zm.go: hasNaNBound now covers bf16/float16/float8 for defense-in-depth parity with float32/float64 (float4 has no NaN encoding). Latent today since GetMinMaxValue skips NaN, but keeps the fail-open guard consistent. Regression tests: TestFloat8SubnormalRoundUpToNormal, TestCastLowPrecFloatDecimal256AndNonFinite. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nstraint types.LowPrecFloat
Replace the inline interface{ ToFloat32() float32 } (and the multi-line
FixedSizeTExceptStrType + ToFloat32 form) repeated across the ordering, compare,
sum/min-max, sort, zonemap, frontend, and cast helpers with a single named constraint
types.LowPrecFloat = { FixedSizeTExceptStrType; ToFloat32() float32 }. The union+method
together admit exactly bf16/float16/float8/float4, so the fixed-size storage bound
(DecodeFixed / column accessors) and the value-widening method live in one place.
No behavior change.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ecimal256 cases
Cover the self-review fixes end-to-end on a live cluster (47/47):
- out-of-range NUMERIC cast rejected (not just string): CAST(7 AS float4),
CAST(1000 AS float8), CAST(70000 AS float16), CAST(1e300 AS bf16).
- Inf/NaN cast rejected: CAST('inf'/'nan'/'-inf' ...), and CAST(1e308*100 AS bf16)
(arithmetic overflow to Inf).
- arithmetic result overflowing the narrow range rejected on cast-back:
CAST(6*2 AS float4), CAST(a+b AS float4) with 3+4>6.
- FP8 subnormal round-up regression: CAST(0.015 AS float8) = 0.015625 (was silently
zero); min-subnormal round-trip; underflow to 0; float4 0.5 subnormal.
- decimal256 -> bf16/float8.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…trixorigin#20567) Design for packed low-precision float vector columns for quantized ML embeddings: per-32-block E8M0 (MXFP) scaling, one shared byte-exact-MXFP payload format for both e4m3 (vecf8) and e2m1 (vecf4) elements, and an MO-only header stripped so the GPU path is a straight memcpy to cuVS/CUTLASS MXFP kernels (no dequant/requant). Contract, decisions, and invariants only; depends on the scalar float8/float4 element codecs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… P4 dependency (matrixorigin#20567) - SQL spelling is vecf8/vecf4 to match the existing family (vecf32/vecf64/vecf16/vecbf16), not vecfloat8/vecfloat4 (there is no vecfloat16 -- it is vecf16). - Note that MO's current cuVS integration supports only float/half/int8/uint8 with no MXFP ingestion, and the cuVS MXFP contract is not vendored (GPU-box only). CPU storage/distance can proceed now; the GPU memcpy path is a forward-looking target pending a cuVS MXFP API. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ot cuVS (matrixorigin#20567) Rewrite the GPU section: fp8/fp4 are tensor-core GEMM formats, so vecf8/vecf4's GPU value is brute-force batch similarity (Q x D^T) via cublasLtMatmul block-scaled matmul, NOT a cuVS index (cuVS accepts only float/half/int8/uint8 + SQ/PQ/binary; no fp8/fp4 path). The stored 32-block E8M0 MXFP payload is exactly cuBLASLt's CUDA_R_UE8 layout, so transfer is strip-header + memcpy into the operand/scale tensors. Records hardware (Blackwell sm_100 / consumer sm_120 incl. RTX 5070), toolchain (CUDA 12.8+/cuBLAS 12.9+), mandatory dataset tiling, MXFP4-vs-NVFP4 fp4 choice, and a P1-P3 CPU / P4 GPU phasing. New cuBLASLt cgo integration, separate from cgo/cuvs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…matrixorigin#20567) Lock the two open decisions: - vecf4 = NVFP4 (e2m1 4-bit elements + E4M3 unsigned 16-block scale, per-vector-normalized, GEMM global=1.0, no stored global). Dictated by cuBLASLt: its FP4 block-scaled matmul consumes NVFP4 only (16-block E4M3), not MXFP4 (32-block E8M0), so storing MXFP4 would force a lossy re-quantization at GEMM and break the strip-header+memcpy contract. NVFP4 is also the more accurate 4-bit format. vecf8 = MXFP8 (e4m3 + E8M0 32-block), which is what cuBLASLt's FP8 path takes directly. - CPU distance accumulate = fp32 (matches the GEMM's fp32 accumulate so CPU==GPU results). Also records: element codecs are the merged scalar Float8/Float4 (bit-identical to CUDA_R_8F_E4M3 / CUDA_R_4F_E2M1) so packing is a pure shuffle; only block-scale codecs are new (E8M0, and reuse Float8 e4m3 for NVFP4's scale); effective bits/element and 1024-dim storage sizes; the per-vector-independent invariant; and the P4 GPU-box verification items. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…l SQL surface (matrixorigin#20567) Verified on RTX 5070 (sm_120), CUDA 13.3, cuBLASLt 13.6: - types.Float8/Float4 match cuda_fp8.h/cuda_fp4.h bit for bit on all codes and 4.3M encode inputs (NaN encoding differs; never stored); FP4 element 2i is the low nibble. - Block scales must use cuBLASLt's tiled 128x4 layout; per-row scales give wrong results. Elements transfer as stored, scales are re-laid out. - Dataset must be operand A: queries-as-A with one query returns silently wrong results. K is padded to a multiple of 32. - MXFP8 and NVFP4 (global 1.0) match a CPU reference; recall@10 on unit-normalized wiki_all 768-d: MXFP8 0.971, NVFP4 0.918. Design: cgo/cublaslt dot-product matmul engine; vector_matmul TVF (one partial per scan pipeline) + vector_matmul_merge aggregate with a JSON result format; single-CN and multi-CN test plan. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…origin#20567) Each hit is a two-element array: position 0 the source key as a JSON string, position 1 the dot product. It halves the result size versus {"id","score"} objects. Unnest reads '$[0]' / '$[1]'; verified on the current build, including a 9223372036854775807 id cast back to bigint. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…/cuda_fp4.h Golden data generated on CUDA 13.3: all 256 e4m3 and 16 e2m1 decodes and 1,069 encode inputs (every rounding midpoint +/-1 ulp, subnormals, saturation, +/-Inf). NaN encoding is excluded (documented difference). A codec change that breaks GPU bit compatibility now fails a CPU-only UT. The generator is cgo/cublaslt/test/narrow_float_golden_gen.cu, with its regeneration command. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
matrixorigin#20567) All C++/CUDA code lives in cgo/cublaslt (engine + test/), all Go GPU code in pkg/cublaslt with //go:build gpu on every file and no CPU stub; callers split *_gpu.go / *_cpu.go like the cuVS table functions. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…#20567) Cell = 12-byte header (version, format, reserved, dim, fp32 global g) + one scale byte per block + packed elements. - vecf8 (MXFP8): e4m3 elements, E8M0 scale per 32, g = 1. - vecf4 (NVFP4): e2m1 elements (element 2i in the low nibble), unsigned E4M3 scale per 16, per-vector fp32 global g = amax/2688, so any finite float32 range fits and block scales stay out of the E4M3 subnormal range. AppendBlockScaled / ParseBlockScaledCell / Dequantize / string round trip; the parser rejects malformed cells (length, version, format, reserved and padding bits, non-finite or negative g, NaN or signed scales, NaN elements). Scale selection is tested minimal at every E8M0/E4M3 boundary; nibble order is checked against CUDA's __nv_cvt_float2_to_fp4x2. Measured with this codec on unit-normalized wiki_all 768-d (50k/200): recall@10 vecf8 0.971, vecf4 0.922. Design doc updated to the two-level vecf4 format. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…rixorigin#20567) T_array_float8 (230, vecf8) and T_array_float4 (231, vecf4) are varlena vector types with Width = dimension. They are deliberately NOT in IsArrayRelate(), which keeps meaning "Width elements of GetArrayElementSize bytes": vecf8/vecf4 cells are block-scaled (vecblock.go) and paths that decode typed slices or call GetArrayElementSize must not accept them. - IsBlockScaledVector(): vecf8/vecf4. - IsVectorType(): IsArrayRelate() || IsBlockScaledVector(), for structural checks that apply to every vector column (PK/partition/index rejection, dimension guards). - BlockScaledFormat(): oid -> cell format. - Type.ArrayCellBytes(): cell byte length for any vector type, the replacement for Width*GetArrayElementSize() size estimates. - Names (VECF8/VECF4, vecf8/vecf4), DescString, OidString, TypeLen, FixedLength, ToType, Types map, DecodeValue/EncodeValue (raw bytes). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- Parser: VECF8/VECF4 tokens (non-reserved keywords) and ArrayFamily type rules; mysql_sql.go regenerated (no conflicts); tree.T prints the width. - Plan: getTypeFromAst maps every vector SQL name through the new types.VectorTypeBySQLName (replaces three hand-maintained six-name lists), so vecf8/vecf4 get the default width and the 1..65535 dimension check. - SHOW CREATE prints VECF8(N)/VECF4(N). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ithmetic/SUM/AVG/inner_product, Parquet LOAD (matrixorigin#20567) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…igin#20567) Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…cf8/vecf4 (matrixorigin#20567) A table created before low-precision cluster keys were rejected failed its TN flush forever ("unsupported data type" in 1-merge aobjects). An AST sweep of the switches that name float32 or vecf32 but not the new types found, besides that: Bugs - TAE aobj/object merge and the CN S3-writer MergeSortBatches had no low-precision sort key (error loop / panic); they order by float32 value as sort.Sort does (sort.LowPrecisionLess). - uuid_to_bin/bin_to_uuid read a bf16 swap flag as varlena (panic); the flag is cast to float64. - DATE_ADD/DATE_SUB/+INTERVAL truncated a low-precision interval to an integer; the value is an interval as its float32 value. - The vector-index distance rewrite peeled cast('[...]' as vecf8(n)) and reported the vecf32 index score for a quantized query vector. - vecf8/vecf4 were accepted as CLUSTER BY and KEY-partition columns, whose byte order/hash splits cells equal by decoded value; both are rejected. Gaps - Zonemap AnyIn, folded constants (getConstantBytes, foldedScalarBytes) and the top-value runtime filter prune by the low-precision value. - vecf8/vecf4 are late-materialization candidates and correlated LIMIT partition keys; json_row writes the new types; Arrow dictionary NULL and MakeAppendBytesFunc handle them; bit_cast to them is not supported instead of an internal error. BVT: lowprec_ddl_dml covers create/alter (add, modify, change, rename, drop column), insert/select, on duplicate key, replace, update, delete, like, as select, rename, truncate and show create table; lowprec_float and vecblock cover each fix. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…matrixorigin#20567) TestTypeSwitchFamilies walks pkg/ (tests excluded) and fails on a switch over types.T that names T_float32 but not every T_float*/T_bf* type, or T_array_float32 but not every T_array_* type, unless the switch carries `// typeswitch:partial <reason>` on or above it (a tag without a reason fails). Family members are read from the constants in types.go, so a new type is checked at every switch on its anchor. The 364 switches that predate the check are in testdata/typeswitch_baseline.txt by file, function and family with a count; a key may not grow. Regenerate with -args -update-typeswitch. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…line (matrixorigin#20567) pkg/container/types/testdata/README.md explains the families, the typeswitch:partial tag, the baseline and its regenerate command, and that the baseline only shrinks; the test's failure messages point to it. The mo-dev skill (both copies) gains a G-TYPESWITCH gate for adding a types.T constant, editing a switch over types.T, or a TestTypeSwitchFamilies failure. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ilies (matrixorigin#20567) A switch that names any T_float*/T_bf* type now has to name all of them, or exactly the low-precision ones (bf16/float16/float8/float4); one that names any T_array_* type all of them, or exactly vecf8/vecf4. Before, only a switch naming T_float32/T_array_float32 was checked, so float64-only and low-precision-only switches were not, and a later low-precision type would reach them unchecked. Subfamily members are discovered from types.go like the families. Three low-precision switches that read float4 in their default now give float4 its own case and fail in default (lowPrecisionCompare, the user variable setter, foldedScalarBytes), so a later member is not decoded as float4. The baseline gains the 20 switches the wider trigger finds (float64-only paths, fixed-schema ETL/export tables, vector-index paths). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ck on the GPU path (matrixorigin#20567) Measured with a temporary phase timer on the benchmark shape (MXFP8, dim 768, 1000 queries, 13970 tile rows): engine creation spent ~16 ms of its ~20 ms zero-filling host staging it never reads before writing (h_d_ ~56 MB, h_a_ ~11 MB); the cuBLASLt heuristics are cached by cuBLASLt and cost 0.04-4 ms. The staging is now allocated uninitialized (run zeroes each tile's rows, the score copy fills h_d_): ~20 ms -> 3.2 ms per engine. The GPU path no longer re-parses each vecf8/vecf4 cell: cells are validated where they are produced and when their column is loaded (objectio.validateVectorCacheData), and the GPU path checks the length. 1M x 768, 1000 queries, top 10, queries in a user variable: vecf4 0.58-0.64 s -> 0.37-0.47 s, vecf8 0.90-0.96 s -> 0.80-0.89 s, vecbf16 1.45-1.55 s -> 1.25-1.43 s. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…rixorigin#20567) Every metric over vecf32/vecbf16/vecf8/vecf4, queries in a user variable (execution) and inline (statement text included), recall unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…32 BLOB and cells compared (matrixorigin#20567) A query literal in the SQL text is embedded in the execution plan that statement_info records for statements over the long-query time (a 64 MB plan for 1,000 768-dim JSON queries, above the loader's 10 MB row); a user variable or prepared parameter keeps it out. Measured times for JSON text, a float32 BLOB and vecblock cells. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…matrixorigin#20567) matrixone.vecblock converts vecf8 (MXFP8) and vecf4 (NVFP4) cells to and from PyTorch FP8/FP4 tensors: from_cells/to_cells, to_float, quantize (the same cells as MatrixOne's CAST), the 128x4 blocked scale layout, and torch._scaled_mm. PyTorch is imported only by the tensor functions and is an optional extra: pip install 'matrixone-python-sdk[torch]'. Examples 35-38: load cells into tensors and a DataLoader, store tensors as cells, score cells with torch._scaled_mm (bit-identical to vector_matmul on the GPU), and fine-tune a projection with hard negatives mined by vector_matmul. Offline tests use reference cells from MatrixOne. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
matrixorigin#29554 landed on main as one squashed commit. The tree is main plus the Python SDK commit 7eecd56, with its examples renumbered to 36-39 after main's example_35_arrow_analytics.py; setup.py keeps main's form, the torch extra is in pyproject.toml. Co-Authored-By: Claude Opus 5.5 <[email protected]>
vecblock.scaled_mm multiplied the torch._scaled_mm output by the row and query global scales in float32, so vecf4 distances differed from vector_matmul on the GPU by up to 1 ulp (462/640 top-10 hits equal); the engine's fix-up kernel takes acc x g_row x g_query in double and rounds once. scaled_mm now does the same: example 38 is bit-identical for vecf8 and vecf4 (64/64 queries). test_scaled_mm_applies_global_scales_in_double fails without the fix. The design records the SDK's global-scale application and the measured bit identity, scoped to the same cuBLASLt algorithm. The examples' own numbers follow their renumbered file names (36-39). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
The offline contracts gate (scripts/run_contracts.py) fails on any skip. tests/offline/test_vecblock.py skipped as a module without PyTorch, which CI does not install, so every offline SDK job failed with all tests passing. The offline file now holds the tests that need no PyTorch (cell layout, SQL helpers) plus one that the tensor functions raise the install hint without it. The PyTorch and GPU tests move to tests/torch, which CI does not collect. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 711b626ad7b25b6016b6ae5789fa44cd41fff4a7
Assessment: request_changes
The stateless adapter appropriately reuses PyTorch and the existing cell format, but two reproduced CPU numerical mismatches violate the server codec’s contract.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
-
P2
clients/python/matrixone/vecblock.py:152: Decode a valid vecf4 cell whose global × block scale is subnormal, including the cell produced by quantizing [[2^-149]].
Impact: to_float() silently returns zero instead of 2^-149; other subnormal cells are misrounded. Mirror the server’s conditional float64 fallback while preserving ordinary float32 rounding, and add boundary regressions.
Evidence: Cell 0102000001000000010000002307 decoded to zero in the CPU probe. pkg/container/types/vecblock.go:437 defines the required fallback. Three cases reproduced this mismatch in vecblock-tests.log. -
P2
clients/python/matrixone/vecblock.py:240: Quantize positive or negative float32 maximum as vecf8.
Impact: The encoder returns cells decoding to infinity, which MatrixOne rejects. Validate decoded finiteness before returning and raise ValueError, preserving nearby finite inputs and vecf4’s supported range.
Evidence: CPU probes emitted 01010000010000000000803ff778 and its negative counterpart, decoding to ±Inf. The unchanged encoder guard at pkg/container/types/vecblock.go:240 and TestBlockScaledDecodedFinite explicitly reject this case.
Validation:
-
Reviewed all 11 changed files, relevant consumers and both discussion entries. Source remained unchanged; syntax, diff and evidence audits passed in checks/1793801622600464835-2.json.
-
Python 3.13.5/PyTorch 2.9.1+cpu: 29 cases selected; 22 passed, five failed across the two findings, and two GPU cases skipped. All 13 supplied CPU/offline cases passed. Receipt: checks/1793801262318076685-2.json; retained vecblock-tests.log and vecblock-tests.xml.
-
Frozen CI includes eight successful offline SDK jobs and two core-import jobs; its workflow does not select tests/torch.
Limitations:
- CUDA scaled_mm and live MatrixOne examples were not executed locally. Server rejection is established from frozen codec source and tests; supplied GPU/example results remain author reports.
to_float folded global * blockScale in float32 first. When that product is
subnormal, MatrixOne applies the global in float64 instead
(blockScaledElem), so the vecf4 cell of [2^-149] decoded to 0 instead of
2^-149 and other subnormal cells were misrounded. to_float now does the
same for those elements and keeps the float32 product for the rest.
quantize returned vecf8 cells that decode to +-Inf for inputs near the
float32 maximum, which MatrixOne rejects ("decodes to an infinite value").
It now raises ValueError for them, as the server encoder does.
Boundary regressions use cells taken from MatrixOne.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Both review findings are fixed in 320d8b0, and the fix was checked against a live MatrixOne server.
Validation
|
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 320d8b0aae42849b33236b41b9242cf85625d244
Assessment: approve
The stateless adapter reuses the accepted cell format, scale layout and PyTorch storage/GEMM without adding an engine or long-lived state. Both earlier numerical findings are resolved by the current source and local CPU checks. No actionable defect remains.
Model: gpt-6.1-sol / max
Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0
Validation:
-
Reviewed all 11 changed files, accepted format/design, server codec and CUDA scale-layout owners, examples, packaging and complete discussion.
-
Python 3.13.5/PyTorch 2.9.1+cpu: 17 supplied cases selected; 15 passed and two CUDA cases skipped. Both repaired numerical regressions passed. vecblock-tests.log/xml match checks/1793823986703796247-2.json, exit 0.
-
Independent scalar-format probe passed 40 exact encoding/decoding/roundtrip controls, four matching finite-persistence refusals and 650 scale-tile coordinates. codec-probe-finite.log matches checks/1793824075476157814-2.json, exit 0.
-
Local source audit passed frozen-head/clean-source, whitespace, Python 3.8 syntax, optional-import/extra, discussion coverage and receipt/log/XML checks; source-audit.log matches checks/1793824217467274149-2.json, exit 0.
-
Frozen CI: 13 successful, 15 skipped and two neutral checks, including eight SDK offline and two core-import jobs. The workflow excludes tests/torch.
-
Reused attributed current-head author evidence: 134-input live-server differential with zero mismatches, 17 GPU-enabled cases, offline contracts and examples 36–39.
Limitations:
- CUDA and live MatrixOne examples were not executed locally; two device tests were skipped. Supplied author GPU/server results were reused without embedded raw execution logs.
✅ Merged into
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #20567
What this PR does / why we need it:
Python SDK support for the
vecf8(MXFP8) /vecf4(NVFP4) columns added in #29554:matrixone.vecblockconverts between MatrixOne cells and PyTorch FP8 / FP4 tensors, plus four examples.matrixone/vecblock.py: split cells into element / block-scale / global-scale tensors (from_cells,to_cells), decode (to_float), quantize with MatrixOne's quantizer (quantize, byte-identical to the server's cells), the cuBLASLt tiled scale layout (to_blocked), SQL literals (cell_sql,blob_literal), andscaled_mm, which runstorch._scaled_mmon the cells and applies the global scales as the engine's fix-up kernel does (fp32 GEMM output ×g_row×g_queryin double, rounded once).examples/README.md):example_36_pytorch_load_vecblock.py: load vecf8 / vecf4 columns into FP8 / FP4 tensors and stream a table into a training loop.example_37_pytorch_store_vecblock.py: quantize in PyTorch and store the cells byte-identical.example_38_pytorch_gpu_scaled_mm.py: score the cells withtorch._scaled_mmand compare withvector_matmulon the GPU (needs a Blackwell GPU).example_39_pytorch_finetune_hard_negatives.py: fine-tune a projection on hard negatives mined byvector_matmul.pip install 'matrixone-python-sdk[torch]'(torch>=2.9). PyTorch is imported only when a tensor function is called; the examples skip themselves without it.tests/offline/test_vecblock.py: reference cells produced by MatrixOne, decode / quantize / round-trip / layout / SQL helpers; two GPU tests (skipped without block-scaledtorch._scaled_mm).docs/design/20260930-low-precision-vector-storage.md: one paragraph on howscaled_mmapplies the global scales and the measured agreement withvector_matmul.Validation
Server built from this head (
MO_CL_CUDA=1, fresh data dir), PyTorch 2.9.1+cu130, NVIDIA GeForce RTX 5070 Laptop GPU (sm_120):pytest tests/offline/test_vecblock.pytorch._scaled_mmvsvector_matmul,gpu_mode = 1)flake8,black --check(project config)Example 38 first failed for vecf4:
scaled_mmmultiplied the global scales in float32, so 178 of 640 top-10 distances differed fromvector_matmulby 1 ulp.scaled_mmnow applies them in double as the engine does;test_scaled_mm_applies_global_scales_in_doublefails without that change.example 38 output
🤖 Generated with Claude Code