Rickesh's picture
Upload folder using huggingface_hub
829dbce verified
Raw
History Blame Contribute Delete
7.62 kB
// ctxstream -- treat an oversized context like a video stream.
//
// The failure this exists to fix, measured on a 4B model over a 261,226-token
// corpus on a 6GB card: the model swept every segment correctly and then, asked
// which label was least common, replied "Status: beta, Status: delta, Status:
// gamma, Status: alpha". It listed the candidates instead of selecting. Earlier
// runs with more segments combined 65 partial counts wrongly.
//
// Both failures are the same mistake in the harness, not the model: a language
// model was asked to plan a traversal and to aggregate arithmetic. Streaming
// splits those out.
//
// manifest segments planned in code, up front, deterministic
// buffer N segments in flight, latency hidden behind compute
// decode model sees ONE segment, emits STRUCTURED records, never prose
// reduce aggregation in code, over parsed records
//
// The model's only job is extraction from a window it comfortably fits.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace ctxstream {
// ---------------------------------------------------------------- manifest
struct Segment {
int index = 0;
std::size_t offset = 0;
std::size_t length = 0;
// Segments may overlap so a record straddling a boundary is seen whole by at
// least one segment. The reducer dedupes on record identity.
std::size_t overlap_prefix = 0;
};
struct ManifestOptions {
// Sized to what the serving model actually fits, not what it advertises.
// Measured: gemma4:e4b holds 32,768 tokens in 3.3GB on a 6GB card.
std::size_t segment_chars = 60000;
std::size_t overlap_chars = 400;
// Prefer splitting on a record boundary within this slack of the target, so
// segments do not cut a row in half.
std::size_t boundary_slack = 4000;
std::string record_delim = "\n";
};
// Deterministic. No model call. Runs before anything is dispatched, which is
// the point: the plan cannot be wrong in a way the model has to recover from.
std::vector<Segment> plan(const std::string& text, const ManifestOptions& opt);
std::string segment_text(const std::string& text, const Segment& s);
// ---------------------------------------------------------------- codegraph
//
// A codebase is not a character stream. Cutting it every N chars splits
// functions, separates a call from its definition, and hands the model
// fragments no human would review. When the input is a directory, the default
// path is: scan -> graph -> segment along graph structure -> stream.
enum class NodeKind { File, Function, Class, Struct, Other };
struct SymbolNode {
int id = 0;
NodeKind kind = NodeKind::Other;
std::string name;
int file = 0; // index into CodeGraph::files
int line = 0;
std::size_t offset = 0;
std::size_t length = 0;
};
enum class EdgeKind { Includes, References };
struct GraphEdge {
int from = 0; // file index
int to = 0; // file index
EdgeKind kind = EdgeKind::Includes;
};
struct FileNode {
int id = 0;
std::string path; // relative to the scanned root
std::string language;
std::size_t bytes = 0;
int symbols = 0;
};
struct CodeGraph {
std::string root;
std::vector<FileNode> files;
std::vector<SymbolNode> symbols;
std::vector<GraphEdge> edges;
// Files skipped and why, so a sweep can never silently miss part of the
// repo and still report a confident answer.
std::vector<std::pair<std::string, std::string>> skipped;
};
struct ScanOptions {
std::size_t max_file_bytes = 2u * 1024 * 1024;
std::vector<std::string> exclude_dirs = {
".git", "node_modules", "build", "dist", "__pycache__", ".venv",
"venv", "target", ".mypy_cache", ".pytest_cache", "vendor"};
bool follow_symlinks = false;
};
CodeGraph scan_repo(const std::string& root, const ScanOptions& opt);
// Segments that respect the graph: a file is never split mid-symbol, and files
// are ordered so that a file follows the ones it includes wherever the include
// graph is acyclic. Large files fall back to symbol-boundary splitting.
std::vector<Segment> plan_codebase(const CodeGraph& g,
const ManifestOptions& opt,
std::string* packed_text);
std::string graph_summary(const CodeGraph& g);
// ---------------------------------------------------------------- backend
struct Completion {
std::string text;
long prompt_tokens = 0; // 0 when the server does not report it
long output_tokens = 0;
bool ok = false;
std::string error;
};
struct BackendOptions {
std::string host = "127.0.0.1";
int port = 11434;
std::string model = "gemma4:e4b";
std::string path = "/api/chat"; // native route: honours num_ctx AND reports
// prompt_eval_count. The OpenAI-compatible
// route silently ignores num_ctx.
int num_ctx = 32768;
int num_predict = 1024;
int timeout_sec = 900;
};
Completion complete(const BackendOptions& opt,
const std::string& system_prompt,
const std::string& user_prompt);
// Guard against the failure that produced a confident answer from a fragment:
// a server that quietly clips the prompt and never says so. Returns true when
// the reported prompt token count is implausibly small for what was sent.
bool looks_truncated(std::size_t prompt_chars, long prompt_tokens);
// ---------------------------------------------------------------- pipeline
struct SegmentResult {
int index = 0;
std::string raw; // exactly what the model returned
bool ok = false;
bool truncated = false;
std::string error;
long prompt_tokens = 0;
long output_tokens = 0;
double seconds = 0.0;
};
struct PipelineOptions {
// Segments in flight. Buffering, in the video sense: keeps the model busy
// while the next prompt is being assembled.
int concurrency = 2;
int max_retries = 2;
bool verbose = true;
};
// Streams every segment through the model. Returns results in segment order.
// Never aggregates, never interprets -- that is the reducer's job.
std::vector<SegmentResult> stream(const std::string& text,
const std::vector<Segment>& segments,
const std::string& extract_prompt,
const BackendOptions& backend,
const PipelineOptions& pipe);
// ---------------------------------------------------------------- reduce
// One parsed record from a segment. The extraction prompt asks for
// "<key>\t<count>" lines, which is cheap for a small model to emit correctly
// and unambiguous to parse -- unlike prose summaries.
struct Record {
std::string key;
double value = 0.0;
};
std::vector<Record> parse_records(const std::string& raw);
struct Tally {
std::vector<std::pair<std::string, double>> sorted; // ascending by value
double total = 0.0;
int parsed_records = 0;
int unparsed_lines = 0;
};
// Sums per key across every segment. This is the step the model kept getting
// wrong; here it is a loop.
Tally tally(const std::vector<SegmentResult>& results);
// Answer construction is chosen explicitly, after the sweep -- not improvised
// by the model mid-traversal.
enum class Answer { Least, Most, Total, List };
std::string construct(const Tally& t, Answer how, const std::string& label = "Answer");
} // namespace ctxstream