FZGPUModules 2.0
GPU-accelerated modular compression pipelines
Loading...
Searching...
No Matches
lorenzo_quant.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "stage/stage.h"
8#include "fzm_format.h"
9#include "backend/types.h"
10#include "log.h"
12
13#include <array>
14#include <cstdint>
15#include <memory>
16#include <cmath>
17#include <cstring>
18
19namespace fz {
20
21
42enum class ErrorBoundMode : uint8_t {
43 ABS = 0,
44 REL = 1,
45 NOA = 2,
46 PREL = 3,
47};
48
63inline ErrorBoundMode resolveApproxRelMode(ErrorBoundMode mode, const char* stage_name) {
64 if (mode != ErrorBoundMode::REL) return mode;
66 "%s: ErrorBoundMode::REL is deprecated for this stage and has been "
67 "mapped to PREL (abs_eb = eb * max(|data|)). This does NOT guarantee a "
68 "per-element relative bound. Use PREL explicitly to silence this, or "
69 "QuantizerStage with REL for an exact point-wise bound.",
70 stage_name);
72}
73
83 uint32_t quant_radius;
84 uint32_t num_elements;
85 uint32_t outlier_count;
88 uint8_t ndim;
89 uint8_t eb_mode;
90 uint32_t dim_x;
91 uint32_t dim_y;
92 uint32_t dim_z;
93 float user_eb;
94 float value_base;
95 uint8_t zigzag_codes;
96 uint8_t centering;
97 uint8_t reserved[2];
106
107 // Total: 60 bytes (fits easily in 128B stage_config)
108
111 input_type(DataType::FLOAT32), code_type(DataType::UINT16),
112 ndim(1), eb_mode(0), dim_x(0), dim_y(1), dim_z(1),
113 user_eb(0.0f), value_base(0.0f), zigzag_codes(0), centering(0),
114 reserved{0, 0}, error_bound_f64(0.0), value_base_f64(0.0) {}
115};
116static_assert(sizeof(LorenzoQuantConfig) <= FZM_STAGE_CONFIG_SIZE, "LorenzoQuantConfig must fit in FZM_STAGE_CONFIG_SIZE");
117
145template<typename TInput = float, typename TCode = uint16_t>
146class LorenzoQuantStage : public Stage {
147public:
149 struct Config {
150 float error_bound = 1e-3;
151 int quant_radius = 32768;
152 float outlier_capacity = 0.2f;
156 std::array<size_t, 3> dims = {0, 1, 1};
166 bool zigzag_codes = false;
175 bool centering = false;
176 Config() = default;
177 Config(TInput eb, TCode radius = 32768, float outlier_cap = 0.2f,
178 std::array<size_t, 3> d = {0, 1, 1})
179 : error_bound(eb), quant_radius(radius), outlier_capacity(outlier_cap),
180 dims(d) {}
181 };
182
183 explicit LorenzoQuantStage(const Config& config = Config());
184 ~LorenzoQuantStage() override;
185
187 fz::stream_t stream,
188 MemoryPool* pool,
189 const std::vector<void*>& inputs,
190 const std::vector<void*>& outputs,
191 const std::vector<size_t>& sizes
192 ) override;
193
199 void postStreamSync(fz::stream_t stream) override;
200
205 void onFinalize(size_t estimated_inlen, MemoryPool* pool) override;
206
207 size_t estimateDeviceFootprintBytes(size_t /*estimated_inlen*/) const override {
208 return sizeof(uint32_t);
209 }
210
211 std::string getName() const override { return "LorenzoQuant"; }
212 size_t getNumInputs() const override {
213 return is_inverse_ ? (config_.centering ? 4 : 3) : 1;
214 }
215 size_t getNumOutputs() const override {
216 return is_inverse_ ? 1 : (config_.centering ? 4 : 3);
217 }
218
219 std::vector<std::string> getOutputNames() const override {
220 if (config_.centering)
221 return {"codes", "outlier_errors", "outlier_indices", "means"};
222 return {"codes", "outlier_errors", "outlier_indices"};
223 }
224
225 std::vector<size_t> estimateOutputSizes(
226 const std::vector<size_t>& input_sizes
227 ) const override;
228
229 std::unordered_map<std::string, size_t> getActualOutputSizesByName() const override {
230 auto names = getOutputNames();
231 std::unordered_map<std::string, size_t> result;
232 for (size_t i = 0; i < names.size() && i < actual_output_sizes_.size(); i++) {
233 result[names[i]] = actual_output_sizes_[i];
234 }
235 return result;
236 }
237 size_t getActualOutputSize(int index) const override {
238 return (index >= 0 && index < static_cast<int>(actual_output_sizes_.size()))
239 ? actual_output_sizes_[index] : 0;
240 }
241
242 // Preserve the forward-mode actual_output_sizes_ across decompression passes.
243 // decompressMulti() calls saveState()/restoreState() around each inverse
244 // execute() to prevent the inverse pass from permanently corrupting the
245 // 4-element forward output-size vector (inverse sets it to a 1-element vector).
246 void saveState() override { saved_output_sizes_ = actual_output_sizes_; }
247 void restoreState() override { actual_output_sizes_ = saved_output_sizes_; }
248
249 // Configuration accessors
250 void setErrorBound(TInput error_bound) { config_.error_bound = error_bound; }
251 void setQuantRadius(TCode radius) { config_.quant_radius = radius; }
252 void setOutlierCapacity(float capacity) { config_.outlier_capacity = capacity; }
253 void setDims(const std::array<size_t, 3>& dims) override { config_.dims = dims; }
259 config_.eb_mode = resolveApproxRelMode(mode, "LorenzoQuantStage");
260 }
261 // Provide a pre-computed value_range (NOA) or max(|data|) (PREL) to skip
262 // the internal data scan during execute(). Pass 0 to re-enable auto-scan.
263 void setValueBase(float value_base) { config_.precomputed_value_base = value_base; }
264 void setZigzagCodes(bool enable) { config_.zigzag_codes = enable; }
269 void setCentering(bool enable) { config_.centering = enable; }
270 void setDims(size_t x, size_t y = 1, size_t z = 1) { config_.dims = {x, y, z}; }
271
272 TInput getErrorBound() const { return config_.error_bound; }
273 TCode getQuantRadius() const { return config_.quant_radius; }
274 float getOutlierCapacity() const { return config_.outlier_capacity; }
275 std::array<size_t, 3> getDims() const { return config_.dims; }
276 ErrorBoundMode getErrorBoundMode() const { return config_.eb_mode; }
281 TInput getComputedAbsErrorBound() const { return computed_abs_eb_; }
282 float getValueBase() const { return config_.precomputed_value_base; }
283 bool getZigzagCodes() const { return config_.zigzag_codes; }
284 bool getCentering() const { return config_.centering; }
285
287 int ndim() const {
288 if (config_.dims[2] > 1) return 3;
289 if (config_.dims[1] > 1) return 2;
290 return 1;
291 }
292
293 void setInverse(bool inverse) { is_inverse_ = inverse; }
294 bool isInverse() const { return is_inverse_; }
295
296 // ── Serialization ─────────────────────────────────────────────────────────
297
298 uint16_t getStageTypeId() const override {
299 return static_cast<uint16_t>(StageType::LORENZO_QUANT);
300 }
301
302 uint8_t getOutputDataType(size_t output_index) const override {
303 switch (output_index) {
304 case 0: return static_cast<uint8_t>(getCodeDataType()); // codes
305 case 1: return static_cast<uint8_t>(getInputDataType()); // outlier_errors
306 case 2: return static_cast<uint8_t>(DataType::UINT32); // outlier_indices
307 default: return static_cast<uint8_t>(DataType::UINT8);
308 }
309 }
310
311 uint8_t getInputDataType(size_t /*input_index*/) const override {
312 return static_cast<uint8_t>(getInputDataType());
313 }
314
315 size_t serializeHeader(size_t output_index, uint8_t* header_buffer, size_t max_size) const override {
316 (void)output_index; // Lorenzo uses same header for all outputs
317
318 if (max_size < sizeof(LorenzoQuantConfig)) {
319 throw std::runtime_error("Insufficient buffer for Lorenzo config");
320 }
321
322 LorenzoQuantConfig config;
323 config.error_bound = static_cast<float>(computed_abs_eb_); // abs bound used by decompressor
324 config.quant_radius = static_cast<uint32_t>(config_.quant_radius);
325 config.num_elements = static_cast<uint32_t>(num_elements_);
326 config.outlier_count = actual_outlier_count_;
327 config.input_type = getInputDataType();
328 config.code_type = getCodeDataType();
329 config.ndim = static_cast<uint8_t>(ndim());
330 config.eb_mode = static_cast<uint8_t>(config_.eb_mode);
331 config.dim_x = static_cast<uint32_t>(config_.dims[0]);
332 config.dim_y = static_cast<uint32_t>(config_.dims[1]);
333 config.dim_z = static_cast<uint32_t>(config_.dims[2]);
334 config.user_eb = static_cast<float>(config_.error_bound); // original user-specified value
335 config.value_base = static_cast<float>(computed_value_base_);
336 config.error_bound_f64 = static_cast<double>(computed_abs_eb_);
337 config.value_base_f64 = static_cast<double>(computed_value_base_);
338 config.zigzag_codes = config_.zigzag_codes ? uint8_t{1} : uint8_t{0};
339 config.centering = config_.centering ? uint8_t{1} : uint8_t{0};
340 config.reserved[0] = 0; config.reserved[1] = 0;
341
342 std::memcpy(header_buffer, &config, sizeof(LorenzoQuantConfig));
343 return sizeof(LorenzoQuantConfig);
344 }
345
346 size_t getMaxHeaderSize(size_t output_index) const override {
347 (void)output_index;
348 return sizeof(LorenzoQuantConfig);
349 }
350
351 void deserializeHeader(const uint8_t* header_buffer, size_t size) override {
352 // Minimum size is the original 32-byte layout (before user_eb/value_base were added).
353 constexpr size_t kLegacySize = 32;
354 if (size < kLegacySize) {
355 throw std::runtime_error("Invalid Lorenzo config size");
356 }
357
358 LorenzoQuantConfig config;
359 std::memcpy(&config, header_buffer, std::min(size, sizeof(LorenzoQuantConfig)));
360
361 // error_bound in the header is always the absolute bound used at compression.
362 // Prefer the full-precision copy; pre-2026-08-08 headers leave it 0.
363 constexpr size_t kSizeBeforeF64 = 44;
364 const bool has_f64 = (size > kSizeBeforeF64 && config.error_bound_f64 != 0.0);
365 config_.error_bound = config.error_bound;
366 computed_abs_eb_ = has_f64 ? static_cast<TInput>(config.error_bound_f64)
367 : static_cast<TInput>(config.error_bound);
368 config_.quant_radius = static_cast<TCode>(config.quant_radius);
369 num_elements_ = config.num_elements;
370 actual_outlier_count_= config.outlier_count;
371 // New fields: present only in headers written by v1+ (≥40B, added user_eb/value_base/eb_mode).
372 constexpr size_t kV1Size = 40;
373 if (size >= kV1Size) {
374 // Files written before the PREL split stored eb_mode==REL for what
375 // was always the approximate mode. Map it silently (no warning —
376 // decode uses the stored absolute error_bound regardless of mode).
377 auto stored = static_cast<ErrorBoundMode>(config.eb_mode);
378 config_.eb_mode = (stored == ErrorBoundMode::REL)
379 ? ErrorBoundMode::PREL : stored;
380 config_.precomputed_value_base = config.value_base;
381 computed_value_base_ = has_f64
382 ? static_cast<TInput>(config.value_base_f64)
383 : static_cast<TInput>(config.value_base);
384 } else {
386 config_.precomputed_value_base = 0.0f;
387 computed_value_base_ = static_cast<TInput>(0);
388 }
389 // zigzag_codes field added in v2 (≥44B). Compared against the literal v2
390 // size, not sizeof(LorenzoQuantConfig) — the struct has grown since (the
391 // f64 bound fields), and keying off sizeof would stop reading these
392 // fields from every v2 archive.
393 constexpr size_t kV2Size = 44;
394 if (size >= kV2Size) {
395 config_.zigzag_codes = (config.zigzag_codes != 0);
396 // `centering` reuses a byte older writers zeroed as `reserved`, so
397 // pre-centering archives decode as centering-off.
398 config_.centering = (config.centering != 0);
399 } else {
400 config_.zigzag_codes = false;
401 config_.centering = false;
402 }
403
404 // Restore spatial dimensions; handle old (pre-dims) files gracefully
405 int eff_ndim = (config.ndim == 0) ? 1 : static_cast<int>(config.ndim);
406 // dim_x: stored explicitly; fall back to derivation for old files
407 if (config.dim_x > 0) {
408 config_.dims[0] = config.dim_x;
409 } else if (config.num_elements > 0) {
410 size_t yz = std::max<size_t>(1, config.dim_y) * std::max<size_t>(1, config.dim_z);
411 config_.dims[0] = config.num_elements / yz;
412 } else {
413 config_.dims[0] = 0;
414 }
415 if (eff_ndim >= 2) {
416 config_.dims[1] = (config.dim_y > 0) ? config.dim_y : 1;
417 } else {
418 config_.dims[1] = 1;
419 }
420 if (eff_ndim >= 3) {
421 config_.dims[2] = (config.dim_z > 0) ? config.dim_z : 1;
422 } else {
423 config_.dims[2] = 1;
424 }
425 }
426
427private:
428 Config config_;
429 std::vector<size_t> actual_output_sizes_;
430 std::vector<size_t> saved_output_sizes_; // saved by saveState(), restored by restoreState()
431 size_t num_elements_ = 0; // Track for header
432 uint32_t actual_outlier_count_ = 0; // Track for header
433 bool is_inverse_ = false; // false = compress, true = decompress
437 TInput computed_abs_eb_ = 0;
440 TInput computed_value_base_ = static_cast<TInput>(0);
447 uint32_t* d_outlier_count_scratch_ = nullptr;
450 MemoryPool* persistent_pool_ = nullptr;
455 std::weak_ptr<const void> persistent_pool_alive_;
456
457
460 void initOutlierCountScratch(MemoryPool* pool);
461
462 DataType getInputDataType() const { return fused::dataTypeOf<TInput>(); }
463 DataType getCodeDataType() const { return fused::dataTypeOf<TCode>(); }
464
465 size_t getMaxOutlierCount(size_t num_elements) const {
466 return static_cast<size_t>(std::ceil(num_elements * config_.outlier_capacity));
467 }
468};
469
470extern template class LorenzoQuantStage<float, uint16_t>;
471extern template class LorenzoQuantStage<float, uint8_t>;
472extern template class LorenzoQuantStage<double, uint16_t>;
473extern template class LorenzoQuantStage<double, uint32_t>;
474
475// Kernel launcher declarations — defined in lorenzo.cu.
476
477template<typename TInput, typename TCode>
478void launchLorenzoKernel(
479 const TInput* d_input, size_t n,
480 TInput ebx2_r, TCode quant_radius,
481 TCode* d_codes, TInput* d_outlier_errors,
482 uint32_t* d_outlier_indices, uint32_t* d_outlier_count,
483 size_t max_outliers, int grid_size,
484 bool zigzag_codes,
485 fz::stream_t stream,
486 // Per-tile means output (one per 1024-element tile), or nullptr to disable
487 // adaptive centering.
488 TInput* d_means = nullptr
489);
490
491template<typename TInput, typename TCode>
492void launchLorenzoInverseKernel(
493 const TCode* d_codes,
494 const TInput* d_outlier_errors, const uint32_t* d_outlier_indices,
495 uint32_t outlier_n,
496 size_t n,
497 TInput ebx2, TCode quant_radius,
498 TInput* d_output,
499 bool zigzag_codes,
500 fz::stream_t stream, MemoryPool* pool,
501 // Per-tile means from the forward pass, or nullptr if centering is off.
502 const TInput* d_means = nullptr
503);
504
506template<typename TInput, typename TCode>
508 const TInput* d_input, size_t nx, size_t ny,
509 TInput ebx2_r, TCode quant_radius,
510 TCode* d_codes, TInput* d_outlier_errors,
511 uint32_t* d_outlier_indices, uint32_t* d_outlier_count,
512 size_t max_outliers,
513 bool zigzag_codes,
514 fz::stream_t stream
515);
516
518template<typename TInput, typename TCode>
520 const TCode* d_codes,
521 const TInput* d_outlier_errors, const uint32_t* d_outlier_indices,
522 uint32_t outlier_n,
523 size_t nx, size_t ny,
524 TInput ebx2, TCode quant_radius,
525 TInput* d_output,
526 bool zigzag_codes,
527 fz::stream_t stream, MemoryPool* pool
528);
529
531template<typename TInput, typename TCode>
533 const TInput* d_input, size_t nx, size_t ny, size_t nz,
534 TInput ebx2_r, TCode quant_radius,
535 TCode* d_codes, TInput* d_outlier_errors,
536 uint32_t* d_outlier_indices, uint32_t* d_outlier_count,
537 size_t max_outliers,
538 bool zigzag_codes,
539 fz::stream_t stream
540);
541
543template<typename TInput, typename TCode>
545 const TCode* d_codes,
546 const TInput* d_outlier_errors, const uint32_t* d_outlier_indices,
547 uint32_t outlier_n,
548 size_t nx, size_t ny, size_t nz,
549 TInput ebx2, TCode quant_radius,
550 TInput* d_output,
551 bool zigzag_codes,
552 fz::stream_t stream, MemoryPool* pool
553);
554
555} // namespace fz
Definition lorenzo_quant.h:146
std::unordered_map< std::string, size_t > getActualOutputSizesByName() const override
Definition lorenzo_quant.h:229
int ndim() const
Returns the effective spatial dimensionality (1, 2, or 3).
Definition lorenzo_quant.h:287
void postStreamSync(fz::stream_t stream) override
uint8_t getOutputDataType(size_t output_index) const override
Definition lorenzo_quant.h:302
uint16_t getStageTypeId() const override
Definition lorenzo_quant.h:298
void setCentering(bool enable)
Definition lorenzo_quant.h:269
void setErrorBoundMode(ErrorBoundMode mode)
Definition lorenzo_quant.h:258
size_t getActualOutputSize(int index) const override
Definition lorenzo_quant.h:237
void saveState() override
Definition lorenzo_quant.h:246
size_t serializeHeader(size_t output_index, uint8_t *header_buffer, size_t max_size) const override
Definition lorenzo_quant.h:315
void execute(fz::stream_t stream, MemoryPool *pool, const std::vector< void * > &inputs, const std::vector< void * > &outputs, const std::vector< size_t > &sizes) override
size_t getMaxHeaderSize(size_t output_index) const override
Definition lorenzo_quant.h:346
size_t estimateDeviceFootprintBytes(size_t) const override
Definition lorenzo_quant.h:207
std::string getName() const override
Definition lorenzo_quant.h:211
uint8_t getInputDataType(size_t) const override
Definition lorenzo_quant.h:311
void deserializeHeader(const uint8_t *header_buffer, size_t size) override
Definition lorenzo_quant.h:351
std::vector< std::string > getOutputNames() const override
Definition lorenzo_quant.h:219
void onFinalize(size_t estimated_inlen, MemoryPool *pool) override
void setDims(const std::array< size_t, 3 > &dims) override
Definition lorenzo_quant.h:253
void setInverse(bool inverse)
Definition lorenzo_quant.h:293
std::vector< size_t > estimateOutputSizes(const std::vector< size_t > &input_sizes) const override
TInput getComputedAbsErrorBound() const
Definition lorenzo_quant.h:281
Definition mempool.h:82
Definition stage.h:31
Compile-time C++ type -> DataType enum mapping, shared by the fused stages that dispatch on multiple ...
FZM binary file format definitions — structs, enums, and helpers.
Logging infrastructure and macros.
#define FZ_LOG(level,...)
Definition log.h:201
Definition dag.h:24
void launchLorenzoKernel3D(const TInput *d_input, size_t nx, size_t ny, size_t nz, TInput ebx2_r, TCode quant_radius, TCode *d_codes, TInput *d_outlier_errors, uint32_t *d_outlier_indices, uint32_t *d_outlier_count, size_t max_outliers, bool zigzag_codes, fz::stream_t stream)
3-D forward Lorenzo kernel launcher.
ErrorBoundMode
Definition lorenzo_quant.h:42
@ PREL
Pseudo-relative: eb × max(|data|), applied as a single ABS bound.
@ ABS
Absolute error bound.
@ REL
Exact per-element point-wise relative bound (QuantizerStage only).
ErrorBoundMode resolveApproxRelMode(ErrorBoundMode mode, const char *stage_name)
Definition lorenzo_quant.h:63
void launchLorenzoKernel2D(const TInput *d_input, size_t nx, size_t ny, TInput ebx2_r, TCode quant_radius, TCode *d_codes, TInput *d_outlier_errors, uint32_t *d_outlier_indices, uint32_t *d_outlier_count, size_t max_outliers, bool zigzag_codes, fz::stream_t stream)
2-D forward Lorenzo kernel launcher. nx is the fast (x) dimension.
constexpr size_t FZM_STAGE_CONFIG_SIZE
Per-stage serialized config slot (bytes)
Definition fzm_format.h:65
DataType
Element data type identifiers used in buffer and stage descriptors.
Definition fzm_format.h:142
void launchLorenzoInverseKernel3D(const TCode *d_codes, const TInput *d_outlier_errors, const uint32_t *d_outlier_indices, uint32_t outlier_n, size_t nx, size_t ny, size_t nz, TInput ebx2, TCode quant_radius, TInput *d_output, bool zigzag_codes, fz::stream_t stream, MemoryPool *pool)
3-D inverse Lorenzo kernel launcher.
@ WARN
Unexpected but recoverable: outlier overflow, fallbacks.
void launchLorenzoInverseKernel2D(const TCode *d_codes, const TInput *d_outlier_errors, const uint32_t *d_outlier_indices, uint32_t outlier_n, size_t nx, size_t ny, TInput ebx2, TCode quant_radius, TInput *d_output, bool zigzag_codes, fz::stream_t stream, MemoryPool *pool)
2-D inverse Lorenzo kernel launcher.
Base class interface for all compression stages.
Definition lorenzo_quant.h:81
uint8_t zigzag_codes
1 if codes are zigzag-encoded, else 0.
Definition lorenzo_quant.h:95
float value_base
value_range (NOA) or max(|data|) (REL) used in conversion.
Definition lorenzo_quant.h:94
uint8_t centering
1 if per-tile mean centering is enabled, else 0.
Definition lorenzo_quant.h:96
DataType input_type
Original input type (1B).
Definition lorenzo_quant.h:86
uint32_t quant_radius
Quantization radius.
Definition lorenzo_quant.h:83
float error_bound
Absolute bound after mode conversion (used by decompressor).
Definition lorenzo_quant.h:82
uint8_t eb_mode
ErrorBoundMode cast to uint8_t.
Definition lorenzo_quant.h:89
uint32_t num_elements
Total element count.
Definition lorenzo_quant.h:84
uint8_t ndim
Spatial dimensionality 1/2/3 (0 treated as 1).
Definition lorenzo_quant.h:88
double value_base_f64
Full-precision value_base; 0 in pre-2026-08-08 headers.
Definition lorenzo_quant.h:105
double error_bound_f64
Definition lorenzo_quant.h:104
uint32_t dim_z
Z dimension (1 for 1-D/2-D).
Definition lorenzo_quant.h:92
uint8_t reserved[2]
Definition lorenzo_quant.h:97
DataType code_type
Quantization code type (1B).
Definition lorenzo_quant.h:87
uint32_t dim_y
Y dimension (1 for 1-D).
Definition lorenzo_quant.h:91
uint32_t outlier_count
Actual number of outliers.
Definition lorenzo_quant.h:85
float user_eb
Original user-specified error bound value.
Definition lorenzo_quant.h:93
uint32_t dim_x
X (fast) dimension; 0 = infer from num_elements.
Definition lorenzo_quant.h:90
Definition lorenzo_quant.h:149
int quant_radius
Quantization radius (2^15 for uint16_t).
Definition lorenzo_quant.h:151
ErrorBoundMode eb_mode
Definition lorenzo_quant.h:160
float error_bound
Error bound (interpretation depends on eb_mode).
Definition lorenzo_quant.h:150
bool zigzag_codes
Definition lorenzo_quant.h:166
float outlier_capacity
Definition lorenzo_quant.h:152
float precomputed_value_base
Definition lorenzo_quant.h:163
bool centering
Definition lorenzo_quant.h:175
std::array< size_t, 3 > dims
Definition lorenzo_quant.h:156
Backend-neutral GPU type aliases.