Comments, doc comments, test names, error and log messages, CLI help, README, Makefile, CI step names and the design document are now all in English. No behaviour changes; the full suite passes under the race detector. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b7417e1a69
commit
28029eb43b
21 files changed
+910
-869
No files matched your search
+69
-70
@@ -1,12 +1,12 @@
|
||||
// Package sim, OpenAI uyumlu sahte bir inference engine'i barındırır.
|
||||
// Package sim provides an OpenAI-compatible fake inference engine.
|
||||
//
|
||||
// Amacı router'ı GPU olmadan gerçekçi koşullarda test edebilmek. Gerçek bir
|
||||
// engine'in router açısından önemli olan davranışlarını modeller:
|
||||
// - continuous batching (sınırlı eşzamanlı dizi sayısı)
|
||||
// - KV cache blok muhasebesi ve blok yetmediğinde kuyruğa alma
|
||||
// - otomatik prefix cache (blok bazlı LRU) ve cache hit'in TTFT'ye etkisi
|
||||
// - batch büyüdükçe token başına gecikmenin artması
|
||||
// - vLLM formatında /metrics
|
||||
// Its purpose is to let the router be tested under realistic conditions
|
||||
// without GPUs. It models the real-engine behaviours the router cares about:
|
||||
// - continuous batching (bounded number of concurrent sequences)
|
||||
// - KV cache block accounting, queueing once blocks run out
|
||||
// - automatic prefix caching (block-level LRU) and its effect on TTFT
|
||||
// - per-token latency growing as the batch grows
|
||||
// - /metrics in vLLM's format
|
||||
package sim
|
||||
|
||||
import (
|
||||
@@ -19,40 +19,40 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config, simüle edilen engine'in davranışını belirler.
|
||||
// Config controls the simulated engine's behaviour.
|
||||
type Config struct {
|
||||
Model string
|
||||
|
||||
// MaxNumSeqs, aynı anda çalışabilecek dizi sayısı (continuous batch kapasitesi).
|
||||
// MaxNumSeqs is how many sequences may run concurrently (batch capacity).
|
||||
MaxNumSeqs int
|
||||
// BlockSize, bir KV cache bloğundaki token sayısı.
|
||||
// BlockSize is the number of tokens per KV cache block.
|
||||
BlockSize int
|
||||
// NumGPUBlocks, toplam KV cache bloğu.
|
||||
// NumGPUBlocks is the total number of KV cache blocks.
|
||||
NumGPUBlocks int
|
||||
// PrefixCacheBlocks, prefix cache'in tutacağı blok sayısı. 0 = kapalı.
|
||||
// PrefixCacheBlocks is the prefix cache capacity in blocks. 0 disables it.
|
||||
PrefixCacheBlocks int
|
||||
|
||||
// PrefillTokensPerSec, engine genelinde paylaşılan prefill hızı.
|
||||
// PrefillTokensPerSec is the prefill rate, shared engine-wide.
|
||||
PrefillTokensPerSec float64
|
||||
// DecodeTokensPerSec, tek dizi çalışırken token üretim hızı.
|
||||
// DecodeTokensPerSec is the generation rate for a single running sequence.
|
||||
DecodeTokensPerSec float64
|
||||
// BatchContention, batch'teki her ek dizinin decode hızını ne kadar
|
||||
// yavaşlattığı. Etkin hız = DecodeTokensPerSec / (1 + BatchContention*(n-1)).
|
||||
// BatchContention is how much each additional sequence slows decoding:
|
||||
// effective rate = DecodeTokensPerSec / (1 + BatchContention*(n-1)).
|
||||
BatchContention float64
|
||||
|
||||
// DefaultOutputTokens, istek max_tokens vermediğinde üretilecek token sayısı.
|
||||
// DefaultOutputTokens is generated when a request omits max_tokens.
|
||||
DefaultOutputTokens int
|
||||
// Tick, simülasyon adımı. Küçük olması çözünürlüğü artırır.
|
||||
// Tick is the simulation step; smaller values increase resolution.
|
||||
Tick time.Duration
|
||||
|
||||
// FailRate, isteklerin hangi oranda 500 ile reddedileceği (kaos testi için).
|
||||
// FailRate is the fraction of requests rejected artificially, for chaos tests.
|
||||
FailRate float64
|
||||
// Seed, deterministik testler için.
|
||||
// Seed makes runs deterministic.
|
||||
Seed int64
|
||||
}
|
||||
|
||||
// Default, makul varsayılanlarla bir Config döner.
|
||||
// Kabaca 8xH100 üstünde 70B bir modelin davranışına benzer ölçekler.
|
||||
// Default returns a configuration with sensible values, roughly in the range
|
||||
// of a 70B model on 8xH100.
|
||||
func Default() Config {
|
||||
return Config{
|
||||
Model: "sim-model",
|
||||
@@ -95,34 +95,34 @@ func (c *Config) normalize() {
|
||||
}
|
||||
}
|
||||
|
||||
// EventKind, akıştaki olay türü.
|
||||
// EventKind is the type of an event in the stream.
|
||||
type EventKind int
|
||||
|
||||
const (
|
||||
// EventToken, üretilen bir token.
|
||||
// EventToken carries one generated token.
|
||||
EventToken EventKind = iota
|
||||
// EventDone, üretimin normal bitişi.
|
||||
// EventDone marks normal completion.
|
||||
EventDone
|
||||
// EventError, üretim sırasında oluşan hata.
|
||||
// EventError reports a failure during generation.
|
||||
EventError
|
||||
)
|
||||
|
||||
// Event, engine'in istemciye ilettiği tek bir olay.
|
||||
// Event is a single event delivered to the caller.
|
||||
type Event struct {
|
||||
Kind EventKind
|
||||
Text string
|
||||
Err error
|
||||
// Result yalnızca EventDone'da doludur; prompt/cache/completion sayılarını taşır.
|
||||
// Result is set only on EventDone; it carries the final token counts.
|
||||
Result *Result
|
||||
}
|
||||
|
||||
// Prompt, engine'e verilen istek.
|
||||
// Prompt is a request handed to the engine.
|
||||
type Prompt struct {
|
||||
Text string
|
||||
MaxTokens int
|
||||
}
|
||||
|
||||
// Result, istek bittiğinde okunabilen özet (Done olayından sonra geçerli).
|
||||
// Result summarizes a finished request; valid from the Done event onwards.
|
||||
type Result struct {
|
||||
PromptTokens int
|
||||
CachedTokens int
|
||||
@@ -130,12 +130,12 @@ type Result struct {
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrTooLong, isteğin KV cache'e hiç sığmadığını belirtir.
|
||||
ErrTooLong = errors.New("istek KV cache kapasitesine sığmıyor")
|
||||
// ErrInjected, FailRate ile üretilen yapay hata.
|
||||
ErrInjected = errors.New("yapay hata (sim fail_rate)")
|
||||
// ErrShutdown, engine kapanırken bekleyen istekler için.
|
||||
ErrShutdown = errors.New("engine kapanıyor")
|
||||
// ErrTooLong means the request does not fit in the KV cache at all.
|
||||
ErrTooLong = errors.New("request does not fit in KV cache capacity")
|
||||
// ErrInjected is the artificial failure produced by FailRate.
|
||||
ErrInjected = errors.New("injected failure (sim fail_rate)")
|
||||
// ErrShutdown is returned to pending requests while the engine stops.
|
||||
ErrShutdown = errors.New("engine shutting down")
|
||||
)
|
||||
|
||||
type req struct {
|
||||
@@ -164,9 +164,9 @@ type req struct {
|
||||
res *Result
|
||||
}
|
||||
|
||||
// flush, biriken olayları bloke olmadan kanala aktarır.
|
||||
// Bloke olmamak şart: tick döngüsü kilidi tutarken yavaş bir istemci
|
||||
// tüm engine'i durdurmamalı.
|
||||
// flush moves buffered events into the channel without blocking.
|
||||
// Not blocking is essential: the tick loop holds the engine lock, and one slow
|
||||
// client must not stall every other request.
|
||||
func (r *req) flush() {
|
||||
for len(r.pending) > 0 {
|
||||
select {
|
||||
@@ -183,7 +183,7 @@ func (r *req) emit(ev Event) {
|
||||
r.flush()
|
||||
}
|
||||
|
||||
// Engine, simüle edilen inference engine.
|
||||
// Engine is the simulated inference engine.
|
||||
type Engine struct {
|
||||
cfg Config
|
||||
|
||||
@@ -203,8 +203,7 @@ type Engine struct {
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// New, verilen konfigürasyonla bir engine kurar ve simülasyon döngüsünü başlatır.
|
||||
// Kapatmak için Close çağrılmalı.
|
||||
// New creates an engine and starts its simulation loop. Call Close to stop it.
|
||||
func New(cfg Config) *Engine {
|
||||
cfg.normalize()
|
||||
seed := cfg.Seed
|
||||
@@ -215,7 +214,7 @@ func New(cfg Config) *Engine {
|
||||
cfg: cfg,
|
||||
freeBlocks: cfg.NumGPUBlocks,
|
||||
cache: NewPrefixCache(cfg.PrefixCacheBlocks),
|
||||
rng: rand.New(rand.NewSource(seed)), //nolint:gosec // simülasyon
|
||||
rng: rand.New(rand.NewSource(seed)), //nolint:gosec // simulation only
|
||||
m: newMetrics(),
|
||||
stop: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
@@ -224,10 +223,10 @@ func New(cfg Config) *Engine {
|
||||
return e
|
||||
}
|
||||
|
||||
// Config, engine'in aktif konfigürasyonunu döner.
|
||||
// Config returns the engine's effective configuration.
|
||||
func (e *Engine) Config() Config { return e.cfg }
|
||||
|
||||
// Close, simülasyon döngüsünü durdurur ve bekleyen istekleri hataya düşürür.
|
||||
// Close stops the simulation loop and fails any pending requests.
|
||||
func (e *Engine) Close() {
|
||||
e.stopOnce.Do(func() {
|
||||
close(e.stop)
|
||||
@@ -235,8 +234,8 @@ func (e *Engine) Close() {
|
||||
})
|
||||
}
|
||||
|
||||
// Submit, isteği kuyruğa alır ve olay kanalını döner.
|
||||
// Kanal, üretim bitince veya hata oluşunca kapanır.
|
||||
// Submit enqueues a request and returns its event channel. The channel closes
|
||||
// when generation finishes or fails.
|
||||
func (e *Engine) Submit(ctx context.Context, p Prompt) (<-chan Event, error) {
|
||||
if e.cfg.FailRate > 0 {
|
||||
e.mu.Lock()
|
||||
@@ -310,9 +309,9 @@ func (e *Engine) run() {
|
||||
}
|
||||
}
|
||||
|
||||
// reap, istemcisi vazgeçmiş istekleri hem kuyruktan hem batch'ten düşürür.
|
||||
// Router'ın iptal propagasyonunu test edebilmek için bu davranış şart:
|
||||
// istemci koptuğunda GPU boşa çalışmamalı.
|
||||
// reap drops requests whose client has gone away, from both the queue and the
|
||||
// running batch. The router's cancellation propagation cannot be tested
|
||||
// without this: when a client disconnects, the GPU must stop working.
|
||||
func (e *Engine) reap() {
|
||||
e.waiting = filterInPlace(e.waiting, func(r *req) bool {
|
||||
if r.ctx.Err() == nil {
|
||||
@@ -338,7 +337,7 @@ func (e *Engine) schedule() {
|
||||
r := e.waiting[0]
|
||||
need := e.blocksFor(r.promptTokens + r.outputTokens)
|
||||
if need > e.freeBlocks {
|
||||
// Head-of-line blocking: gerçek engine de böyle davranır.
|
||||
// Head-of-line blocking; real engines behave the same way.
|
||||
break
|
||||
}
|
||||
|
||||
@@ -362,7 +361,7 @@ func (e *Engine) advance(dt float64) {
|
||||
return
|
||||
}
|
||||
|
||||
// Prefill bütçesi engine genelinde paylaşılır ve FIFO dağıtılır.
|
||||
// The prefill budget is shared engine-wide and handed out FIFO.
|
||||
budget := e.cfg.PrefillTokensPerSec * dt
|
||||
for _, r := range e.running {
|
||||
if budget <= 0 {
|
||||
@@ -376,7 +375,7 @@ func (e *Engine) advance(dt float64) {
|
||||
budget -= used
|
||||
}
|
||||
|
||||
// Decode hızı batch büyüdükçe düşer.
|
||||
// Decoding slows down as the batch grows.
|
||||
n := 0
|
||||
for _, r := range e.running {
|
||||
if r.prefillLeft <= 0 {
|
||||
@@ -420,9 +419,9 @@ func (e *Engine) finish(r *req) {
|
||||
r.finished = true
|
||||
e.freeBlocks += r.blocks
|
||||
|
||||
// Üretilen çıktı da cache'e girer: bir sonraki turda konuşma geçmişi
|
||||
// olarak geri geldiğinde hit vermeli. Çok turlu sohbeti modellemenin
|
||||
// tek yolu bu.
|
||||
// The generated output enters the cache too: when it comes back as
|
||||
// conversation history on the next turn it must hit. That is the only way
|
||||
// to model multi-turn chat.
|
||||
full := Tokenize(r.prompt.Text + generatedText(r.emitted))
|
||||
e.cache.Insert(BlockHashes(full, e.cfg.BlockSize))
|
||||
|
||||
@@ -469,7 +468,19 @@ func (e *Engine) shutdown() {
|
||||
e.waiting, e.running, e.draining = nil, nil, nil
|
||||
}
|
||||
|
||||
// Stats, router'ın scrape edeceği anlık durumu döner.
|
||||
// Stats returns the instantaneous state the router would scrape.
|
||||
type Stats struct {
|
||||
Running int
|
||||
Waiting int
|
||||
KVCacheUsage float64
|
||||
BlockSize int
|
||||
NumGPUBlocks int
|
||||
PrefixQueries int64
|
||||
PrefixHits int64
|
||||
CachedBlocks int
|
||||
}
|
||||
|
||||
// Stats returns a snapshot of the engine's current state.
|
||||
func (e *Engine) Stats() Stats {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
@@ -487,18 +498,6 @@ func (e *Engine) Stats() Stats {
|
||||
}
|
||||
}
|
||||
|
||||
// Stats, engine'in anlık durumu.
|
||||
type Stats struct {
|
||||
Running int
|
||||
Waiting int
|
||||
KVCacheUsage float64
|
||||
BlockSize int
|
||||
NumGPUBlocks int
|
||||
PrefixQueries int64
|
||||
PrefixHits int64
|
||||
CachedBlocks int
|
||||
}
|
||||
|
||||
func filterInPlace(s []*req, keep func(*req) bool) []*req {
|
||||
out := s[:0]
|
||||
for _, r := range s {
|
||||
|
||||
Reference in new issue
Block a user