FZGPUModules 2.0
GPU-accelerated modular compression pipelines
Loading...
Searching...
No Matches
ans_stage.h
Go to the documentation of this file.
1#pragma once
2
24
25#include "stage/stage.h"
26#include "fzm_format.h"
27#include "backend/types.h"
28#include <cstdint>
29#include <cstring>
30#include <stdexcept>
31#include <string>
32#include <unordered_map>
33#include <vector>
34
35namespace fz {
36
37class ANSStage : public Stage {
38public:
39 // Vendored dietgpu tree (modules/coders/ans/dietgpu/) uses inline NVPTX
40 // lanemask assembly (%laneid, %lanemask_lt/le/gt/ge) and a hardcoded
41 // 32-lane warp model with no HIP/SYCL translation — excluded rather than
42 // ported. Its .cu
43 // sources aren't compiled on HIP (CMakeLists.txt), so this must hide
44 // Stage::isSupportedOnBackend() rather than override it — see that
45 // method's doc comment for why it's static, not virtual.
46 static constexpr bool isSupportedOnBackend() {
47#if defined(FZGMOD_BACKEND_HIP) || defined(FZGMOD_BACKEND_SYCL)
48 return false;
49#else
50 return true;
51#endif
52 }
53
54 ANSStage() = default;
55 ~ANSStage() override = default;
56
57 // ── Configuration ─────────────────────────────────────────────────────────
58
64 void setProbBits(uint8_t pb) { prob_bits_ = pb; }
65 uint8_t getProbBits() const { return prob_bits_; }
66
67 // ── Stage control ─────────────────────────────────────────────────────────
68 void setInverse(bool inv) override { is_inverse_ = inv; }
69 bool isInverse() const override { return is_inverse_; }
70
71 // dietGPU requires input aligned to 4 bytes (kANSRequiredAlignment).
72 size_t getRequiredInputAlignment() const override { return 4; }
73
74 // ── Pool lifecycle ────────────────────────────────────────────────────────
75
81 void onFinalize(size_t estimated_inlen, MemoryPool* pool) override;
82
83 size_t estimateDeviceFootprintBytes(size_t inlen) const override;
84
85 size_t estimateScratchBytes(const std::vector<size_t>& input_sizes) const override;
86
87 // ── Execution ─────────────────────────────────────────────────────────────
88 void execute(
89 fz::stream_t stream,
90 MemoryPool* pool,
91 const std::vector<void*>& inputs,
92 const std::vector<void*>& outputs,
93 const std::vector<size_t>& sizes
94 ) override;
95
96 // ── Metadata ──────────────────────────────────────────────────────────────
97 std::string getName() const override { return "ANS"; }
98 size_t getNumInputs() const override { return 1; }
99 size_t getNumOutputs() const override { return 1; }
100
101 std::vector<size_t> estimateOutputSizes(
102 const std::vector<size_t>& input_sizes
103 ) const override {
104 if (input_sizes.empty()) return {0};
105 if (!is_inverse_) {
106 // ANS worst-case expansion is ~1.25× per block plus fixed header overhead.
107 // 2× + 8 KiB is a conservative but safe bound for all realistic inputs.
108 return {input_sizes[0] * 2 + 8192};
109 }
110 // original_bytes_ is restored from the serialized FZM header before execute();
111 // fall back to input size if deserializeHeader() has not yet been called.
112 return {original_bytes_ > 0 ? original_bytes_ : input_sizes[0]};
113 }
114
115 std::unordered_map<std::string, size_t>
116 getActualOutputSizesByName() const override {
117 return {{"output", actual_output_size_}};
118 }
119
120 size_t getActualOutputSize(int index) const override {
121 return (index == 0) ? actual_output_size_ : 0;
122 }
123
124 // ── Type system ───────────────────────────────────────────────────────────
125 uint16_t getStageTypeId() const override {
126 return static_cast<uint16_t>(StageType::ANS);
127 }
128
129 // Byte-transparent: opt out of pipeline type-compatibility checking.
130 uint8_t getOutputDataType(size_t /*output_index*/) const override {
131 return static_cast<uint8_t>(DataType::UNKNOWN);
132 }
133 uint8_t getInputDataType(size_t /*input_index*/) const override {
134 return static_cast<uint8_t>(DataType::UNKNOWN);
135 }
136
137 // ── Serialization ─────────────────────────────────────────────────────────
138 size_t serializeHeader(
139 size_t /*output_index*/, uint8_t* buf, size_t max_size
140 ) const override {
141 if (max_size < 12) return 0;
142 buf[0] = prob_bits_;
143 buf[1] = buf[2] = buf[3] = 0;
144 std::memcpy(buf + 4, &original_bytes_, sizeof(uint64_t));
145 return 12;
146 }
147
148 void deserializeHeader(const uint8_t* buf, size_t size) override {
149 if (size >= 1)
150 prob_bits_ = buf[0];
151 if (size >= 12)
152 std::memcpy(&original_bytes_, buf + 4, sizeof(uint64_t));
153 }
154
155 size_t getMaxHeaderSize(size_t /*output_index*/) const override { return 12; }
156
157 void saveState() override {
158 saved_prob_bits_ = prob_bits_;
159 saved_original_bytes_ = original_bytes_;
160 saved_output_size_ = actual_output_size_;
161 }
162
163 void restoreState() override {
164 prob_bits_ = saved_prob_bits_;
165 original_bytes_ = saved_original_bytes_;
166 actual_output_size_ = saved_output_size_;
167 }
168
169private:
170 bool is_inverse_ = false;
171 uint8_t prob_bits_ = 10; // kANSDefaultProbBits
172 uint64_t original_bytes_ = 0; // set by forward execute; used by inverse estimateOutputSizes
173 size_t actual_output_size_ = 0;
174
175 // Capacity (input bytes) of current scratch allocation. Grow-only.
176 size_t cap_bytes_ = 0;
177
178 // Persistent scratch device pointers, sub-allocated from MemoryPool.
179 // All are null until initScratch() is called.
180 uint32_t* d_temp_histogram_ = nullptr; // uint32_t[256]
181 void* d_table_ = nullptr; // uint4[256] (encode table: pdf/cdf/mul/shift)
182 uint8_t* d_compressed_blocks_ = nullptr; // uint8_t[max_blocks * kUncoalescedStride]
183 uint32_t* d_compressed_words_ = nullptr; // uint32_t[max_blocks]
184 uint32_t* d_comp_words_prefix_ = nullptr; // uint32_t[max_blocks]
185 void* d_temp_prefix_sum_ = nullptr; // CUB temp storage (nullptr when blocks ≤ 512)
186 uint32_t* d_decode_table_ = nullptr; // uint32_t[1 << prob_bits_]
187
188 // D2H readback buffer for ANSCoalescedHeader after forward encode.
189 // Stored as raw bytes to avoid pulling the dietgpu headers into this header.
190 // sizeof(ANSCoalescedHeader) == 32.
191 uint8_t last_header_bytes_[32] = {};
192
193 // Histogram launch params — computed in initScratch(), reused every execute().
194 int hist_grid_dim_ = 0;
195 int hist_block_dim_ = 0;
196 int hist_shmem_use_ = 0;
197 int hist_r_per_block_ = 0;
198
199 // saveState / restoreState snapshots
200 uint8_t saved_prob_bits_ = 10;
201 uint64_t saved_original_bytes_ = 0;
202 size_t saved_output_size_ = 0;
203
204 // Allocates all 7 scratch buffers from pool and computes histogram launch
205 // params for the given input capacity. Replaces any previous allocation.
206 void initScratch(size_t inlen, MemoryPool* pool);
207
208 // execute()'s forward/inverse bodies, split into separate functions so that
209 // no single function holds both branches' local variables, kernel launches,
210 // and conditional (vGPU) code paths at once — see ans_stage.cu for why this
211 // matters (an nvc++ host-codegen bug producing a misaligned stack-argument
212 // store for CUDA kernel launches in the combined function).
213 void executeForward(fz::stream_t stream, MemoryPool* pool,
214 uint8_t* in, uint8_t* out, size_t byte_size);
215 void executeInverse(fz::stream_t stream, MemoryPool* pool,
216 uint8_t* in, uint8_t* out);
217
218 // Per-block scratch stride (bytes): ANSWarpState (128 B) + max raw compressed
219 // block (5120 B = roundUp(4096 + 4096/4, 16)). Derived from dietGPU constants.
220 static constexpr size_t kUncoalescedStride = 128 + 5120; // 5248
221};
222
223} // namespace fz
Definition stage.h:31
virtual std::string getName() const =0
virtual void saveState()
Definition stage.h:179
virtual uint16_t getStageTypeId() const =0
virtual size_t getRequiredInputAlignment() const
Definition stage.h:88
virtual std::unordered_map< std::string, size_t > getActualOutputSizesByName() const =0
static constexpr bool isSupportedOnBackend()
Definition stage.h:52
FZM binary file format definitions — structs, enums, and helpers.
Definition dag.h:24
@ ANS
rANS entropy coder (GPU, via dietGPU)
Definition fzm_format.h:105
@ UNKNOWN
Byte-transparent stages: skip type checking at finalize().
Definition fzm_format.h:153
Base class interface for all compression stages.
Backend-neutral GPU type aliases.