Documentation
¶
Overview ¶
Package steady provides a zero-allocation text classification engine using byte-level n-gram hashing, logistic regression, Platt scaling, and conformal prediction. Designed for sub-millisecond CPU inference in pure Go.
Package steady provides zero-allocation text classification in pure Go.
Models are trained offline and loaded at runtime via memory-mapped files. Classification runs the byteSteady encoder, OVA logistic regression, Platt scaling, and conformal prediction in a single sub-millisecond pass with zero heap allocations.
Quick start:
m, _ := steady.Load("model.bin")
defer m.Close()
m.SetLabelNames([]string{"spam", "urgent", "question", "update", "complaint", "praise"})
result := m.Classify("I am a Go developer")
if !result.IsEmpty() {
fmt.Println(result.Kinds[0], result.Confidences[0])
}
Training:
go run ./cmd/steady -input data.txt -output model.bin -epochs 20 -bucket 2000000 -dim 64
Input format: __label__classname Text here
Example (Classify) ¶
Example_classify demonstrates loading a model and classifying text.
package main
import (
"fmt"
"os"
"strings"
"github.com/xDarkicex/steady"
)
func main() {
lines := []string{
"__label__spam buy cheap watches now",
"__label__urgent server down in production",
"__label__question how do I reset my password",
"__label__update deployed v2.3.1 to staging",
"__label__complaint the checkout page is broken",
"__label__praise the new dashboard looks amazing",
}
input := strings.Repeat(strings.Join(lines, "\n")+"\n", 30)
tmpDir, _ := os.MkdirTemp("", "steady_example_*")
defer os.RemoveAll(tmpDir)
inputPath := tmpDir + "/train.txt"
outputPath := tmpDir + "/model.bin"
os.WriteFile(inputPath, []byte(input), 0644)
cfg := steady.DefaultTrainConfig()
cfg.Input = inputPath
cfg.Output = outputPath
cfg.Bucket = 500
cfg.Dim = 8
cfg.Epochs = 10
cfg.LR = 0.2
cfg.Seed = 42
cfg.LabelNames = []string{"spam", "urgent", "question", "update", "complaint", "praise"}
if err := steady.Train(cfg); err != nil {
panic(err)
}
m, err := steady.Load(outputPath)
if err != nil {
panic(err)
}
defer m.Close()
m.SetLabelNames(cfg.LabelNames)
result := m.Classify("buy cheap watches now")
if result.IsEmpty() {
fmt.Println("noise")
} else {
fmt.Println(result.Kinds[0])
}
}
Output: spam
Index ¶
- func ApplyPlatt(score, a, b float32) float32
- func CalibratePlatt(pool *memory.Pool, rawScores [][]float32, labels []int, numLabels int) ([]float32, []float32)
- func ComputeQuantile(scores []float32, alpha float64) float32
- func Encode(text []byte, table []float32, bucket, dim int, pool *memory.Pool) []float32
- func PredictLogits(hidden, weights, bias, out []float32)
- func Train(cfg TrainConfig) error
- type DebugResult
- type Model
- type PredictionSet
- type TrainConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyPlatt ¶
ApplyPlatt returns the Platt-calibrated probability for a raw score. P(calibrated) = 1 / (1 + exp(-(A * score + B)))
func CalibratePlatt ¶
func CalibratePlatt(pool *memory.Pool, rawScores [][]float32, labels []int, numLabels int) ([]float32, []float32)
CalibratePlatt fits Platt scaling parameters (A, B) for each label using Newton's method on a calibration set. rawScores[i] is the vector of uncalibrated scores for example i, labels[i] is the true label index. Returns two slices of length numLabels allocated from pool.
func ComputeQuantile ¶
ComputeQuantile computes the conformal quantile Q from calibration scores. scores[i] is the non-conformity score (1 - probability for the true label) for calibration example i. alpha is the desired error rate (e.g., 0.05 for 95%).
func Encode ¶
Encode computes the averaged byteSteady embedding for raw text. The table parameter is a bucket × dim float32 matrix in row-major order. The returned slice is allocated from pool and has length dim.
func PredictLogits ¶
func PredictLogits(hidden, weights, bias, out []float32)
PredictLogits writes OVA logistic probabilities for each label into out. hidden is the embedding vector (length dim). weights is numLabels × dim row-major, bias is numLabels floats. out must have length >= numLabels.
func Train ¶
func Train(cfg TrainConfig) error
Train runs the full training pipeline and writes the model artifact.
Types ¶
type DebugResult ¶
type DebugResult struct {
Logits []float32
Calibrated []float32
PlattA []float32
PlattB []float32
Q float32
IsEmpty bool
Kinds []string
}
DebugResult holds raw intermediate values for debugging a classification.
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model holds a loaded classification model. All fields are read-only after Load.
func Load ¶
Load opens a model file and returns the loaded Model. The caller must call Close to release resources.
func (*Model) Classify ¶
func (m *Model) Classify(text string) PredictionSet
Classify runs the full classification pipeline on text. It returns a calibrated prediction set with conformal coverage guarantees. An empty set indicates that the text could not be classified with sufficient confidence (noise or out-of-distribution).
func (*Model) ClassifyDebug ¶
func (m *Model) ClassifyDebug(text string) DebugResult
ClassifyDebug runs classification and returns raw intermediate values.
func (*Model) SetLabelNames ¶
SetLabelNames sets the human-readable label names used in prediction sets.
type PredictionSet ¶
PredictionSet is the output of a conformal classification. It contains the set of labels that meet the coverage guarantee at the configured significance level. An empty set indicates out-of-distribution or noise input.
func PredictSet ¶
PredictSet returns the prediction set for calibrated probabilities. For each label i, include if (1.0 - probs[i]) <= q. If no labels qualify, returns an empty set. Uses pool for output slices.
func (PredictionSet) IsEmpty ¶
func (ps PredictionSet) IsEmpty() bool
IsEmpty returns true if the prediction set contains no labels.
type TrainConfig ¶
type TrainConfig struct {
Input string
Output string
Bucket int
Dim int
Epochs int
LR float32
Alpha float64
LabelNames []string
NumGoroutines int
CalibSplit float64
Seed uint64
}
TrainConfig holds hyperparameters for training a classification model.
func DefaultTrainConfig ¶
func DefaultTrainConfig() TrainConfig
DefaultTrainConfig returns a TrainConfig with sensible defaults.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
steady
command
Command steady trains and evaluates text classification models using byteSteady embeddings, OVA logistic regression, Platt scaling, and conformal prediction.
|
Command steady trains and evaluates text classification models using byteSteady embeddings, OVA logistic regression, Platt scaling, and conformal prediction. |