FZGPUModules 2.0
GPU-accelerated modular compression pipelines
Loading...
Searching...
No Matches
huffman_stage.h
Go to the documentation of this file.
1#pragma once
2
27
28#include "stage/stage.h"
29#include "fzm_format.h"
30#include "coders/huffman/phf/hf.h" // phf_header, phf_stream_t
31
32#include "backend/types.h"
33#include <cstdint>
34#include <cstring>
35#include <memory>
36#include <stdexcept>
37#include <string>
38#include <type_traits>
39#include <unordered_map>
40#include <vector>
41
42// Forward-declare phf::Buf<T> to avoid pulling hf_buf.h (CUDA-only) into this header.
43// HuffmanStage<T>::~HuffmanStage() is defined in huffman_stage.cu where the type is complete.
44namespace phf { template<typename E> struct Buf; }
45
46namespace fz {
47
53
73
81
94 double center = -1.0;
97 double scale = 32.0;
99 double shape = 2.0;
100};
101
118template <typename T>
119class HuffmanStage : public Stage {
121 static_assert(
122 std::is_same_v<T, uint8_t> ||
123 std::is_same_v<T, uint16_t> ||
124 std::is_same_v<T, uint32_t>,
125 "HuffmanStage: T must be uint8_t, uint16_t, or uint32_t.");
127
128public:
129 // __host__-only: HIP's clang infers __host__ __device__ for defaulted
130 // special members by default, but ~unique_ptr<phf::Buf<T>> (the type this
131 // destructor implicitly invokes, defined in huffman_stage.cu) is
132 // host-only, so that inference fails to compile under HIP. Neither
133 // function touches device code at all — pin them host-only explicitly.
134 __host__ HuffmanStage();
135 __host__ ~HuffmanStage() override;
136
137 // ── Configuration ─────────────────────────────────────────────────────────
138
170 void setBklen(uint32_t bklen) {
171 constexpr uint32_t kMul = (4u / sizeof(T)) ? (4u / sizeof(T)) : 1u;
172 uint32_t rounded = ((bklen + kMul - 1u) / kMul) * kMul;
173 // bklen_ is stored uint16_t in the serialized header (see the file
174 // comment above) and threaded as uint16_t through the histogram
175 // kernel API end to end. 65536 itself would silently wrap to 0 at
176 // that boundary — validate here instead of producing a corrupt or
177 // crashing stage.
178 if (rounded > 0xFFFFu)
179 throw std::invalid_argument(
180 "HuffmanStage::setBklen: bklen (after rounding, " + std::to_string(rounded) +
181 ") exceeds 65535 — bklen_ is a uint16_t end to end (serialized header and "
182 "histogram kernel API), so the full symbol range of a 16+ bit type cannot be "
183 "histogrammed in one pass. Reduce the upstream quant_radius/code range, or "
184 "split the input across multiple Huffman stages.");
185 bklen_ = rounded;
186 }
187 uint32_t getBklen() const { return bklen_; }
188
197 void setExecutionMode(HuffmanExecutionMode mode) { execution_mode_ = mode; }
198 HuffmanExecutionMode getExecutionMode() const { return execution_mode_; }
199
200 // ── Pre-built codebooks ───────────────────────────────────────────────────
201
213 void setBookSource(HuffmanBookSource src) { book_source_ = src; }
214 HuffmanBookSource getBookSource() const { return book_source_; }
215
233 void setFixedBookFromFreq(const uint32_t* h_freq, uint32_t n);
234
244
266 void setValidateSymbolRange(bool on) { validate_symbol_range_ = on; }
267 bool getValidateSymbolRange() const { return validate_symbol_range_; }
268
270 const std::vector<uint32_t>& getFixedBookFreq() const { return fixed_freq_; }
271
288 void setAdaptiveFloorShift(uint8_t shift) { adaptive_floor_shift_ = shift; }
289 uint8_t getAdaptiveFloorShift() const { return adaptive_floor_shift_; }
290
293 uint8_t getAdaptiveFloorShiftUsed() const { return adaptive_shift_used_; }
294
306 bool getAdaptiveFallbackUsed() const { return adaptive_fallback_; }
307
311 std::vector<std::string> getRunNotes() const override {
312 if (adaptive_fallback_) return {"huffman_adaptive_fallback"};
313 return {};
314 }
315
333 void setRefitThreshold(float ratio) { refit_threshold_ = ratio; }
334 float getRefitThreshold() const { return refit_threshold_; }
335
354 void setRefitInterval(uint32_t n) { refit_interval_ = n; }
355 uint32_t getRefitInterval() const { return refit_interval_; }
356
360 uint32_t getRefitCount() const { return refit_count_; }
361
365 double getFitBitsPerSymbol() const { return fit_bits_per_sym_; }
366
370 bool hasBookSpec() const { return has_book_spec_; }
371 const HuffmanBookSpec& getBookSpec() const { return book_spec_; }
372
373 // ── Stage control ─────────────────────────────────────────────────────────
374 void setInverse(bool inv) override { is_inverse_ = inv; }
375 bool isInverse() const override { return is_inverse_; }
376
377 void setTerminalOutput(bool terminal) override { is_terminal_output_ = terminal; }
378
379 void postStreamSync(fz::stream_t stream) override;
380
381 // ── Pool lifecycle ────────────────────────────────────────────────────────
382
391 void onFinalize(size_t estimated_inlen, MemoryPool* pool) override;
392
393 size_t estimateDeviceFootprintBytes(size_t inlen) const override;
394 size_t estimatePinnedFootprintBytes(size_t inlen) const override;
395
396 // ── Execution ─────────────────────────────────────────────────────────────
398 fz::stream_t stream,
399 MemoryPool* pool,
400 const std::vector<void*>& inputs,
401 const std::vector<void*>& outputs,
402 const std::vector<size_t>& sizes
403 ) override;
404
405 // ── Metadata ──────────────────────────────────────────────────────────────
406 std::string getName() const override { return "Huffman"; }
407 size_t getNumInputs() const override { return 1; }
408 size_t getNumOutputs()const override { return 1; }
409
410 std::vector<size_t> estimateOutputSizes(
411 const std::vector<size_t>& input_sizes
412 ) const override {
413 if (input_sizes.empty()) return {0};
414 if (!is_inverse_) {
415 const size_t n = input_sizes[0] / sizeof(T);
416 if (n == 0) return {0};
417 const size_t sublen = capi_phf_coarse_tune_sublen(n);
418 const size_t pardeg = (n - 1) / sublen + 1;
419 constexpr size_t kMaxCodeBits = 27;
420 constexpr size_t kCellBits = 32;
421 const size_t cells_per_partition =
422 (sublen * kMaxCodeBits + kCellBits - 1) / kCellBits;
423 const size_t bitstream_bytes = pardeg * cells_per_partition * sizeof(uint32_t);
424 const size_t reverse_book_bytes =
425 phf_reverse_book_bytes(static_cast<uint16_t>(bklen_), 4, sizeof(T));
426 return {PHFHEADER_FORCED_ALIGN + reverse_book_bytes
427 + 2 * pardeg * sizeof(PHF_METADATA) + bitstream_bytes};
428 }
429 // Inverse: exact decoded size restored from the serialized header.
430 return {original_len_ * sizeof(T)};
431 }
432
433 std::unordered_map<std::string, size_t>
434 getActualOutputSizesByName() const override {
435 return {{"output", actual_output_size_}};
436 }
437
438 size_t getActualOutputSize(int index) const override {
439 return (index == 0) ? actual_output_size_ : 0;
440 }
441
442 // ── Type system ───────────────────────────────────────────────────────────
443 uint16_t getStageTypeId() const override {
444 return static_cast<uint16_t>(StageType::HUFFMAN);
445 }
446
447 // Byte-transparent output: opt out of pipeline type-compatibility checking.
448 uint8_t getOutputDataType(size_t /*output_index*/) const override {
449 return static_cast<uint8_t>(DataType::UNKNOWN);
450 }
451 uint8_t getInputDataType(size_t /*input_index*/) const override {
452 return static_cast<uint8_t>(DataType::UNKNOWN);
453 }
454
455 // ── Serialization ─────────────────────────────────────────────────────────
457 size_t /*output_index*/, uint8_t* buf, size_t max_size
458 ) const override {
459 if (max_size < 11) return 0;
460 buf[0] = static_cast<uint8_t>(dataTypeOf<T>());
461 uint16_t bk = static_cast<uint16_t>(bklen_);
462 std::memcpy(buf + 1, &bk, sizeof(uint16_t));
463 std::memcpy(buf + 3, &original_len_, sizeof(uint64_t));
464 return 11;
465 }
466
467 void deserializeHeader(const uint8_t* buf, size_t size) override {
468 if (size >= 3) {
469 uint16_t bk;
470 std::memcpy(&bk, buf + 1, sizeof(uint16_t));
471 // Take the archive's bklen verbatim — NOT through setBklen(). Decode has
472 // to reproduce the layout the encoder actually used, so rounding here
473 // would describe a different reverse codebook than the one in the stream.
474 //
475 // But an archive written before setBklen enforced 4-byte alignment can
476 // carry a bklen that puts the bitstream at a non-4 offset, and the decode
477 // kernel reads it as uint32*. That does not merely decode wrong: it
478 // poisons the CUDA context, and every later allocation in the process
479 // fails with "misaligned address" — a failure that points nowhere near
480 // this stage. Refuse it here, where the cause is still legible.
481 if ((sizeof(T) * static_cast<size_t>(bk)) % 4u != 0)
482 throw std::runtime_error(
483 "HuffmanStage: archive declares bklen=" + std::to_string(bk) +
484 " with a " + std::to_string(sizeof(T)) + "-byte symbol, which puts "
485 "the bitstream at a non-4-byte offset. Such archives were written "
486 "by a build predating the alignment fix and cannot be decoded "
487 "correctly — the stream itself is malformed, not just this reader.");
488 bklen_ = bk;
489 }
490 if (size >= 11)
491 std::memcpy(&original_len_, buf + 3, sizeof(uint64_t));
492 }
493
494 size_t getMaxHeaderSize(size_t /*output_index*/) const override { return 11; }
495
496 void saveState() override {
497 saved_bklen_ = bklen_;
498 saved_original_len_ = original_len_;
499 saved_output_size_ = actual_output_size_;
500 }
501
502 void restoreState() override {
503 bklen_ = saved_bklen_;
504 original_len_ = saved_original_len_;
505 actual_output_size_ = saved_output_size_;
506 }
507
508private:
509 bool is_inverse_ = false;
510 uint32_t bklen_ = defaultBklen();
513
514 // Frequency table defining the fixed codebook (host-only; see setFixedBookFromFreq).
515 std::vector<uint32_t> fixed_freq_;
516 // Model that generated fixed_freq_, when it came from setFixedBookFromModel().
517 HuffmanBookSpec book_spec_ {};
518 bool has_book_spec_ = false;
519 uint8_t adaptive_floor_shift_ = 24;
520 uint8_t adaptive_shift_used_ = 24;
525 bool adaptive_fallback_ = false;
526
527 // Refit bookkeeping (Adaptive only).
528 float refit_threshold_ = 1.2f;
529 bool validate_symbol_range_ = true;
530 uint32_t refit_interval_ = 0; // 0 = only the bit-rate trigger
531 uint32_t calls_since_fit_ = 0;
532 double fit_bits_per_sym_ = 0.0; // rate the resident book achieved when fitted
533 bool just_fitted_ = false; // next encode establishes fit_bits_per_sym_
534 uint32_t refit_count_ = 0;
535 // True when buf_->d_bk4 / d_revbk4 currently hold the fixed book. Cleared by
536 // initBuf(), which allocates fresh (uninitialized) codebook buffers.
537 bool fixed_book_resident_ = false;
538
539 uint64_t original_len_ = 0; // element count set by forward execute
540 size_t actual_output_size_ = 0;
541 size_t cap_inlen_ = 0; // allocated capacity (elements); grow-only
542 uint32_t last_bklen_ = 0; // bklen_ when buf_ was last allocated
543
544 // Histogram launch params — computed once in initBuf(), reused every execute()
545 int hist_grid_dim_ = 0;
546 int hist_block_dim_ = 0;
547 int hist_shmem_use_ = 0;
548 int hist_r_per_block_ = 0;
549
550 // cuSZ Huffman working buffers — allocated on first execute() or in onFinalize()
551 std::unique_ptr<phf::Buf<T>> buf_;
552 phf_header header_ {};
553 uint8_t* pending_device_output_ = nullptr;
554 bool pending_device_readback_ = false;
555 size_t pending_device_inlen_ = 0;
556 bool is_terminal_output_ = true;
557
558 // Pool used for buf_ allocations. Set by onFinalize() or captured from the
559 // pool parameter on the first execute() call. Raw non-owning pointer; the
560 // pool outlives the stage when used inside a Pipeline.
561 MemoryPool* pool_ = nullptr;
562
563 // saveState / restoreState snapshots
564 uint32_t saved_bklen_ = defaultBklen();
565 uint64_t saved_original_len_ = 0;
566 size_t saved_output_size_ = 0;
567
568 static constexpr uint32_t defaultBklen() {
569 if constexpr (std::is_same_v<T, uint8_t>) return 256;
570 return 1024;
571 }
572
573 template<typename U>
574 static constexpr DataType dataTypeOf() {
575 if constexpr (std::is_same_v<U, uint8_t>) return DataType::UINT8;
576 if constexpr (std::is_same_v<U, uint16_t>) return DataType::UINT16;
577 return DataType::UINT32;
578 }
579
580 // Allocates buf_ from pool and computes histogram launch params for the given
581 // element count. Must be in huffman_stage.cu: calls cudaFuncSetAttribute with
582 // a __global__ pointer. If buf_ already exists, destroys it first (returning
583 // its allocations to the pool) before creating the new one.
584 void initBuf(size_t inlen, MemoryPool* pool);
585
586 // Builds the canonical codebook from fixed_freq_ into buf_ and H2Ds it.
587 // Requires buf_ to exist. Must be in huffman_stage.cu (needs phf::Buf<T>).
588 void buildFixedBook(fz::stream_t stream);
589
590 // Builds a reusable codebook from a sampled histogram, flooring frequencies and
591 // retrying with a flatter floor until the book fits the 27-bit code field.
592 void buildAdaptiveBook(const uint32_t* h_hist, fz::stream_t stream);
593
594 // Builds d_bk4 and d_revbk4 directly from buf_->d_freq. DeviceResident uses
595 // this for PerBlock/Adaptive histograms and for a Fixed table copied H2D.
596 void buildDeviceBook(fz::stream_t stream, MemoryPool* pool,
597 size_t expected_symbols, uint32_t source_mode);
598
599 // Records the achieved bit rate and applies Adaptive refit policy. Called
600 // immediately for HostCoordinated and from postStreamSync for DeviceResident.
601 void updateAdaptiveRate(size_t inlen, size_t total_nbit);
602
603 // Index of the first symbol with freq > 0 whose built code is unusable, or -1.
604 int findUnusableCode(const uint32_t* freq) const;
605};
606
607extern template class HuffmanStage<uint8_t>;
608extern template class HuffmanStage<uint16_t>;
609extern template class HuffmanStage<uint32_t>;
610
611} // namespace fz
Definition huffman_stage.h:119
size_t estimateDeviceFootprintBytes(size_t inlen) const override
void setRefitThreshold(float ratio)
Definition huffman_stage.h:333
size_t getMaxHeaderSize(size_t) const override
Definition huffman_stage.h:494
size_t serializeHeader(size_t, uint8_t *buf, size_t max_size) const override
Definition huffman_stage.h:456
uint16_t getStageTypeId() const override
Definition huffman_stage.h:443
double getFitBitsPerSymbol() const
Definition huffman_stage.h:365
std::vector< std::string > getRunNotes() const override
Definition huffman_stage.h:311
void onFinalize(size_t estimated_inlen, MemoryPool *pool) override
size_t getActualOutputSize(int index) const override
Definition huffman_stage.h:438
uint32_t getRefitCount() const
Definition huffman_stage.h:360
void saveState() override
Definition huffman_stage.h:496
bool getAdaptiveFallbackUsed() const
Definition huffman_stage.h:306
bool hasBookSpec() const
Definition huffman_stage.h:370
uint8_t getAdaptiveFloorShiftUsed() const
Definition huffman_stage.h:293
void setInverse(bool inv) override
Definition huffman_stage.h:374
std::vector< size_t > estimateOutputSizes(const std::vector< size_t > &input_sizes) const override
Definition huffman_stage.h:410
void deserializeHeader(const uint8_t *buf, size_t size) override
Definition huffman_stage.h:467
void setFixedBookFromFreq(const uint32_t *h_freq, uint32_t n)
void setAdaptiveFloorShift(uint8_t shift)
Definition huffman_stage.h:288
size_t estimatePinnedFootprintBytes(size_t inlen) const override
std::string getName() const override
Definition huffman_stage.h:406
const std::vector< uint32_t > & getFixedBookFreq() const
Frequency table backing the fixed codebook; empty when none has been set.
Definition huffman_stage.h:270
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
void setBookSource(HuffmanBookSource src)
Definition huffman_stage.h:213
void setExecutionMode(HuffmanExecutionMode mode)
Definition huffman_stage.h:197
void setTerminalOutput(bool terminal) override
Definition huffman_stage.h:377
uint8_t getOutputDataType(size_t) const override
Definition huffman_stage.h:448
std::unordered_map< std::string, size_t > getActualOutputSizesByName() const override
Definition huffman_stage.h:434
void setRefitInterval(uint32_t n)
Definition huffman_stage.h:354
void setFixedBookFromModel(const HuffmanBookSpec &spec)
void postStreamSync(fz::stream_t stream) override
void setBklen(uint32_t bklen)
Definition huffman_stage.h:170
uint8_t getInputDataType(size_t) const override
Definition huffman_stage.h:451
void setValidateSymbolRange(bool on)
Definition huffman_stage.h:266
Definition mempool.h:82
Definition stage.h:31
FZM binary file format definitions — structs, enums, and helpers.
Definition dag.h:24
HuffmanBookSource
Definition huffman_stage.h:68
@ Adaptive
Histogram the first call only, then reuse that codebook forever.
Definition huffman_stage.h:71
@ PerBlock
Histogram + build a fresh codebook on every forward call (default).
Definition huffman_stage.h:69
@ Fixed
Build one codebook up front and reuse it for every forward call.
Definition huffman_stage.h:70
HuffmanBookModel
Definition huffman_stage.h:75
@ Laplace
exp(-|i-center|/scale)
Definition huffman_stage.h:77
@ GeneralizedNormal
exp(-(|i-center|/scale)^shape)
Definition huffman_stage.h:78
@ Uniform
flat; every symbol equally likely
Definition huffman_stage.h:79
@ Gaussian
exp(-((i-center)/scale)^2 / 2)
Definition huffman_stage.h:76
HuffmanExecutionMode
Definition huffman_stage.h:49
@ HostCoordinated
cuSZ coarse path with a host partition-prefix scan (default).
Definition huffman_stage.h:50
@ DeviceResident
Device scan/header assembly; book construction follows the selected source.
Definition huffman_stage.h:51
DataType
Element data type identifiers used in buffer and stage descriptors.
Definition fzm_format.h:142
@ UNKNOWN
Byte-transparent stages: skip type checking at finalize().
Definition fzm_format.h:153
Base class interface for all compression stages.
Definition huffman_stage.h:90
double shape
Exponent for GeneralizedNormal only (2.0 == Gaussian, 1.0 == Laplace).
Definition huffman_stage.h:99
double scale
Definition huffman_stage.h:97
double center
Definition huffman_stage.h:94
Backend-neutral GPU type aliases.