KASKADE 7 development version
Loading...
Searching...
No Matches
bddcSpaceTransfer.hh
Go to the documentation of this file.
1
2/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
3/* */
4/* This file is part of the library KASKADE 7 */
5/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
6/* */
7/* Copyright (C) 2024-2024 Zuse Institute Berlin */
8/* */
9/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
10/* see $KASKADE/academic.txt */
11/* */
12/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
13
14#ifndef BDDCSPACETRANSFER_COMPRESSION_HH
15#define BDDCSPACETRANSFER_COMPRESSION_HH
16
17#include "dune/common/fvector.hh"
18#include <dune/istl/bvector.hh>
19#include <array>
20#include <vector>
21#include <map>
22#include <set>
23#include <queue>
24#include <cstdint>
25#include <type_traits>
26#include <limits>
27#include <cmath>
28
29// huffman coding
30#include "boost/timer/timer.hpp"
31#include "mg/prefixcoder.hh"
34#include "mg/bddcLiftingPlan.hh"
35#include <optional>
36#include <random>
37#include <mutex>
38#include <memory>
39#include <stdexcept>
40#include <string>
41#include <iomanip>
42
43namespace Kaskade::BDDC
44{
45
55 using Interfaces = std::vector<std::pair<int,std::vector<int>>>;
56 using InterfaceClassification = std::vector<std::pair<int,int>>;
57
58 // ====================================================================================
59 // Data Compression
60 // ====================================================================================
61
62 // ====================================
63 // Print Helper
64 // ====================================
65 template <typename T>
66 void printVector(const std::vector<T>& vec, const std::string& label) {
67 std::cout << label << ": ";
68 std::cout << std::fixed << std::setprecision(5);
69 for (const auto& val : vec) {
70 std::cout << val << " ";
71 }
72 std::cout << '\n';
73 }
74 // ====================================
75 // Find Next Power of 2
76 // ====================================
77 static inline int nextPowerOfTwo(int n) {
78 int power = 1;
79 while (power < n) {
80 power *= 2;
81 }
82 return power;
83 }
84 // ====================================
85 // Transform Base Class
86 // ====================================
87 template <typename Scalar>
88 class Transform {
89 public:
90 virtual std::vector<Scalar> apply(const std::vector<Scalar>& data) const = 0; // Apply transformation
91 virtual std::vector<Scalar> inverse(const std::vector<Scalar>& data) const = 0; // Apply inverse transformation
92 virtual ~Transform() = default;
93 };
94
95 // ====================================
96 // Haar Wavelet Transform
97 // Good for: Structured data with spatial locality
98 // Bad for: Unstructured meshes (requires power-of-2, assumes ordering)
99 // ====================================
100 template <typename Scalar>
101 class HaarWaveletTransform : public Transform<Scalar> {
102 public:
103 std::vector<Scalar> apply(const std::vector<Scalar>& data) const override {
104 return haarWaveletTransform(data);
105 }
106
107 std::vector<Scalar> inverse(const std::vector<Scalar>& data) const override {
108 return inverseHaarWaveletTransform(data);
109 }
110
111 private:
112 // Haar Wavelet Transform logic
113 std::vector<Scalar> haarWaveletTransform(const std::vector<Scalar>& data) const {
114 std::vector<Scalar> transformed = data;
115 int n = data.size();
116 while (n > 1) {
117 std::vector<Scalar> temp(n);
118 for (int i = 0; i < n / 2; ++i) {
119 temp[i] = (transformed[2 * i] + transformed[2 * i + 1]) / sqrtl(2.0);
120 temp[n / 2 + i] = (transformed[2 * i] - transformed[2 * i + 1]) / sqrtl(2.0);
121 }
122 for (int i = 0; i < n; ++i) transformed[i] = temp[i];
123 n /= 2;
124 }
125 return transformed;
126 }
127
128 std::vector<Scalar> inverseHaarWaveletTransform(const std::vector<Scalar>& data) const {
129 std::vector<Scalar> reconstructed = data;
130 int n = 2;
131 while (n <= data.size()) {
132 std::vector<Scalar> temp(reconstructed);
133 for (int i = 0; i < n / 2; ++i) {
134 temp[2 * i] = (reconstructed[i] + reconstructed[n / 2 + i]) / sqrtl(2.0);
135 temp[2 * i + 1] = (reconstructed[i] - reconstructed[n / 2 + i]) / sqrtl(2.0);
136 }
137 for (int i = 0; i < n; ++i) reconstructed[i] = temp[i];
138 n *= 2;
139 }
140 return reconstructed;
141 }
142 };
143
144 // ====================================
145 // Discrete Cosine Transform
146 // Good for: Unstructured data, no power-of-2 requirement, better energy compaction
147 // Used in: JPEG, MP3 - proven for real-world data
148 // Optimized: Uses cosine lookup table for better performance
149 // ====================================
150 template <typename Scalar>
151 class DCTTransform : public Transform<Scalar> {
152 public:
153 std::vector<Scalar> apply(const std::vector<Scalar>& data) const override {
154 return dctTransform(data);
155 }
156
157 std::vector<Scalar> inverse(const std::vector<Scalar>& data) const override {
158 return inverseDCTTransform(data);
159 }
160
161 private:
162 inline static constexpr Scalar PI = Scalar(3.141592653589793238462643383279502884L);
163
164 // Cosine table cache for performance
165 mutable std::map<int, std::vector<std::vector<Scalar>>> cosine_cache_forward;
166 mutable std::map<int, std::vector<std::vector<Scalar>>> cosine_cache_inverse;
167
168 // Precompute cosine table for given size
169 void precomputeCosineTable(int N) const {
170 if (cosine_cache_forward.find(N) != cosine_cache_forward.end()) {
171 return; // Already computed
172 }
173
174 // Forward DCT cosine table
175 std::vector<std::vector<Scalar>> forward_table(N, std::vector<Scalar>(N));
176 for (int k = 0; k < N; ++k) {
177 Scalar alpha = (k == 0) ? std::sqrt(1.0 / N) : std::sqrt(2.0 / N);
178 for (int n = 0; n < N; ++n) {
179 forward_table[k][n] = alpha * std::cos(PI * k * (2.0 * n + 1.0) / (2.0 * N));
180 }
181 }
182 cosine_cache_forward[N] = forward_table;
183
184 // Inverse DCT cosine table
185 std::vector<std::vector<Scalar>> inverse_table(N, std::vector<Scalar>(N));
186 for (int n = 0; n < N; ++n) {
187 for (int k = 0; k < N; ++k) {
188 Scalar alpha = (k == 0) ? std::sqrt(1.0 / N) : std::sqrt(2.0 / N);
189 inverse_table[n][k] = alpha * std::cos(PI * k * (2.0 * n + 1.0) / (2.0 * N));
190 }
191 }
192 cosine_cache_inverse[N] = inverse_table;
193 }
194
195 // DCT-II (forward transform) - Optimized with lookup table
196 std::vector<Scalar> dctTransform(const std::vector<Scalar>& data) const {
197 int N = data.size();
198 if (N == 0) return data;
199
200 // Precompute cosine table for this size
201 precomputeCosineTable(N);
202 const auto& cos_table = cosine_cache_forward[N];
203
204 std::vector<Scalar> transformed(N);
205 for (int k = 0; k < N; ++k) {
206 Scalar sum = 0.0;
207 for (int n = 0; n < N; ++n) {
208 sum += data[n] * cos_table[k][n];
209 }
210 transformed[k] = sum;
211 }
212 return transformed;
213 }
214
215 // DCT-III (inverse transform) - Optimized with lookup table
216 std::vector<Scalar> inverseDCTTransform(const std::vector<Scalar>& data) const {
217 int N = data.size();
218 if (N == 0) return data;
219
220 // Precompute cosine table for this size
221 precomputeCosineTable(N);
222 const auto& cos_table = cosine_cache_inverse[N];
223
224 std::vector<Scalar> reconstructed(N);
225 for (int n = 0; n < N; ++n) {
226 Scalar sum = 0.0;
227 for (int k = 0; k < N; ++k) {
228 sum += data[k] * cos_table[n][k];
229 }
230 reconstructed[n] = sum;
231 }
232 return reconstructed;
233 }
234 };
235
236 // ====================================
237 // Delta Encoding
238 // Good for: Data with smooth variations, simple and fast
239 // Stores first value + differences (deltas)
240 // ====================================
241 template <typename Scalar>
242 class DeltaEncoding : public Transform<Scalar> {
243 public:
244 std::vector<Scalar> apply(const std::vector<Scalar>& data) const override {
245 if (data.empty()) return data;
246
247 std::vector<Scalar> deltas(data.size());
248 deltas[0] = data[0]; // First value unchanged
249
250 for (size_t i = 1; i < data.size(); ++i) {
251 deltas[i] = data[i] - data[i-1]; // Store difference
252 }
253 return deltas;
254 }
255
256 std::vector<Scalar> inverse(const std::vector<Scalar>& deltas) const override {
257 if (deltas.empty()) return deltas;
258
259 std::vector<Scalar> reconstructed(deltas.size());
260 reconstructed[0] = deltas[0]; // First value
261
262 for (size_t i = 1; i < deltas.size(); ++i) {
263 reconstructed[i] = reconstructed[i-1] + deltas[i]; // Accumulate deltas
264 }
265 return reconstructed;
266 }
267 };
268
269 // ====================================
270 // Quantization & Dequantization
271 // ====================================
272 template <typename TransmissionScalar, typename Scalar>
274 public:
275 virtual void quantize(const double& data, TransmissionScalar& quantizedData, double typeMin, double typeMax, double minVal, double scale) = 0;
276 // virtual void dequantize(const vector<TransmissionScalar>& data, int scale, vector<Scalar>& dequantized) = 0;
277 virtual void dequantize(const TransmissionScalar& quantizedData, double& data, double typeMin, double minVal, double scale) const = 0;
278 virtual ~Quantization() = default;
279 };
280
281 // Quantizer class for quantization and dequantization
282 template <typename Scalar, typename TransmissionScalar>
283 class Quantizer : public Quantization<TransmissionScalar, Scalar> {
284 public:
285 // Quantize the data
286 void quantize(const double& data, TransmissionScalar& quantizedData, double typeMin, double typeMax, double minVal, double scale) override {
287 static_assert(std::is_arithmetic<TransmissionScalar>::value, "Quantized type must be numeric.");
288
289 // Compute in long double and clamp to both requested type range and true scalar bounds.
290 // This avoids overflow/UB on cast for wide unsigned types (e.g. uint64_t).
291 long double normalized =
292 (static_cast<long double>(data) - static_cast<long double>(minVal)) *
293 static_cast<long double>(scale) +
294 static_cast<long double>(typeMin);
295
296 long double lo_req = static_cast<long double>(typeMin);
297 long double hi_req = static_cast<long double>(typeMax);
298 long double lo_type = static_cast<long double>(std::numeric_limits<TransmissionScalar>::lowest());
299 long double hi_type = static_cast<long double>(std::numeric_limits<TransmissionScalar>::max());
300
301 long double lo = std::max(lo_req, lo_type);
302 long double hi = std::min(hi_req, hi_type);
303 if (hi < lo)
304 hi = lo;
305
306 long double q = std::round(normalized);
307 if (q < lo) q = lo;
308 if (q > hi) q = hi;
309
310 quantizedData = static_cast<TransmissionScalar>(q);
311 }
312
313 // Dequantize the data
314 void dequantize(const TransmissionScalar& quantizedData, double& data, double typeMin, double minVal, double scale) const {
315 static_assert(std::is_arithmetic<TransmissionScalar>::value, "Quantized type must be numeric.");
316
317 // Perform dequantization in long double to reduce precision loss for wide symbols.
318 long double q = static_cast<long double>(quantizedData);
319 long double restored = ((q - static_cast<long double>(typeMin)) / static_cast<long double>(scale)) +
320 static_cast<long double>(minVal);
321 data = static_cast<double>(restored);
322 }
323 };
324
325 // ----------------------------------------------------------------------------------------------
330 template <int m, class Scalar>
332 {
333 public:
337
343 SpaceTransferBase(int id, Interfaces const& ifs);
344
351 void setInterfaceAveragingWeights(int s, XVector const& rho);
352
361
368 void getInterfaceAveragingWeights(int s, XVector& rho) const;
369
377 {
378 weights = 1;
379 for (size_t i=0; i<globalIndex.size(); ++i)
380 for (int j=0; j<m; ++j)
381 weights[globalIndex[i]*m+j] = myAvgWeight[i][j]/avgWeightSum[i][j];
382 }
383
384 protected:
385
386 // Returns the interface-local indices of dofs shared with subdomain s.
387 std::vector<int> const& localIdx(int s) const;
388
389 std::vector<int> filteredLocalIdx(int s) const;
390 void setExcludedLocalDofs(std::vector<int> const& dofs);
392
393 int id; // own subdomain number
394
395 // We think in interface dofs and indices. We therefore maintain a mapping of
396 // interface dof indices to subdomain dof indices (globalIndex), and a
397 // list of interface indices (instead of subdomain indices) for each interface group
398 // (localIfs).
399 std::vector<int> globalIndex;
401 std::vector<unsigned char> excludedGlobal;
403
404 // This contains for each shared dof the own averaging weight w_i as well as the
405 // sum of all weights (i.e. the averaging denominator).
408
409 };
410
411 // ----------------------------------------------------------------------------------------------
412
440 template <int m, class Scalar=double, class TransmissionScalar=Scalar>
441 class SpaceTransfer: public SpaceTransferBase<m,Scalar>
442 {
443 using Base = SpaceTransferBase<m,Scalar>;
444
445 public:
449
451
455 using TransmissionType = std::vector<TEntry>;
456 // For quantized/encoded transfers, use SpaceTransferDataCompression instead.
457
463 SpaceTransfer(int id, Interfaces const& ifs);
464
475 void setDumpIteration(int) {}
476
498
503 void preProlongate(Vector const& u);
504
509 void getInterfaceValues(int s, TransmissionType& values) const;
510
515 void setInterfaceValues(int s, TransmissionType const& values);
516
523 void postProlongate(Vector const& u, Vector& du) const;
524
528
558
559 void preRestrict(Vector const& r);
560
562
564
570
574
576 void setInActiveIdx(int gIdx);
577
578 void get_globalIndex(std::set<int> & globalIndex_notActive)
579 {
580 std::map<int, int>::iterator it;
581 for (it = globalIndex_active.begin(); it != globalIndex_active.end(); it++)
582 {
583 if (not it->second)
584 globalIndex_notActive.insert(it->first);
585 }
586 }
587
588 private:
589 using Base::localIdx;
590 using Base::localIfs;
591 using Base::globalIndex;
592 using Base::avgWeightSum;
593 using Base::myAvgWeight;
594
595 // We store the interface values in transmission type to be sent to
596 // neighboring subdomains on demand. On restriction, this contains our residual updates.
597 // On prolongation, this contains our weighted correction values.
598 TransmissionType localIfValues;
599
600 // We accumulate the interface values received from neighbors. On restriction, this
601 // sums up the residual contributions from all adjacent subdomains (including us).
602 // On prolongation, this sums up the weighted interface corrections.
603 XVector ifValues;
604
605 // We keep track of the local residual that we already have sent to neighbors (which may
606 // be inexact due to compression or mixed precision), such that we can send only the
607 // updates.
608 XVector localPublishedResidual;
609
610
611 // TODO: docme
612 std::map<int,int> globalIndex_active;
613 };
614
615 // ----------------------------------------------------------------------------------------------
616
617 // Transform options for interface payloads.
618 // GRAPH_LIFTING uses local operator connectivity to define smoothness;
619 // NONE leaves the interface vector unchanged. No transform based only on
620 // arbitrary vector ordering is exposed.
622
654 // Quantization applies to entries not protected by the exact-value policies.
655 template <int m, class Scalar=double, class TransmissionScalar=Scalar, class quantizedScalar=TransmissionScalar, class StorageType=uint8_t>
657 {
658 using Base = SpaceTransferBase<m,Scalar>;
659
660 public:
661 using QuantizedScalar = quantizedScalar;
662
666
668
672 using quantizedType = std::vector<Dune::FieldVector<quantizedScalar,m>>;
673
674 using TransmissionType = std::vector<TEntry>;
675 using deqTransmissionType = std::vector<XEntry>;
676
678
679 using Frequency = unsigned int;
680
682 std::vector<TransmissionScalar> scaleBytes; // serialized scale
683 std::vector<TransmissionScalar> minValueBytes;// serialized min
684 mutable uint32_t symbolCount; // number of symbols
685 uint32_t checksum = 0; // checksum of symbols
686 std::vector<StorageType> bitstream; // encoded symbols
687 };
688
690 std::vector<TransmissionScalar> scaleBytes; // serialized scale
691 std::vector<TransmissionScalar> minValueBytes;// serialized min
692 mutable uint32_t symbolCount; // number of symbols
693 uint32_t checksum = 0; // checksum of symbols
694 mutable std::vector<StorageType> bitstream; // encoded symbols
695 };
696
705
706 void setExcludedLocalDofs(std::vector<int> const& dofs)
707 {
709 applyNodeLocalExactMask();
710 producer_lifting_plans.clear();
711 producer_float_plans.clear();
712 local_float_plans.clear();
713 producer_lifting_setup_stale = require_producer_lifting_plans;
714 }
715
723 void setNodeLocalCompressionBypass(std::vector<int> const& nodes)
724 {
725 if (m!=1 || !std::is_same_v<Scalar,TransmissionScalar>)
726 throw std::invalid_argument("Local compression bypass requires scalar matching precision");
727 if (require_producer_lifting_plans || node_local_bypass)
728 throw std::logic_error("Configure local bypass once before domain setup");
729 node_local_exact.assign(globalIndex.size(),0);
730 std::vector<std::set<int>> ownerNodes(globalIndex.size());
731 int const ownNode=nodes.at(this->id);
732 if (ownNode<0) throw std::invalid_argument("Invalid subdomain node");
733 for (auto& owners: ownerNodes) owners.insert(ownNode);
734 for (auto const& [peer,idx]: this->localIfs)
735 {
736 if (peer==this->id) continue;
737 int const node=nodes.at(peer);
738 if (node<0) throw std::invalid_argument("Invalid subdomain node");
739 for (auto i: idx)
740 if (!ownerNodes.at(i).insert(node).second) node_local_exact.at(i)=1;
741 }
742 node_local_bypass=true;
743 applyNodeLocalExactMask();
744 local_float_plans.clear();
745 }
746
747 std::size_t nodeLocalExactDofs() const
748 {
749 return std::count(node_local_exact.begin(),node_local_exact.end(),1);
750 }
751
754 {
755 producer_lifting_plans.clear();
756 producer_float_plans.clear();
757 local_float_plans.clear();
758 require_producer_lifting_plans = true;
759 producer_lifting_setup_stale = false;
760 }
761
763 std::vector<unsigned char> exportIntegerLiftingPlan(int consumer) const;
765 void importIntegerLiftingPlan(int producer, std::vector<unsigned char> const& bytes);
766
767 // Interfaces with fewer scalar values use the uncompressed path.
768 // Zero disables the threshold.
769 void setCompressionMinInterfaceSize(std::size_t minValues)
770 {
771 compression_min_interface_size = minValues;
772 }
773
774 // Restrict the size threshold to selected BDDC interface types.
775 // A zero mask applies the threshold to every interface.
777 {
778 compression_threshold_interface_types = typeMask;
779 }
780
782 {
783 Base::setInterfaceClassifications(classifications);
784 }
785
796 // Initialize graph-lifting from one matrix (topology and weights both from mat).
797 // Useful as a fallback; preferred path is K-topology + A-weights below.
798 template <class MatrixLike>
799 void setGraphLiftingFromMatrix(MatrixLike const& mat);
800 // Practical compromise for EMI:
801 // - topologyMat (typically K): which interface DoFs are connected
802 // - weightMat (typically A): interpolation strength on those edges
803 // This keeps hierarchy geometry-aware while adapting weights to current operator.
804 template <class TopologyMatrixLike, class WeightMatrixLike>
805 void setGraphLiftingTopologyAndWeights(TopologyMatrixLike const& topologyMat,
806 WeightMatrixLike const& weightMat);
807
808 std::vector<TransmissionScalar> valueToVecTransmission(Scalar value) const;
809 Scalar VecTransmissionToValue(const std::vector<TransmissionScalar>& bytes) const;
810
811 // The wire format stores minValue and scale as two float32 values packed
812 // into the smallest number of TransmissionScalar slots. With the current
813 // double transmission type this reduces their header from two slots to one.
814 static constexpr size_t metadataSlots()
815 {
816 return (2 * sizeof(float) + sizeof(TransmissionScalar) - 1) /
817 sizeof(TransmissionScalar);
818 }
819 std::vector<TransmissionScalar> packMetadata(double scale, double minValue) const;
820 std::pair<double, double> unpackMetadata(std::vector<TransmissionScalar> const& bytes) const;
821
822 bool isRestrictEncodingEnabled() const { return use_encoding_restrict && !bypassAll(); }
823 bool isProlongateEncodingEnabled() const { return use_encoding_prolongate && !bypassAll(); }
824 static bool hasSharedRestrictCodebook() { return sharedRestrictCodebook().has_value(); }
825 static bool hasSharedProlongateCodebook() { return sharedProlongateCodebook().has_value(); }
826 // Estimated in-process codebook footprint; it is reported separately from
827 // per-message payload because the table is not transmitted per message.
828 static std::uint64_t sharedRestrictCodebookBits();
829 static std::uint64_t sharedProlongateCodebookBits();
830
831 // Append the latest restrict-side quantized symbols to out for codebook training.
832 void appendRestrictSymbols(std::vector<quantizedScalar>& out) const;
833 // Append the latest restrict-side raw quantized symbols (s, before n/tail split).
834 void appendRestrictRawSymbols(std::vector<quantizedScalar>& out) const;
835 // Append the latest prolongate-side quantized symbols to out for codebook training.
836 void appendProlongateSymbols(std::vector<quantizedScalar>& out) const;
837 // Append the latest prolongate-side raw quantized symbols (s, before n/tail split).
838 void appendProlongateRawSymbols(std::vector<quantizedScalar>& out) const;
839 // Build (or clear) the shared restrict-side codebook from aggregated symbols.
840 // Built from the first aggregated exchange, then reused until explicitly rebuilt.
841 static void buildSharedRestrictCodebookFromSymbols(std::vector<quantizedScalar> const& symbols);
842 // Build (or clear) the shared prolongate-side codebook from aggregated symbols.
843 // Built from the first aggregated exchange, then reused until explicitly rebuilt.
844 static void buildSharedProlongateCodebookFromSymbols(std::vector<quantizedScalar> const& symbols);
845 // Encode the last restrict symbols using the shared codebook (if enabled/available),
846 // populate dres_data metadata/bitstream, then clear the symbol buffer.
848 // Encode the last prolongate symbols using the shared codebook (if enabled/available),
849 // populate value_data metadata/bitstream, then clear the symbol buffer.
851
852 void enableTransformCheck(bool enable = true) { check_transform = enable; }
853 bool isTransformCheckEnabled() const { return check_transform; }
854 void enableEncodingCheck(bool enable = true) { check_encoding = enable; sharedEncodingDebug() = enable; }
855 bool isEncodingCheckEnabled() const { return check_encoding; }
856 void enableSymbolCheck(bool enable = true) { check_symbols = enable; }
857 bool isSymbolCheckEnabled() const { return check_symbols; }
858 void requireRestrictHuffman(bool enable = true) { require_huffman_restrict = enable; }
859 void requireProlongateHuffman(bool enable = true) { require_huffman_prolongate = enable; }
860 bool isRestrictHuffmanRequired() const { return require_huffman_restrict; }
861 bool isProlongateHuffmanRequired() const { return require_huffman_prolongate; }
862 void enableFpgaAsciiDump(bool enable = true) { sharedFpgaAsciiDumpEnabled() = enable; }
863 bool isFpgaAsciiDumpEnabled() const { return sharedFpgaAsciiDumpEnabled(); }
864 static void setFpgaAsciiDumpDirectory(std::string directory);
865 static std::string const& fpgaAsciiDumpDirectory();
866 static void setFpgaAsciiDumpSubdomainFilter(int subdomain);
868 void setDumpIteration(int iteration) { sharedFpgaAsciiDumpIteration() = iteration; }
875 void setQuantizationBits(int bits);
876
887
896 void setRestrictZeroPreserving(bool enable) { zero_preserving_restrict = enable; }
897 bool isRestrictZeroPreserving() const { return zero_preserving_restrict; }
898
908 void setProlongateZeroPreserving(bool enable) { zero_preserving_prolongate = enable; }
909 bool isProlongateZeroPreserving() const { return zero_preserving_prolongate; }
910
926 {
927 if (enable && (m!=1 || sizeof(typename TransmissionType::value_type)!=8))
928 throw std::runtime_error("Constant-split prolongation requires scalar double slots");
929 prolongate_constant_split=enable;
930 }
931
933 void setInterfaceAveragingWeights(int s, XVector const& rho)
934 {
936 if (prolongate_constant_split && s!=this->id)
937 prolongate_producer_weights[s]=rho;
938 }
939
941 std::uint64_t prolongateConstantHeaderBytes() const { return prolongate_constant_header_bytes; }
942
950 void setProlongateGroupSize(std::size_t size)
951 {
952 if (size && m!=1) throw std::runtime_error("Grouped prolongation requires scalar DOFs");
953 prolongate_group_size=size;
954 }
955
957 {
958 Vector contribution; // Producer contribution divided by the full averaging weight sum.
961 bool codecValid=true;
962 };
963
975 std::size_t localSize, int precision, std::size_t groupSize) const;
976 void setRestrictGroupSize(std::size_t size)
977 {
978 if (size && sizeof(typename TransmissionType::value_type)!=8)
979 throw std::runtime_error("Experimental restriction groups require 8-byte transmission slots");
980 restrict_group_size = size;
981 }
982
992
1014
1019 void preProlongate(Vector const& u);
1020
1025 void getInterfaceValues(int s, TransmissionType& values) const;
1026
1031 void setInterfaceValues(int s, TransmissionType const& values);
1032
1039 void postProlongate(Vector const& u, Vector& du) const;
1040
1044
1074
1075 void preRestrict(Vector const& r);
1076
1078
1080
1086
1090
1092 void setInActiveIdx(int gIdx);
1093
1094 void get_globalIndex(std::set<int> & globalIndex_notActive)
1095 {
1096 std::map<int, int>::iterator it;
1097 for (it = globalIndex_active.begin(); it != globalIndex_active.end(); it++)
1098 {
1099 if (not it->second)
1100 globalIndex_notActive.insert(it->first);
1101 }
1102 }
1103
1110 {
1111 std::vector<Scalar> quantizationInput;
1112 std::vector<quantizedScalar> quantized, lifted, symbols;
1113 };
1114 PacketStages inspectPacketStages(int peer, bool residual) const;
1115
1120 void setSymbolHistogramOutput(std::string directory)
1121 {
1122 int const r=quantization_bits_restrict>0 ? quantization_bits_restrict : bits;
1123 int const p=quantization_bits_prolongate>0 ? quantization_bits_prolongate : bits;
1124 if (!directory.empty() && (m!=1 || !std::is_unsigned<quantizedScalar>::value ||
1125 sizeof(quantizedScalar)!=4 || r<2 || r>24 || p<2 || p>24 ||
1126 zero_preserving_restrict || zero_preserving_prolongate ||
1127 restrict_group_size || prolongate_group_size || compression_min_interface_size ||
1128 !use_zigzag_restrict || !use_zigzag_prolongate ||
1129 !use_bitlength_restrict || !use_bitlength_prolongate ||
1130 !use_encoding_restrict || !use_encoding_prolongate))
1131 throw std::runtime_error("Packet histograms require scalar uint32 affine 2..24-bit full coding without grouping or thresholds");
1132 symbolHistogramDirectory=std::move(directory);
1133 symbolHistogramRestrictExchange=0;
1134 symbolHistogramProlongateExchange=0;
1135 }
1136
1137
1139
1140 private:
1141 using Base::localIdx;
1142 using Base::globalIndex;
1143 using Base::avgWeightSum;
1144 using Base::myAvgWeight;
1145
1146 bool node_local_bypass=false;
1147 std::vector<unsigned char> node_local_exact;
1148 void applyNodeLocalExactMask()
1149 {
1150 if (!node_local_bypass) return;
1151 if (this->excludedGlobal.empty()) this->excludedGlobal.assign(globalIndex.size(),0);
1152 for (std::size_t i=0; i<node_local_exact.size(); ++i)
1153 if (node_local_exact[i]) this->excludedGlobal[i]=1;
1154 }
1155 bool bypassPacket(int peer) const
1156 {
1157 return node_local_bypass && this->filteredLocalIdx(peer).empty();
1158 }
1159 bool bypassAll() const
1160 {
1161 return node_local_bypass && std::all_of(this->excludedGlobal.begin(),
1162 this->excludedGlobal.end(),[](auto excluded) { return excluded!=0; });
1163 }
1164 void receiveRawInterface(int peer, TransmissionType const& values, bool residual);
1165 void prepareRawInterface(Vector const& values, bool residual);
1166
1167 // Entries excluded from quantization remain part of P and P^T. They follow
1168 // the quantized payload as an unquantized trailer in normal interface order.
1169 std::vector<int> unquantizedLocalIdx(int s) const;
1170 void appendUnquantizedValues(int s, TransmissionType& values, bool residual) const;
1171 void receiveInterfaceValues(int s, TransmissionType const& values, bool residual);
1172 void getQuantizedInterfaceValues(int s, TransmissionType& values) const;
1173 void getQuantizedInterfaceValuesImpl(int s, TransmissionType& values) const;
1174 void setQuantizedInterfaceValues(int s, TransmissionType const& values);
1175 void setQuantizedInterfaceValuesImpl(int s, TransmissionType const& values,
1176 std::vector<double> const* groupScales, std::vector<double> const* groupMinima,
1177 std::vector<double> const* constantContribution=nullptr);
1178 void getQuantizedInterfaceResidualUpdate(int s, TransmissionType& dres) const;
1179 void setQuantizedInterfaceResidualUpdate(int s, TransmissionType const& dres);
1180 void getQuantizedInterfaceResidualUpdateImpl(int s, TransmissionType& dres) const;
1181 void setQuantizedInterfaceResidualUpdateImpl(int s, TransmissionType const& dres,
1182 std::vector<double> const* groupScales);
1183
1184 // We store the interface values in transmission type to be sent to
1185 // neighboring subdomains on demand. On restriction, this contains our residual updates.
1186 // On prolongation, this contains our weighted correction values.
1187 TransmissionType localIfValues;
1188 deqTransmissionType localIfValues_dequantized;
1189
1190 // We accumulate the interface values received from neighbors. On restriction, this
1191 // sums up the residual contributions from all adjacent subdomains (including us).
1192 // On prolongation, this sums up the weighted interface corrections.
1193 XVector ifValues;
1194
1195 // We keep track of the local residual that we already have sent to neighbors (which may
1196 // be inexact due to compression or mixed precision), such that we can send only the
1197 // updates.
1198 XVector localPublishedResidual;
1199
1200 std::optional<HuffmanCodec<quantizedScalar>> codebook_restrict;
1201 std::optional<HuffmanCodec<quantizedScalar>> codebook_prolongate;
1202
1203 // Return a shared Huffman codebook used for RESTRICTION.
1204 //
1205 // Semantics:
1206 // - One shared instance per template instantiation
1207 // - Lazily initialized via std::optional
1208 // - Persists for the lifetime of the program
1209 //
1210 // Motivation:
1211 // - Avoid repeated construction of expensive Huffman trees
1212 // - Restriction operators are reused across many iterations
1213 //
1214 // Usage:
1215 // - Caller checks has_value() and emplaces if needed
1216 // - Intended for read-only access after initialization
1217 //
1218 // Threading:
1219 // - Initialization is thread-safe (C++11)
1220 // - Mutation is NOT thread-safe
1221 static std::optional<HuffmanCodec<quantizedScalar>>& sharedRestrictCodebook();
1222 // Shared flag indicating bit-length encoding is enabled for restriction.
1223 static bool& sharedRestrictBitlengthMode();
1224
1225 // Return a shared Huffman codebook used for PROLONGATION.
1226 //
1227 // Same semantics as sharedRestrictCodebook(), but kept separate
1228 // because restriction and prolongation may have different
1229 // symbol statistics and codebooks.
1230 static std::optional<HuffmanCodec<quantizedScalar>>& sharedProlongateCodebook();
1231 // Shared flag indicating bit-length encoding is enabled for prolongation.
1232 static bool& sharedProlongateBitlengthMode();
1233 // Shared debug flag for codebook build logs.
1234 static bool& sharedEncodingDebug();
1235 // Shared controls for ASCII dumps used in FPGA-side validation.
1236 static bool& sharedFpgaAsciiDumpEnabled();
1237 static std::string& sharedFpgaAsciiDumpDirectoryStorage();
1238 static int& sharedFpgaAsciiDumpSubdomainFilterStorage();
1239 static int& sharedFpgaAsciiDumpIteration();
1240
1241 // Control flags for compression pipeline
1242 mutable bool use_transform_restrict = false;
1243 mutable bool use_encoding_restrict = false; // Enable/disable Huffman encoding
1244 mutable bool use_transform_prolongate = false;
1245 // Select the transform location independently for each transfer direction.
1246 // The post-quantization path is an exact fixed-width integer transform.
1247 mutable bool transform_after_quantization_restrict = false;
1248 mutable bool transform_after_quantization_prolongate = false;
1249 bool transform_before_and_after_quantization = false;
1250 std::string symbolHistogramDirectory;
1251 std::uint64_t symbolHistogramRestrictExchange=0, symbolHistogramProlongateExchange=0;
1252 mutable bool use_encoding_prolongate= false; // Enable/disable Huffman encoding
1253 mutable bool use_bitlength_restrict = false; // Encode bit-lengths, store tails raw
1254 mutable bool use_bitlength_prolongate = false; // Encode bit-lengths, store tails raw
1255 mutable bool use_zigzag_restrict = true; // Map signed symbols before bit-length coding
1256 mutable bool use_zigzag_prolongate = true;
1257 mutable std::size_t compression_min_interface_size = 0;
1258 mutable int compression_threshold_interface_types = 0;
1259
1260 mutable size_t original_data_size_restrict = 0;
1261 mutable size_t original_data_size_prolongate = 0;
1262
1263 std::map<int,int> globalIndex_active;
1264
1265 std::vector<quantizedScalar> scale_composed;
1266 std::vector<quantizedScalar> minValue_composed;
1267
1268 double typeMinRestrict;
1269 double typeMaxRestrict;
1270 double typeMinProlongate;
1271 double typeMaxProlongate;
1272 int bits = sizeof(quantizedScalar)*8;
1273 int quantization_bits_restrict = 0;
1274 int quantization_bits_prolongate = 0;
1275
1276 std::vector<quantizedScalar> last_quantized_restrict;
1277 std::vector<quantizedScalar> last_quantized_prolongate;
1278 // Raw quantized symbols s (before optional bit-length transform to n).
1279 // Used for entropy reporting/comparison.
1280 std::vector<quantizedScalar> last_raw_restrict;
1281 std::vector<quantizedScalar> last_raw_prolongate;
1282
1283 mutable bool check_transform = false;
1284 mutable bool check_encoding = false;
1285 mutable bool check_symbols = false;
1286 mutable bool require_huffman_restrict = false;
1287 mutable bool require_huffman_prolongate = false;
1288
1289 [[noreturn]] void throwRequiredEncodingFailure(char const* phase, std::string const& reason) const
1290 {
1291 throw std::runtime_error(std::string("BDDC ") + phase + " compression required on subdomain "
1292 + std::to_string(this->id) + ": " + reason);
1293 }
1294
1295 Quantizer<Scalar, quantizedScalar> quantizer;
1296 bool zero_preserving_restrict = false;
1297 bool zero_preserving_prolongate = false;
1298 bool prolongate_constant_split = false;
1299 float prolongate_constant = 0;
1300 std::map<int,XVector> prolongate_producer_weights;
1301 mutable std::uint64_t prolongate_constant_header_bytes = 0;
1302 std::size_t restrict_group_size = 0;
1303 std::size_t prolongate_group_size = 0;
1304 std::vector<std::size_t> prolongate_group_ids;
1305 std::vector<double> prolongate_group_scales, prolongate_group_minima;
1306 std::vector<double> prolongate_group_wire_scales, prolongate_group_wire_minima;
1307 std::vector<std::size_t> restrict_group_ids;
1308 std::vector<double> restrict_group_scales;
1309 std::uint64_t restrictionCaptureInvocation = 0;
1310 std::uint64_t frozenRestrictInvocation = 0, frozenProlongateInvocation = 0;
1311 void captureFrozenInput(bool residual);
1312
1313
1314 // Decode with the same mode on own and received contributions. The second
1315 // metadata value is reserved zero in the experimental restriction mode.
1316 void decodeRestrict(quantizedScalar code, Scalar& value, double offset, double scale) const
1317 {
1318 if (zero_preserving_restrict)
1319 {
1320 if (offset!=0)
1321 throw std::runtime_error("Zero-preserving restriction metadata mismatch");
1322 value = ZeroPreservingQuantization::decode(code,typeMaxRestrict,scale);
1323 }
1324 else
1325 quantizer.dequantize(code,value,typeMinRestrict,offset,scale);
1326 }
1327 void decodeProlongate(quantizedScalar code, Scalar& value, double offset, double scale) const
1328 {
1329 if (zero_preserving_prolongate)
1330 {
1331 if (offset!=0)
1332 throw std::runtime_error("Zero-preserving prolongation metadata mismatch");
1333 value = ZeroPreservingQuantization::decode(code,typeMaxProlongate,scale);
1334 }
1335 else
1336 quantizer.dequantize(code,value,typeMinProlongate,offset,scale);
1337 }
1338
1339 // Graph-lifting storage.
1340 // - interface_graph: adjacency on interface-local indices
1341 // - interface_graph_weights: edge strengths used in prediction
1342 // Built once and reused in restrict/prolongate exchange.
1343 mutable bool interface_graph_ready = false;
1344 mutable std::vector<std::vector<int>> interface_graph;
1345 mutable std::vector<std::vector<Scalar>> interface_graph_weights;
1346
1347 using UnsignedQuantized = std::make_unsigned_t<quantizedScalar>;
1348 // Payload flags for the encoded path:
1349 // - Bitlength: Huffman encodes only the bit-length n of each symbol
1350 // - Zigzag: signed values are mapped to nonnegative before bit-length split
1351 // (needed because bit-length is defined on unsigned magnitudes)
1352 static constexpr uint32_t kEncodedFlagBitlength = 1u << 0;
1353 static constexpr uint32_t kEncodedFlagZigzag = 1u << 1;
1354 static constexpr uint32_t kEncodedFlagIntegerGraphLifting = 1u << 2;
1355 // Split scheme helpers:
1356 // - bitLengthSymbol: n = number of bits including leading 1 (0 if value==0)
1357 // - tailBits: the remaining (n-1) least-significant bits
1358 static uint32_t bitLengthSymbol(UnsignedQuantized value);
1359 static UnsignedQuantized tailBits(UnsignedQuantized value, uint32_t bitlen);
1360 // Zigzag maps signed ints to nonnegative for entropy coding; inverse restores sign.
1361 // Example: 0->0, -1->1, 1->2, -2->3, ...
1362 static UnsignedQuantized zigzagEncode(quantizedScalar value);
1363 static quantizedScalar zigzagDecode(UnsignedQuantized value);
1364
1365
1366 public:
1367 // Helper methods to control compression features. There are deliberately
1368 // only two transform states: identity or graph lifting.
1372
1373 void setRestrictEncoding(bool enable = true) { use_encoding_restrict = enable; }
1374 void setProlongateEncoding(bool enable = true) { use_encoding_prolongate = enable; }
1375 void setRestrictTransform(bool enable = true) { use_transform_restrict = enable; }
1376 void setProlongateTransform(bool enable = true) { use_transform_prolongate = enable; }
1377 void setRestrictTransformAfterQuantization(bool enable = true) { transform_after_quantization_restrict = enable; }
1378 void setProlongateTransformAfterQuantization(bool enable = true) { transform_after_quantization_prolongate = enable; }
1387 {
1388 transform_before_and_after_quantization = enable;
1389 }
1390 bool isRestrictTransformAfterQuantizationEnabled() const { return transform_after_quantization_restrict; }
1391 bool isProlongateTransformAfterQuantizationEnabled() const { return transform_after_quantization_prolongate; }
1392 void setRestrictBitlengthEncoding(bool enable = true);
1393 void setProlongateBitlengthEncoding(bool enable = true);
1394 void setRestrictZigzagEncoding(bool enable = true) { use_zigzag_restrict = enable; }
1395 void setProlongateZigzagEncoding(bool enable = true) { use_zigzag_prolongate = enable; }
1396 bool isRestrictZigzagEncodingEnabled() const { return use_zigzag_restrict; }
1397 bool isProlongateZigzagEncodingEnabled() const { return use_zigzag_prolongate; }
1398 bool isRestrictBitlengthEncodingEnabled() const { return use_bitlength_restrict; }
1399 bool isProlongateBitlengthEncodingEnabled() const { return use_bitlength_prolongate; }
1400
1401 // Apply graph lifting using the interface topology supplied at construction.
1402 std::vector<Scalar> applyTransform(const std::vector<Scalar>& data) const {
1403 std::vector<int> empty;
1404 return applyTransform(data, empty);
1405 }
1406
1407 // Apply currently selected transform using optional per-neighbor interface indices.
1408 std::vector<Scalar> applyTransform(const std::vector<Scalar>& data,
1409 const std::vector<int>& iface_idx) const {
1411 return applyGraphLiftingTransform(data, iface_idx);
1412 return data;
1413 }
1414
1415 std::vector<Scalar> inverseTransform(const std::vector<Scalar>& data) const {
1416 std::vector<int> empty;
1417 return inverseTransform(data, empty);
1418 }
1419
1420 std::vector<Scalar> inverseTransform(const std::vector<Scalar>& data,
1421 const std::vector<int>& iface_idx) const {
1423 return inverseGraphLiftingTransform(data, iface_idx);
1424 return data;
1425 }
1426
1427 // Performance statistics tracking (LOCAL VERSION)
1439
1440 double getCompressionRatio() const {
1441 return total_sent_bytes > 0 ? (double)total_original_sent_bytes / total_sent_bytes : 1.0;
1442 }
1443
1456
1457 void printSummary(int subdomain_id = -1, std::string const& label = "") const {
1458 std::string prefix = subdomain_id >= 0 ? "[Subdomain " + std::to_string(subdomain_id) + "] " : "";
1459 std::cout << "\n" << prefix << "=== " << label << " Compression Statistics ===" << '\n';
1460 std::cout << prefix << "Original Vol (Send): " << total_original_sent_bytes << " bytes" << '\n';
1461 std::cout << prefix << "Original Vol (Recv): " << total_original_received_bytes << " bytes" << '\n';
1462 std::cout << prefix << "Total Sent: " << total_sent_bytes << " bytes" << '\n';
1463 std::cout << prefix << "Total Recv: " << total_received_bytes << " bytes" << '\n';
1464 std::cout << prefix << "Logical streams: " << total_stream_bytes << " bytes" << '\n';
1465 std::cout << prefix << "Stream padding: " << total_stream_padding_bytes << " bytes" << '\n';
1466 if (total_sent_bytes > 0)
1467 std::cout << prefix << "Ratio (Send): " << getCompressionRatio() << ":1" << '\n';
1468 std::cout << prefix << "============================\n" << '\n';
1469 }
1470 };
1471
1474 mutable std::shared_ptr<std::mutex> stats_mutex_restrict = std::make_shared<std::mutex>();
1475 mutable std::shared_ptr<std::mutex> stats_mutex_prolongate = std::make_shared<std::mutex>();
1476
1477 // Accessors for aggregated reporting.
1480
1481 void resetStats() {
1482 std::lock_guard<std::mutex> lock_r(*stats_mutex_restrict);
1483 std::lock_guard<std::mutex> lock_p(*stats_mutex_prolongate);
1484 stats_restrict.reset();
1485 stats_prolongate.reset();
1486 prolongate_constant_header_bytes=0;
1487 }
1488 void printStats() const {
1489 stats_restrict.printSummary(this->id, "Restrict");
1490 stats_prolongate.printSummary(this->id, "Prolongate");
1491 }
1492
1493 // Per-iteration encoding diagnostics (only if enableEncodingCheck(true))
1495 size_t encoded_msgs = 0;
1496 size_t fallback_msgs = 0;
1498 size_t missing_symbol = 0;
1499 size_t recv_fallback = 0;
1500
1501 void reset() {
1502 encoded_msgs = 0;
1503 fallback_msgs = 0;
1504 missing_codebook = 0;
1505 missing_symbol = 0;
1506 recv_fallback = 0;
1507 }
1508 };
1509
1512 void resetEncodingSummary() const { encsum_restrict.reset(); encsum_prolongate.reset(); }
1513
1514 private:
1515 // Build fallback interface graph from interface membership only
1516 // (used if matrix-based setup was not provided).
1517 void buildInterfaceGraph() const;
1518 void ensureInterfaceGraph() const;
1519 static void addUndirectedEdge(std::vector<std::vector<int>>& graph, int a, int b);
1520 static void addOrSetWeightedEdge(std::vector<std::vector<int>>& graph,
1521 std::vector<std::vector<Scalar>>& graph_weights,
1522 int a, int b, Scalar w, bool overwrite);
1523
1524 // Build a deterministic two-level split for one neighbor interface.
1525 // Endpoints may have different local matrix graphs. Exchange the producer plan.
1526 void buildTwoLevelSplit(std::vector<int> const& iface_idx,
1527 std::vector<int>& coarse,
1528 std::vector<int>& fine,
1529 std::vector<std::vector<int>>& coarse_neighbors_of_fine,
1530 std::vector<std::vector<Scalar>>& coarse_weights_of_fine) const;
1531
1532 // Connectivity-aware lifting analysis/synthesis on one neighbor stream.
1533 // This is a second-generation wavelet style transform on graphs:
1534 // - coarse coefficients are copied DoFs on C
1535 // - detail coefficients are prediction residuals on F from neighboring C
1536 // Input/Output layout:
1537 // - Input in nodal-major layout [node0(c0..cm-1), node1(...), ...]
1538 // - Output retains nodal-major positions; fine positions contain prediction details.
1539 std::vector<Scalar> applyGraphLiftingTransform(std::vector<Scalar> const& data,
1540 std::vector<int> const& iface_idx) const;
1541 std::vector<Scalar> inverseGraphLiftingTransform(std::vector<Scalar> const& data,
1542 std::vector<int> const& iface_idx) const;
1543
1544 // Exact integer-domain counterpart of graph lifting. Values are transformed
1545 // in the quantized fixed-width domain; zigzag maps signed modular details to
1546 // unsigned symbols without losing information.
1547 std::vector<quantizedScalar> applyIntegerGraphLiftingTransform(
1548 std::vector<quantizedScalar> const& data,
1549 std::vector<int> const& iface_idx,
1550 bool zigzag) const;
1551 std::vector<quantizedScalar> inverseIntegerGraphLiftingTransform(
1552 std::vector<quantizedScalar> const& data,
1553 std::vector<int> const& iface_idx,
1554 bool zigzag, int producer = -1) const;
1555
1556 // Float lifting is performed once per producer on disjoint owner-set groups.
1557 // Coefficients retain nodal positions, so every destination receives the same
1558 // quantized coefficient and uses the producer's predictor for reconstruction.
1559 bool floatLifting(bool residual) const
1560 {
1562 (residual ? use_transform_restrict &&
1563 (!transform_after_quantization_restrict || transform_before_and_after_quantization)
1564 : use_transform_prolongate &&
1565 (!transform_after_quantization_prolongate || transform_before_and_after_quantization));
1566 }
1567 IntegerLiftingPlan<Scalar> const& floatLiftingPlan(std::vector<int> const& idx,
1568 int producer = -1) const;
1569 std::vector<Scalar> floatLift(std::vector<Scalar> const& data,
1570 std::vector<int> const& idx, bool inverse,
1571 int producer = -1) const;
1572 deqTransmissionType quantizationInput(bool residual) const;
1573 void reconstructOwnFloat(bool residual);
1574 mutable std::map<std::vector<int>,IntegerLiftingPlan<Scalar>> local_float_plans;
1575 std::map<int,IntegerLiftingPlan<Scalar>> producer_float_plans;
1576
1577 IntegerLiftingPlan<Scalar> integerLiftingPlan(std::vector<int> const& idx,
1578 int producer = -1) const;
1579 std::map<int,IntegerLiftingPlan<Scalar>> producer_lifting_plans;
1580 bool require_producer_lifting_plans = false;
1581 bool producer_lifting_setup_stale = false;
1582
1583 };
1584
1585}
1586
1587#endif
std::vector< Scalar > apply(const std::vector< Scalar > &data) const override
std::vector< Scalar > inverse(const std::vector< Scalar > &data) const override
std::vector< Scalar > inverse(const std::vector< Scalar > &deltas) const override
std::vector< Scalar > apply(const std::vector< Scalar > &data) const override
std::vector< Scalar > apply(const std::vector< Scalar > &data) const override
std::vector< Scalar > inverse(const std::vector< Scalar > &data) const override
virtual void dequantize(const TransmissionScalar &quantizedData, double &data, double typeMin, double minVal, double scale) const =0
virtual ~Quantization()=default
virtual void quantize(const double &data, TransmissionScalar &quantizedData, double typeMin, double typeMax, double minVal, double scale)=0
void quantize(const double &data, TransmissionScalar &quantizedData, double typeMin, double typeMax, double minVal, double scale) override
void dequantize(const TransmissionScalar &quantizedData, double &data, double typeMin, double minVal, double scale) const
Dune::BlockVector< Dune::FieldVector< Scalar, 1 > > Vector
void diagnosticProlongationWeights(Vector &weights) const
Read normalized producer weights into a full scalar-DOF vector. Caller sizes the vector to the local ...
Dune::BlockVector< XEntry > XVector
std::vector< unsigned char > excludedGlobal
void resetInterfaceAveragingWeights()
Keeps only this subdomain's contribution to the averaging weights.
std::vector< int > const & localIdx(int s) const
void setInterfaceAveragingWeights(int s, XVector const &rho)
Receives the averaging weights from the given subdomain.
void setExcludedLocalDofs(std::vector< int > const &dofs)
void setInterfaceClassifications(InterfaceClassification const &classifications)
std::vector< int > filteredLocalIdx(int s) const
Dune::FieldVector< Scalar, m > XEntry
InterfaceClassification interface_classifications
void getInterfaceAveragingWeights(int s, XVector &rho) const
Provides the averaging weights to the given subdomain.
SpaceTransferBase(int id, Interfaces const &ifs)
Constructor.
void postProlongate(Vector const &u, Vector &du) const
Computes difference of averaged interface values to own interface values and imbues them into the sub...
void setRestrictBitlengthEncoding(bool enable=true)
void setNodeLocalCompressionBypass(std::vector< int > const &nodes)
Keep any DOF with two same-node owners exact on ALL its copies. Configure before domain plan/weight e...
std::vector< TransmissionScalar > valueToVecTransmission(Scalar value) const
SpaceTransferDataCompression(int id, Interfaces const &ifs)
Constructor.
void appendProlongateSymbols(std::vector< quantizedScalar > &out) const
PacketStages inspectPacketStages(int peer, bool residual) const
Dune::BlockVector< Dune::FieldVector< Scalar, 1 > > Vector
void setGraphLiftingFromMatrix(MatrixLike const &mat)
std::shared_ptr< std::mutex > stats_mutex_prolongate
void resetPublishedResidual()
Resets the published residual to zero.
void setGraphLiftingTopologyAndWeights(TopologyMatrixLike const &topologyMat, WeightMatrixLike const &weightMat)
Scalar VecTransmissionToValue(const std::vector< TransmissionScalar > &bytes) const
static void setFpgaAsciiDumpSubdomainFilter(int subdomain)
void setProlongateZeroPreserving(bool enable)
Enable symmetric exact-zero quantization of weighted corrections.
void getInterfaceValues(int s, TransmissionType &values) const
Provides the weighted own interface dof values , possibly compressed.
Dune::BlockVector< Dune::FieldVector< TransmissionScalar, m > > TVector
void preProlongate(Vector const &u)
Prepares exchange of interface values.
void setInterfaceResidualUpdate(int s, TransmissionType const &dres)
CompressionStatsV2 const & restrictStats() const
std::vector< unsigned char > exportIntegerLiftingPlan(int consumer) const
Export producer prediction plans for the selected R/P orders during setup.
void setRestrictQuantizationBits(int bits)
Set quantization bit depth for restriction only.
static void buildSharedRestrictCodebookFromSymbols(std::vector< quantizedScalar > const &symbols)
void setSymbolHistogramOutput(std::string directory)
std::vector< Scalar > inverseTransform(const std::vector< Scalar > &data) const
void setRestrictZeroPreserving(bool enable)
Enable experimental symmetric, exact-zero restriction quantization.
void importIntegerLiftingPlan(int producer, std::vector< unsigned char > const &bytes)
Cache a neighbor's predictor; weights retain their Scalar precision.
GroupedProlongationProbe diagnosticGroupedProlongation(std::size_t localSize, int precision, std::size_t groupSize) const
Read-only grouped quantization of the current weighted prolongation buffer. Groups follow producer un...
void appendRestrictRawSymbols(std::vector< quantizedScalar > &out) const
void prepareIntegerLiftingPlans()
Prepare a fresh setup exchange; missing producer plans subsequently fail closed.
std::vector< Scalar > inverseTransform(const std::vector< Scalar > &data, const std::vector< int > &iface_idx) const
void enableTransform(TransformType type=TransformType::GRAPH_LIFTING)
void setTransformBeforeAndAfterQuantization(bool enable=true)
std::shared_ptr< std::mutex > stats_mutex_restrict
void setCompressionMinInterfaceSize(std::size_t minValues)
void setProlongateQuantizationBits(int bits)
Set quantization bit depth for prolongation only.
void appendProlongateRawSymbols(std::vector< quantizedScalar > &out) const
void setQuantizationBits(int bits)
Set quantization bit depth for both restriction and prolongation.
void setInterfaceValues(int s, TransmissionType const &values)
Receives the weighted (and possibly compressed )interface dof values of an adjacent subdomain.
void setProlongateGroupSize(std::size_t size)
Enable affine producer-union prolongation groups (zero keeps legacy packets). Groups count non-exclud...
void setExcludedLocalDofs(std::vector< int > const &dofs)
void setProlongateConstantSplit(bool enable)
Split a producer constant before weighting/quantizing prolongation. Choose c as the float32 mean of u...
std::vector< Scalar > applyTransform(const std::vector< Scalar > &data) const
void get_globalIndex(std::set< int > &globalIndex_notActive)
std::pair< double, double > unpackMetadata(std::vector< TransmissionScalar > const &bytes) const
std::vector< Scalar > applyTransform(const std::vector< Scalar > &data, const std::vector< int > &iface_idx) const
Dune::FieldVector< TransmissionScalar, m > TEntry
void setInterfaceClassifications(InterfaceClassification const &classifications)
void setProlongateTransformAfterQuantization(bool enable=true)
std::vector< Dune::FieldVector< quantizedScalar, m > > quantizedType
the data type that is used for actual data exchange between subdomains
std::vector< TransmissionScalar > packMetadata(double scale, double minValue) const
void appendRestrictSymbols(std::vector< quantizedScalar > &out) const
CompressionStatsV2 const & prolongateStats() const
void setProlongateBitlengthEncoding(bool enable=true)
static std::uint64_t sharedRestrictCodebookBits()
static void setFpgaAsciiDumpDirectory(std::string directory)
static void buildSharedProlongateCodebookFromSymbols(std::vector< quantizedScalar > const &symbols)
void getInterfaceResidualUpdate(int s, TransmissionType &dres) const
std::uint64_t prolongateConstantHeaderBytes() const
Additional sent header bytes, already included in prolongateStats().
static std::string const & fpgaAsciiDumpDirectory()
static std::uint64_t sharedProlongateCodebookBits()
void setInterfaceAveragingWeights(int s, XVector const &rho)
Cache existing setup weights for reconstructing a producer constant.
void postProlongate(Vector const &u, Vector &du) const
Computes difference of averaged interface values to own interface values and imbues them into the sub...
void getInterfaceResidualUpdate(int s, TransmissionType &dres) const
Dune::BlockVector< XEntry > XVector
void resetPublishedResidual()
Resets the published residual to zero.
Dune::FieldVector< TransmissionScalar, m > TEntry
void setInterfaceResidualUpdate(int s, TransmissionType const &dres)
void get_globalIndex(std::set< int > &globalIndex_notActive)
Dune::FieldVector< Scalar, m > XEntry
void preProlongate(Vector const &u)
Prepares exchange of interface values.
SpaceTransfer(int id, Interfaces const &ifs)
Constructor.
void postRestrict(Vector &r)
Dune::BlockVector< Dune::FieldVector< Scalar, 1 > > Vector
void preRestrict(Vector const &r)
void setInterfaceValues(int s, TransmissionType const &values)
Receives the weighted (and possibly compressed )interface dof values of an adjacent subdomain.
std::vector< TEntry > TransmissionType
the data type that is used for actual data exchange between subdomains
void getInterfaceValues(int s, TransmissionType &values) const
Provides the weighted own interface dof values , possibly compressed.
virtual std::vector< Scalar > inverse(const std::vector< Scalar > &data) const =0
virtual ~Transform()=default
virtual std::vector< Scalar > apply(const std::vector< Scalar > &data) const =0
std::vector< std::pair< int, std::vector< int > > > Interfaces
A data structure describing the interfaces of a subdomain.
constexpr R power(R base, int exp)
Computes integral powers of values in a multiplicative half-group.
Definition power.hh:31
void printVector(const std::vector< T > &vec, const std::string &label)
std::vector< std::pair< int, int > > InterfaceClassification
void printSummary(int subdomain_id=-1, std::string const &label="") const
static double decode(double code, double maxCode, double scale)