niobium/compiler.h
Niobium Client — Minimal Compiler API
User-facing API for controlling FHETCH instruction trace recording. This is the strict-minimum subset of the Niobium compiler interface needed to record instruction traces on the client side.
Usage:
#include "niobium/compiler.h"
niobium::compiler().init(argc, argv);
niobium::compiler().start();
// ... OpenFHE operations (probes fire automatically) ...
niobium::compiler().stop();Include: #include "niobium/compiler.h"
Declarations
enum niobium::CapturedKind
enum class CapturedKind : uint8_t { SRP, MRP, SRPArray, MRPArray }Shape of the value passed to tag_input / tag_output. Mirrors the four overloads in fhetch_api.h.
| Value | Description |
|---|---|
SRP | |
MRP | |
SRPArray | |
MRPArray |
enum niobium::TraceFormat
enum class TraceFormat : uint8_t { Text, Binary, Both }Which serialization of the recorded trace to write.
Selected with --trace-format=<text|binary|both> on the CLI consumed by init(). The two forms describe the same program; the binary one is smaller and faster to read, and the text one is human-readable.
| Value | Description |
|---|---|
Text | |
Binary | |
Both |
struct niobium::CapturedShape
struct niobium::CapturedShapePer-record shape returned by the for_each_captured_* helpers in compiler_internal.h. per_element_moduli has size 1 for SRP / MRP (the element's moduli list) and size K for SRPArray / MRPArray (one list per array position).
Fields
| Name | Declaration | Description |
|---|---|---|
kind | CapturedKind kind | |
per_element_moduli | std::vector<std::vector<uint64_t>> per_element_moduli |
struct niobium::CapturedInputRecord
struct niobium::CapturedInputRecordPer-record snapshot of a captured input. One record per distinct tag_input name, with shape + per-residue values + addr_ids in encounter order.
Fields
| Name | Declaration | Description |
|---|---|---|
name | std::string name | |
shape | CapturedShape shape | |
addr_ids | std::vector<uint64_t> addr_ids | |
per_residue_values | std::vector<std::vector<uint64_t>> per_residue_values |
class niobium::Compiler
class niobium::CompilerCompiler
Compiler()~Compiler
~Compiler()SESSION LIFECYCLE
init
void init(int &argc, char **argv)Initialize compiler with command-line arguments. Parses and consumes Niobium-specific flags from argv.
enable_auto_tagging
void enable_auto_tagging()Opt into cooperative auto-tagging: the host program drives the record/replay lifecycle explicitly (init/cache_parameters/start/stop/ probe/replay/result), while the auto-facade transparently tags inputs and keys (capturing their file paths) via the OpenFHE deserialize hooks. No YAML config is consulted. No-op unless a strong auto-facade implementation is linked. Call right after init(), before loading the crypto context.
start
bool start()Begin instruction recording. Must be called before performing any FHE operations to record.
Returns: true if recording started successfully.
stop
bool stop()Stop instruction recording and finalize the FHETCH trace. Writes the trace file and serializes input/output metadata.
Returns: true if recording stopped successfully.
pause
bool pause()Temporarily pause recording. Use to exclude deserialization or plaintext operations from the trace.
resume
bool resume()Resume recording after pause().
PROGRAM METADATA
set_program_info
void set_program_info(const std::string &name, const std::string &version, const std::string &description)Set program information for debugging and identification.
set_build_info
void set_build_info(const std::string &file, int line, const std::string ×tamp)Set build information for traceability.
Parameters
file— Source file path (use__FILE__).line— Source line number (use__LINE__).timestamp— Build timestamp (use__TIMESTAMP__).
CACHE MANAGEMENT
CacheParameters
typedef std::vector<std::pair<std::string, std::string>> CacheParametersVector of key-value pairs used to determine cache validity.
cache_parameters
void cache_parameters(CacheParameters ¶ms)Set cache parameters for instruction trace validation. Cache parameters uniquely identify the computation configuration.
is_cache_valid
bool is_cache_valid()Check if the cached instruction trace is valid for reuse.
Returns: true if cache is valid (skip recording), false if recording needed.
INPUT / OUTPUT TAGGING (OpenFHE types)
tag_input
template <typename T>
void tag_input(const std::string &input_name, const T &value, std::optional<std::filesystem::path> file=std::nullopt)Tag an input ciphertext/plaintext for recording.
Parameters
input_name— Unique name for the input.value— OpenFHE Ciphertext or Plaintext to tag.file— Optional file path for data loading during replay.
template <typename T>
void tag_input(const std::string &input_name, T &value, std::optional<std::filesystem::path> file=std::nullopt)Tag an input (non-const overload, for in-place ID capture).
probe
template <typename T>
void probe(const std::string &var_name, const T &value)Tag an output ciphertext/plaintext for recording. Call for all computation outputs before stop().
Parameters
var_name— Unique name for the output variable.value— OpenFHE Ciphertext or Plaintext to tag as output.
template <typename T>
void probe(const std::string &var_name, const std::vector<T> &values)Tag a vector of output ciphertexts for recording.
CRYPTO CONTEXT
capture_crypto_context
template <typename CryptoContextType>
void capture_crypto_context(const CryptoContextType &cc)Capture the cryptographic context for serialization. Must be called after all keys are loaded and before recording starts.
Parameters
cc— OpenFHE CryptoContext (lbcrypto::CryptoContext<DCRTPoly>).
set_ring_dimension
void set_ring_dimension(uint64_t N)Set the ring dimension for the FHETCH simulator. Called automatically by capture_crypto_context(), or can be set manually.
set_crypto_context_info
void set_crypto_context_info(const std::string &scheme_name, uint32_t multiplicative_depth, uint32_t scaling_mod_size, const std::string &security_level, const std::vector<uint64_t> &modulus_chain)Set crypto context metadata for replay.json. Called by capture_crypto_context template instantiation.
set_key_start_addr_id
void set_key_start_addr_id(const std::string &key_type, uint64_t addr_id)Set key start addr_id for a given key type.
reserve_addresses
static void reserve_addresses(uint64_t next_addr)Advance the FHETCH address allocator to at least next_addr so the next call to tag_keys/tag_input places polynomials starting there. Used to match the compiler's fixed key-start offsets (e.g. 25 for evalmult, 49 for evalautomorphism).
tag_keys
template <typename CryptoContextType>
void tag_keys(const CryptoContextType &cc)Capture evaluation key polynomial data for the simulator. Iterates over all EvalMult and EvalAutomorphism keys loaded in the CryptoContext and extracts their polynomial coefficients. Call after deserializing keys and before start().
Parameters
cc— OpenFHE CryptoContext containing the loaded keys.
tag_bootstrap_precompute
template <typename CryptoContextType>
void tag_bootstrap_precompute(const CryptoContextType &cc)Internal: capture CKKS bootstrap precomputation plaintexts. Invoked automatically from stop() via the hook registered by capture_crypto_context(); not meant to be called by user code.
RECORDING MODES
enable_hollow_mode
void enable_hollow_mode(bool enabled=true)Enable or disable hollow recording mode. When enabled, OpenFHE operations skip expensive polynomial math but preserve structure and fire probes. Reduces recording time from hours to seconds for large workloads.
is_hollow_mode
bool is_hollow_mode() constCheck if hollow recording mode is active.
enable_multithreaded_recording
void enable_multithreaded_recording()Enable multi-threaded recording mode. Call before start() when using multithreading in user code.
is_multithreaded
bool is_multithreaded() constCheck if multi-threaded recording is enabled.
enable_input_streaming
void enable_input_streaming(bool enabled=true)Stream tagged input/key polynomial data straight to the on-disk .bin files at tag time and drop the in-RAM copy, instead of buffering every captured input's coefficient values until stop(). Recording memory otherwise scales with the number of tagged inputs (each ~one ciphertext worth of polynomials), which dominates input-heavy workloads.
Trade-off: the in-process replay() simulator-load path consumes the buffered values, so enable this only for cooperative / transport replay flows where the trace is replayed in a separate process that reads the .bin files back from disk. Call before start().
is_input_streaming
bool is_input_streaming() constCheck if input streaming (drop buffered input values) is active.
release_openfhe_data_at_replay
void release_openfhe_data_at_replay(bool enabled=true)Cooperative replay() delegates execution to a subprocess that reads the project from disk, so the recording process no longer needs any OpenFHE polynomial data — by default it releases everything it can reach right before spawning the worker: SDK-retained ciphertexts, buffered captured-input values, and ALL OpenFHE evaluation keys (relinearization / rotation / sum — often multi-GB). Pass false to opt out if this process keeps computing after replay(): further Eval* calls, re-tagging live ciphertexts, or another record cycle in the same process all need the released state. result() and output serialization are unaffected (they read the reconstructed probe files, not key material). Only cooperative (auto-tagging) replay releases; in-process and epoch-recording flows never do.
is_release_openfhe_data_at_replay
bool is_release_openfhe_data_at_replay() constCheck whether cooperative replay() releases OpenFHE data (default true).
FHETCH MODE
is_fhetch_mode
bool is_fhetch_mode() constCheck if operating in FHETCH mode (set automatically when any FHETCH API function is called, vs. OpenFHE probe path).
set_fhetch_mode
void set_fhetch_mode()Activate FHETCH mode (called internally by FHETCH API functions).
REPLAY (FHETCH Simulator)
replay
bool replay()Replay the recorded trace through the FHETCH simulator. Executes the .fhetch trace using OpenFHE modular arithmetic, producing computed polynomial values. Cooperative (auto-tagging) sessions dispatch a disk-based subprocess replay: fhetch_sim --project for target "local" (or, when NBCC_FHETCH_DRIVER is set, the fhetch_driver roundtrip harness), nbcc_fhetch_replay otherwise.
Returns: true if replay succeeded with zero errors.
replay_project
bool replay_project(const std::string &target, const std::filesystem::path &dir, const std::string &opt_level="O0", bool niobium_hw=false)Replay the on-disk project at dir to completion in a fresh subprocess, writing serialized_probes/<name>.ct into dir. For target "local" spawns the bundled fhetch_sim --project=<dir> (located via NBCC_FHETCH_SIM, else "fhetch_sim" on PATH); for any other target forwards to nbcc_fhetch_replay --project=<dir> --target=<target>. Reads nothing from this Compiler — the target, opt-level, and hardware-format flag all come from the call — so N threads may call it concurrently with distinct dirs. opt_level and niobium_hw (the full montgomery + bit-reversal format, i.e. --niobium_hw) forward only to non-local targets.
result
template <typename CryptoContextType, typename CiphertextType>
bool result(CryptoContextType &cc, const std::string &var_name, CiphertextType &result)Retrieve a hardware-computed result ciphertext after replay.
Parameters
cc— CryptoContext for result assembly.var_name— Name of the output (as passed to probe()).result— Ciphertext to populate with computed values.
Returns: true if the result was retrieved successfully.
reconstruct_probes
void reconstruct_probes() constReconstruct probe ciphertexts from simulator output.
refresh_all_inputs
void refresh_all_inputs()Re-extract polynomial data from all stored OpenFHE objects. Called at replay() time to capture polynomials at their current FHETCH addresses, including derived addresses created by OpenFHE's internal processing between tag_input/tag_keys and start().
refresh_stale_inputs
int refresh_stale_inputs()Cooperative-replay staleness refresh: read inputs.json, and for each file-backed input whose on-disk source file mtime differs from the recorded mtime, reload that file and rewrite its .bin against the recorded .ids addresses. Unchanged inputs are left untouched. Lets a replay run pick up new keys/data without re-recording or re-running the computation. Returns the number of inputs refreshed.
FUNCTIONAL EPOCHS
start_epoch
void start_epoch()Mark the start of a new epoch's computation. On first call, memorizes the polynomial ID base. On subsequent calls, resets the counter back to keep each epoch's address space predictable.
stop_epoch
bool stop_epoch()Trigger a functional epoch boundary. Performs: stop → write trace → reset state → resume recording. Each epoch is cached independently in program_dir/epoch_N/.
epoch_id
uint32_t epoch_id() constGet the current epoch ID (0 before first stop_epoch() call).
STATE QUERIES
running_p
bool running_p()Check if the compiler is currently recording instructions.
stopped_p
bool stopped_p()Check if stop() has been called (recording is complete).
program_name
std::string program_name()Get the current program name (including cache parameters).
get_program_directory
std::filesystem::path get_program_directory() constGet or create the program directory for output files.
set_program_directory
void set_program_directory(const std::filesystem::path &dir)Override the program directory for output files. When set (non-empty), get_program_directory() returns this path verbatim instead of the cwd/<program_name> default. Set before stop()/stop_epoch() writes the trace so inputs, templates, and the .fhetch land in dir.
CONVENIENCE
run
template <typename Lambda, typename... Args Args>
void run(Lambda &&work, Args &&...args)Run a lambda with automatic start/stop bracketing.
clear_captured_inputs
void clear_captured_inputs()Clear all captured input data (called before refresh).
clear_captured_outputs
void clear_captured_outputs()Clear all captured output probe data.
clear_captured
void clear_captured()Clear both captured inputs and outputs (end-of-cycle convenience).
set_auto_capture_at_stop
void set_auto_capture_at_stop(std::function<void()> fn)Register a callback to run inside stop() right before the replay index is written. Used by capture_crypto_context() template specializations to auto-capture CC-derived precomputed data (e.g. CKKS bootstrap precompute) without a user-facing API.
set_auto_capture_bootstrap_precompute
void set_auto_capture_bootstrap_precompute(bool enabled)Enable or disable the automatic CKKS bootstrap precompute capture installed by capture_crypto_context() (default: enabled).
auto_capture_bootstrap_precompute_enabled
bool auto_capture_bootstrap_precompute_enabled() constset_post_recording_hook
void set_post_recording_hook(std::function<void()> fn)Register a callback to run inside stop() AFTER trace_writer.stop_recording() but BEFORE write_replay_json. Lets downstream layers do OpenFHE work without polluting the trace. Pass nullptr to clear; reset() also clears.
reset
void reset()Clear all per-program singleton state (captured inputs/outputs, trace writer, program_dir, recording flags, hooks). Does NOT touch hollow_mode, multithreaded, or target.
store_input_element
void store_input_element(const std::string &input_name, CapturedKind kind, bool starts_new_element, uint64_t addr_id, uint64_t modulus, const std::vector<uint64_t> &values)Append a residue to a captured input record. Sets kind on the record's first call; later calls must match the existing kind. starts_new_element marks an SRPArray / MRPArray element boundary.
store_output_probe
void store_output_probe(const std::string &output_name, CapturedKind kind, bool starts_new_element, uint64_t addr_id, uint64_t modulus)Append a residue to a captured output probe. Same semantics as store_input_element above.
set_input_source
void set_input_source(const std::string &input_name, const std::string &source_path)Record the on-disk source file a captured input was loaded from, plus its current modification time. Persisted into inputs.json so a later replay run can detect (by mtime) which input files changed and refresh only those against the recorded addresses — the cached_input/cached_key equivalent for cooperative auto-tagging. No-op if input_name has no captured record yet.
niobium::compiler
Compiler & compiler()Get the global Compiler singleton instance.
Something not looking right? Suggest a change on GitHub.