Documentation
¶
Overview ¶
Package agenttrace reads, replays and scores agent workload traces in the replay format of the Evolving Infra benchmarks (the Trie client's schema-v2 traces and schema-v3 tasks, one JSON object per line).
A Task is one agent session: its agents, each a sequence of generate, wait, append_message and replace_context events, and the dependency edges that start a sub-agent after an event of its parent and join it back. A generate event's prompt is either recorded token ids, chat messages to be rendered by the server, or runs of block ids that Blocks expands with the keyed splitmix64 mix of the Trie client, so equal block ids give equal tokens and the server sees exactly the trace's prefix sharing.
Replay sends tasks through a Sender with the client's semantics: a fixed number of concurrent task slots refilled in trace order, a fresh replay cycle (and so fresh block content) for each re-admission of a task, dependency edges between events, waits clipped and scaled, and the stationary warm start, which begins each slot's first task at a uniform cut through its recorded span. A LifecycleWriter records one event per request step in the client's lifecycle schema.
ScoreDir and ScoreLogs score a run's lifecycle events by the rules of the reference score.py: only requests admitted inside the window that are not warm-start requests count, and the prefix hit is token-weighted.
Ceiling computes the prompt-token fraction an engine with one infinite, never-evicting cache could serve (h*), per agent and in total, in the recorded order; Replay computes it at send time over the requests it sent. LostReuse is 1 - h/h* for a measured hit rate h.
Generate writes synthetic tasks in the same format for four shapes: decode-heavy, dynamic (sub-agents and compaction), prefill-heavy, and long-session, a scaled synthetic shape of long multi-turn conversations with idle gaps, modelled on published aggregate statistics (see LongSessionConfig).
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- Constants
- func Generate(w io.Writer, cfg SynthConfig) error
- func LostReuse(h, hstar float64) float64
- func PoolFromTokenizer(dir string) ([]int, error)
- func RunBlocks(runs []Run) uint64
- func TokenIDsSHA256(ids []int) string
- type Agent
- type BlockSpec
- type Blocks
- type CeilingReport
- type Dependency
- type Event
- type EventRef
- type Kind
- type LifecycleEvent
- type LifecycleID
- type LifecycleWriter
- type LongSessionConfig
- type MooncakeRequest
- type Options
- type Prompter
- type Reader
- type Record
- type Registry
- type ReplaySettings
- type Request
- type Response
- type Result
- type Reuse
- type Run
- type Score
- type Sender
- type Shape
- type SynthConfig
- type Task
Examples ¶
Constants ¶
const MooncakeBlockTokens = 512
MooncakeBlockTokens is the block size of the Mooncake FAST'25 traces: each hash id stands for 512 prompt tokens.
Variables ¶
This section is empty.
Functions ¶
func Generate ¶
func Generate(w io.Writer, cfg SynthConfig) error
Generate writes cfg.Tasks synthetic tasks of cfg.Shape to w in the trace format, one task per line. The same configuration always writes the same bytes.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/eval/agenttrace"
)
func main() {
var b strings.Builder
if err := agenttrace.Generate(&b, agenttrace.SynthConfig{Shape: agenttrace.Dynamic, Tasks: 2, Seed: 1}); err != nil {
panic(err)
}
tasks, err := agenttrace.ReadAll(strings.NewReader(b.String()))
if err != nil {
panic(err)
}
for _, t := range tasks {
fmt.Println(t.ID, len(t.Agents), "agents,", len(t.Deps), "edges")
}
}
Output: dynamic-0000 3 agents, 4 edges dynamic-0001 3 agents, 4 edges
func LostReuse ¶
LostReuse returns 1 - h/hstar, the fraction of the ideal cache's reuse that a measured hit rate h lost. It is NaN when hstar is 0 or NaN.
func PoolFromTokenizer ¶
PoolFromTokenizer returns the regular vocabulary ids of the tokenizer in dir, sorted: every id of tokenizer.json's model vocabulary except added tokens and the pad, bos and eos ids of config.json, limited to its vocab_size. It is the pool the reference client draws a portable trace from.
func TokenIDsSHA256 ¶
TokenIDsSHA256 returns the SHA-256 of the JSON list of ids without spaces, the digest the format records for prompts.
Types ¶
type Agent ¶
type Agent struct {
ID string
Events []Event
InitialMessages []json.RawMessage
Tools json.RawMessage
Kind string // metadata.kind, if any
Parent string // metadata.parent, if any
RoutingKey string // metadata.routing_key, if any
ControlOnly bool // metadata.control_only
// Block is the agent's block expansion parameters: its own
// metadata.block_tokens, else the task's, else nil.
Block *BlockSpec
}
An Agent is one agent of a task: the schema-v2 trace of the format.
type BlockSpec ¶
A BlockSpec is a trace's metadata.block_tokens: each block id expands to Size token ids drawn from Pool by a mix keyed by Seed. A spec without a pool is not bound to a tokenizer; NewBlocks then takes one.
type Blocks ¶
type Blocks struct {
// contains filtered or unexported fields
}
Blocks expands the block runs of one replay cycle of one trace.
func NewBlocks ¶
NewBlocks returns the expander of spec for replay cycle cycle. Every replay cycle of a trace gets its own content. The spec's own pool wins over pool, which serves a spec without one.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/eval/agenttrace"
)
func main() {
spec := &agenttrace.BlockSpec{Size: 4, Seed: 12345, Pool: []int{100, 101, 102, 103, 104, 105, 106, 107}}
b, err := agenttrace.NewBlocks(spec, 0, nil)
if err != nil {
panic(err)
}
ids, err := b.Tokens([]agenttrace.Run{{First: 0, Count: 2}}, -1)
if err != nil {
panic(err)
}
again, _ := b.Tokens([]agenttrace.Run{{First: 1, Count: 1}}, -1)
fmt.Println(len(ids), fmt.Sprint(ids[4:]) == fmt.Sprint(again))
}
Output: 8 true
type CeilingReport ¶
A CeilingReport is the ideal-cache reuse of a set of tasks: in total and per agent, keyed by task id and agent id.
func Ceiling ¶
func Ceiling(tasks []*Task, block int, prompts Prompter) (*CeilingReport, error)
Ceiling returns the reuse an engine with one infinite cache of block tokens per block would see on each task replayed alone, in recorded order: each generate is looked up at its recorded start (source_t_s) and its prompt and output are inserted at its recorded end (source_t_s plus source_api_time_s), so that concurrent agents of a task share only what had completed. Tasks without recorded times are taken agent by agent in event order. Each task has its own registry, since separate tasks and replay cycles never share block content.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/eval/agenttrace"
)
func main() {
// One agent whose second prompt extends the first by two blocks.
const trace = `{"schema_version": 2, "trace_id": "t", "events": [
{"type": "generate", "max_tokens": 4, "recorded_prompt_block_runs": [[0, 4]], "recorded_output_block_runs": [[100, 1]], "source_t_s": 0, "source_api_time_s": 1},
{"type": "wait", "seconds": 5, "actor": "tool"},
{"type": "generate", "max_tokens": 4, "recorded_prompt_block_runs": [[0, 6]], "recorded_output_block_runs": [[101, 1]], "source_t_s": 6, "source_api_time_s": 1}],
"metadata": {"block_tokens": {"block_size": 16, "seed": 1, "pool": [7, 8, 9]}}}`
tasks, err := agenttrace.ReadAll(strings.NewReader(strings.ReplaceAll(trace, "\n", " ")))
if err != nil {
panic(err)
}
rep, err := agenttrace.Ceiling(tasks, 16, agenttrace.BlockPrompter(0, nil))
if err != nil {
panic(err)
}
fmt.Printf("%d of %d prompt tokens: h* = %.2f\n", rep.Total.Cached, rep.Total.Prompt, rep.Total.Rate())
fmt.Printf("lost reuse at h = 0.2: %.2f\n", agenttrace.LostReuse(0.2, rep.Total.Rate()))
}
Output: 64 of 160 prompt tokens: h* = 0.40 lost reuse at h = 0.2: 0.50
type Dependency ¶
A Dependency holds After's start until Before has completed (When "complete") or started (When "start").
type Event ¶
type Event struct {
Kind Kind
// Generate.
MaxTokens int
PromptTokens []int
OutputTokens []int
PromptRuns []Run
// PromptLen, when positive, cuts PromptRuns' expansion to that many
// tokens of the trace's block size, and to the same fraction of the
// last block when the replay expands blocks to fewer tokens.
PromptLen int
OutputRuns []Run
SourceT float64 // recorded start, seconds; valid if HasSourceT
SourceAPITime float64 // recorded duration, seconds
HasSourceT bool
Assistant json.RawMessage // recorded_assistant, or nil
Images int // len(recorded_image_data)
// Wait.
Seconds float64
Actor string // "user", "tool" or "other"
// AppendMessage and ReplaceContext.
Messages []json.RawMessage
Reason string
}
An Event is one step of an agent.
A generate event is a model request. Its prompt is PromptTokens, PromptRuns (expanded by Blocks) or, when both are empty, the agent's current messages. A wait event is tool or user time. An append_message event appends Messages[0] to the agent's messages and a replace_context event replaces them with Messages.
type LifecycleEvent ¶
type LifecycleEvent struct {
TsNs int64 `json:"ts_ns"`
Event string `json:"event"`
Request *LifecycleID `json:"request"`
Attrs json.RawMessage `json:"attrs"`
}
A LifecycleEvent is one line of a client lifecycle file. Only the fields the scorer reads are decoded.
func ReadLifecycle ¶
func ReadLifecycle(r io.Reader) ([]LifecycleEvent, error)
ReadLifecycle reads the events of one lifecycle file.
type LifecycleID ¶
type LifecycleID struct {
ExperimentRequestID string `json:"experiment_request_id"`
}
A LifecycleID is the request identity of a lifecycle event.
type LifecycleWriter ¶
type LifecycleWriter struct {
RunID string
CellID string
Arm string
Concurrency int
// contains filtered or unexported fields
}
A LifecycleWriter appends client lifecycle events in the reference client's schema (opx.lifecycle-event.v1), one JSON object per line. It is safe for concurrent use.
func NewLifecycleWriter ¶
func NewLifecycleWriter(w io.Writer, runID string, concurrency int) *LifecycleWriter
NewLifecycleWriter returns a writer appending to w.
func (*LifecycleWriter) Err ¶
func (w *LifecycleWriter) Err() error
Err returns the first write error.
type LongSessionConfig ¶
type LongSessionConfig struct {
MedianTokens int // median prompt length over all requests, in tokens
Turns int // turns from the opening transcript on
TTL time.Duration // the idle time a long gap exceeds
LongGaps float64 // fraction of the gaps between turns that exceed TTL
ColdStarts float64 // fraction of conversations that open cold
}
A LongSessionConfig sets the parameters of the LongSession shape.
LongSession is a scaled synthetic shape modelled on published aggregate statistics of long-context agent serving (median, p90 and maximum prompt length, and a prefix-cache hit rate near 97%, from https://blog.luminal.com/p/how-we-scaled-above-2-t-tokens-in). It is not a recording, sample or reconstruction of anyone's traffic.
Each task is one conversation: a single agent whose prompt only grows. The prompt lengths of all its requests keep the published per-request ratio of median, p90 and maximum, 146:276:550, scaled to MedianTokens: final context lengths are spread over the tasks by quantile anchors fitted so that this holds for the default Turns and medians of 8192 tokens and up, with an assumed floor. Other Turns, shorter contexts and coarser blocks change the spread within a conversation, and so the request-level ratios (by under 10% for a median of 2048 or 64-token blocks). A conversation takes Turns turns from its opening transcript on, or fewer if more would shrink the opening below a quarter of its final length. Each turn appends the previous turn's output (16 to 64 tokens, as fresh blocks: outputs never reappear verbatim) and new tokens, growing the context by 1-3%, so an ideal cache serves about 95-97% of the prompt tokens. The waits between turns are user think times of 1-10 s, except that a LongGaps fraction of them last 1.25-2 times TTL. A ColdStarts fraction of conversations open with their whole opening transcript in one request, as a conversation resumed on, or moved to, a server that has never seen it; the others open with a short message and paste the rest of the opening transcript over up to three quick turns.
func DefaultLongSession ¶
func DefaultLongSession() LongSessionConfig
DefaultLongSession returns the default LongSession parameters: a median prompt of 8192 tokens, so a longest prompt near 30,900 that fits a 32768-token context; 40 turns; a TTL of five minutes; 10% long gaps; and 25% cold starts.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/eval/agenttrace"
)
func main() {
c := agenttrace.DefaultLongSession()
c.MedianTokens = 4096
var b strings.Builder
cfg := agenttrace.SynthConfig{Shape: agenttrace.LongSession, Tasks: 32, Seed: 1, LongSession: &c}
if err := agenttrace.Generate(&b, cfg); err != nil {
panic(err)
}
tasks, err := agenttrace.ReadAll(strings.NewReader(b.String()))
if err != nil {
panic(err)
}
pool := make([]int, 1000)
for i := range pool {
pool[i] = i
}
rep, err := agenttrace.Ceiling(tasks, 16, agenttrace.BlockPrompter(0, pool))
if err != nil {
panic(err)
}
fmt.Printf("%d requests, h* = %.2f\n", rep.Total.Requests, rep.Total.Rate())
}
Output: 1272 requests, h* = 0.96
type MooncakeRequest ¶
type MooncakeRequest struct {
Timestamp int64 `json:"timestamp"`
InputLength int `json:"input_length"`
OutputLength int `json:"output_length"`
HashIDs []uint64 `json:"hash_ids"`
}
A MooncakeRequest is one line of a Mooncake FAST'25 trace (github.com/kvcache-ai/Mooncake, FAST25-release/traces): an arrival time in milliseconds, prompt and output lengths in tokens, and the remapped hash ids of the prompt's 512-token blocks, equal ids marking blocks whose KV cache could be shared.
type Options ¶
type Options struct {
// Concurrency is the number of task slots. Each slot runs one task at
// a time; when it ends, the slot takes the next task in trace order,
// cycling through the tasks again once all have been admitted.
Concurrency int
// Duration stops admission once that much time has passed and then
// cancels requests still in flight. Zero replays each task once and
// waits for all of them.
Duration time.Duration
// WarmStart begins each slot's first task at a uniformly random cut
// through its recorded span (the stationary warm start).
WarmStart bool
// Seed seeds the warm-start draws and trajectory prefixes.
Seed uint64
// DelayScale multiplies every wait; 0 means 1. A negative value
// replays with no waits at all.
DelayScale float64
// MaxToolDelay and MaxUserDelay clip tool and user waits, in seconds,
// before scaling. Zero means no clip.
MaxToolDelay, MaxUserDelay float64
// TokensPerBlock expands each block to that many tokens instead of the
// trace's block size: the first TokensPerBlock tokens of the block's
// full expansion, so equal blocks stay equal and prefix structure is
// kept. Zero keeps the trace's size.
TokensPerBlock int
// Pool is the token pool for traces without their own.
Pool []int
// MapTokens maps every recorded token id t (not block expansions) to
// Pool[t%len(Pool)]. Equal ids stay equal; distinct ids may collide.
MapTokens bool
// TrajectoryPrefix prepends that many random pool tokens, drawn per
// admitted task, to every prompt of the task.
TrajectoryPrefix int
// MaxPromptTokens skips generates whose prompt is longer, as if they
// were before a warm-start cut. Zero means no limit.
MaxPromptTokens int
// MaxOutputTokens caps each request's output. Zero means no cap.
MaxOutputTokens int
// PrefixBlock is the block size of the ideal-cache registry; 0 means 16.
PrefixBlock int
// Lifecycle receives the lifecycle events, if not nil.
Lifecycle *LifecycleWriter
}
Options configure Replay. The zero value of a field selects the reference client's default, except as noted.
type Prompter ¶
A Prompter returns the prompt and output token ids of generate event i of agent a of task t in replay cycle 0. A nil prompt leaves the generate out, as a replay that skips it would.
func BlockPrompter ¶
BlockPrompter returns the Prompter that expands block runs with tokens per block (the spec's size if tokens <= 0) and pool for portable specs, and passes recorded token ids through.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
A Reader reads tasks from a trace file, one JSON object per line.
type Record ¶
type Record struct {
// ID is the request's experiment_request_id in the lifecycle log, a
// digest of its trace, replay cycle and generate position, so the
// same request of two replays of one trace has the same ID.
ID string
Task, Agent string
Cycle uint64
Index int
Warmup bool
PromptTokens int // tokens sent (len(Request.Tokens)); 0 for messages
Ideal int // what the ideal cache held at send time
Response *Response
Err error
}
A Record is the outcome of one request of a replay.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
A Registry models one engine with an infinite, never-evicting prefix cache in blocks of BlockSize tokens, as the reference client's GlobalPrefixRegistry does. Insert records the block chain of a processed sequence; Match returns how many tokens of a prompt that engine could serve from cache. It is safe for concurrent use.
Chains are keyed by the first 16 bytes of a SHA-256 over the previous key and the block's tokens, so a collision is negligible at corpus scale.
func NewRegistry ¶
NewRegistry returns an empty registry of blocks of size tokens.
type ReplaySettings ¶
type ReplaySettings struct {
Preset string `json:"preset"`
DiffersFromPreset map[string]json.RawMessage `json:"differs_from_preset"`
}
ReplaySettings is the part of a replay-settings file the scorer reads.
type Request ¶
type Request struct {
Task *Task
Agent *Agent
Event int // index in Agent.Events
Index int // position among the agent's generates
Cycle uint64
// Tokens is the prompt, when the trace records it as token ids or
// block runs. Otherwise Messages (with Tools) is the agent's chat
// context for the server to render.
Tokens []int
Messages []json.RawMessage
Tools json.RawMessage
MaxTokens int
Warmup bool // a one-token warm-start request
}
A Request is one model request of a replay.
type Response ¶
type Response struct {
PromptTokens int
CachedTokens *int // nil if the server does not say
CompletionTokens int
OutputTokens []int // generated token ids, if the server returns them
Start time.Time // just before the request was written
FirstToken time.Time // first token received; zero if none
End time.Time // response complete; zero if unknown
// MaxTokenGap is the longest wait between two consecutive streamed
// tokens, a decode stall the client saw; zero if fewer than two
// arrived.
MaxTokenGap time.Duration
OutputSHA256 string // hex SHA-256 of the generated text, if the sender computes it
}
A Response is what a Sender observed of one request.
type Result ¶
type Result struct {
Records []Record
Admitted int // tasks admitted
Skipped int // generates skipped by MaxPromptTokens
Failed int // tasks that ended with an error other than cancellation
}
A Result is the outcome of a replay.
type Reuse ¶
A Reuse counts the prompt tokens of some requests and how many of them a cache served (or could serve).
type Run ¶
type Run struct {
First, Count uint64
}
A Run is a run of Count consecutive block ids starting at First.
type Score ¶
type Score struct {
Files int `json:"files"`
WindowStartNs int64 `json:"window_start_ns"`
WindowEndNs int64 `json:"window_end_ns"`
WindowS float64 `json:"window_s"`
ReplayPreset []string `json:"replay_preset"`
ReplayDiffersFromPreset map[string]json.RawMessage `json:"replay_differs_from_preset"`
ReplayContextModes []string `json:"replay_context_modes"`
CompletedModelRequests int `json:"completed_model_requests"`
CompletedTraces int `json:"completed_traces"`
FailedRequests int `json:"failed_requests"`
FailuresByClass map[string]int `json:"failures_by_class"`
CancelledRequests int `json:"cancelled_requests"`
MigratedRequests int `json:"migrated_requests"`
WarmupRequests int `json:"warmup_requests"`
RequestsPerS float64 `json:"requests_per_s"`
CompletionTokS float64 `json:"completion_tok_s"`
NewPromptTokS *float64 `json:"new_prompt_tok_s"`
CacheHit *float64 `json:"cache_hit"`
MeanPromptTokens *float64 `json:"mean_prompt_tokens"`
InflightMean float64 `json:"inflight_mean"`
TTFTP50 *float64 `json:"ttft_p50"`
TTFTP90 *float64 `json:"ttft_p90"`
TTFTP95 *float64 `json:"ttft_p95"`
TTFTP99 *float64 `json:"ttft_p99"`
TTFTMean *float64 `json:"ttft_mean"`
E2EMean *float64 `json:"e2e_mean"`
E2EP95 *float64 `json:"e2e_p95"`
// CachedUnreported counts completed window requests whose
// cached_prompt_tokens was null. score.py fails on such a run; here
// CacheHit and NewPromptTokS are then nil.
CachedUnreported int `json:"cached_unreported,omitempty"`
}
A Score is the steady-window score of a run, field for field the output of the reference score.py. Fields that score.py reports as null are nil.
type Shape ¶
type Shape int
A Shape is a synthetic workload shape.
const ( // DecodeHeavy is one agent per task with long outputs, short new // context each turn and no sub-agents. DecodeHeavy Shape = iota // Dynamic is a main agent that forks sub-agents sharing its prefix, // joins them, and compacts its context. Dynamic // PrefillHeavy is one agent per task that appends a long new context // each turn and generates short outputs. PrefillHeavy // LongSession is one long multi-turn conversation per task: see // [LongSessionConfig]. LongSession )
func ParseShape ¶
ParseShape returns the shape named name.
type SynthConfig ¶
type SynthConfig struct {
Shape Shape
Tasks int
Seed uint64
BlockSize int // tokens per block; 0 means 64, or 16 for LongSession
// NoParentPrefix starts each sub-agent's prompt without its parent's
// prefix, as if the fork had no parent link.
NoParentPrefix bool
// LongSession sets the LongSession shape's parameters; nil means
// [DefaultLongSession].
LongSession *LongSessionConfig
}
A SynthConfig configures Generate.
type Task ¶
type Task struct {
ID string
Agents []*Agent
Deps []Dependency
StartOffset float64
CacheSaltScope string
Single bool
Block *BlockSpec // metadata.block_tokens of the task
}
A Task is one admission slot's work: concurrent agents joined by dependency edges. A schema-v2 row is read as a task of one agent with Single set.
func ReadMooncake ¶
ReadMooncake reads the first n requests of a Mooncake trace, or all of them when n <= 0, and returns them as one task in arrival order. Each request is one agent: a wait from the first request's arrival to its own, then one generate of the request's blocks, cut to its input length, with its output length as max_tokens. The blocks expand with seed, as Blocks expands any trace's, so equal hash ids give equal tokens.
A replay of the task sends every request at its recorded arrival, scaled by Options.DelayScale, whatever the server's speed: the open loop the trace was recorded under, not the closed loop of task slots.