steady

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 19 Imported by: 0

README

SteadyPicker

SteadyPicker is a tiny, deterministic video-settings engine. It converts a generation prompt into quota-aware duration, aspect-ratio, and resolution settings without making a production network or LLM call.

The released CLI includes the trained settings-v1 model, so one executable is all you need.

Quick start

Install with Go:

go install github.com/hensmth/steady-picker/cmd/steady-picker@latest

Or download a ready-to-run binary from the latest release for Linux, macOS, or Windows.

Send one JSON object over stdin:

printf '%s\n' \
  '{"prompt":"a flower transforming in a timelapse","mode":"text-to-video"}' |
  steady-picker predict

Output:

{"duration":6,"aspect_ratio":"16:9","resolution":"480p","source":"model","confidence":0.9999,"model_version":"v1","policy_version":"balanced-v1"}

Prompts are read from stdin, not command-line arguments. Prediction is local, network-free, and normally completes in milliseconds.

Policy

  • Safe fallback: 4 seconds, 16:9, 480p.
  • Maximum duration: 6 seconds.
  • Default resolution: 480p.
  • 720p requires 720p, HD output, or render in HD in the prompt.
  • Decorative wording such as 4K style, cinematic, or high quality stays at 480p.
  • Image-to-video requests retain the source frame with auto.
  • Learned 2- or 6-second overrides require a singleton conformal set, at least 0.80 calibrated confidence, and a matching semantic cue.

Ambiguous or out-of-distribution prompts keep the conservative fallback.

Input

predict accepts:

{
  "prompt": "a quick vertical video of a bird taking flight",
  "mode": "text-to-video",
  "image_aspect_ratio": 1.777
}
  • prompt is required.
  • mode is text-to-video or image-to-video.
  • image_aspect_ratio is optional and only relevant to image-to-video.
  • Input is limited to one JSON line of at most 16 KiB.

Use a custom model when needed:

steady-picker predict --model ./custom-model.bin --model-version custom-v1

Go library

package main

import (
	"fmt"
	"log"

	steady "github.com/hensmth/steady-picker"
)

func main() {
	model, err := steady.LoadDefault()
	if err != nil {
		log.Fatal(err)
	}
	defer model.Close()

	result := steady.PickSettings(model, steady.PickRequest{
		Prompt: "a quick wink in a portrait video",
		Mode:   "text-to-video",
	}, steady.DefaultModelVersion)
	fmt.Printf("%+v\n", result)
}

Load(path) memory-maps an external model. LoadBytes(data) supports models embedded by another application.

Training

Training data uses one label per line:

__label__d2 A quick shot of a bird taking flight
__label__d4 A dancer turns toward the camera
__label__d6 A timelapse showing a flower fully bloom
steady-picker train --input training.txt --output custom-model.bin
steady-picker evaluate --model custom-model.bin --test held-out.txt

Training is seeded and single-worker by default, so identical inputs and parameters produce identical model checksums. The scripts directory contains optional public-prompt acquisition, Hermes teacher labelling, deterministic splitting, and cross-validation helpers. Teacher labelling runs locally by default and accepts --ssh-host for a remote Hermes installation.

Development

go test ./...
go test -race ./...
go vet ./...

Released binaries are built for:

  • Linux: amd64 and arm64
  • macOS: amd64 and arm64
  • Windows: amd64

See MODEL_CARD.md for model provenance, evaluation, intended use, and limitations.

Origin and license

The classifier is derived from xDarkicex/steady and retains its MIT license. SteadyPicker adds independent calibration data, complete one-vs-all updates, corrected averaged-embedding gradients, deterministic training, strict artifact validation, and the quota policy.

See THIRD_PARTY_NOTICES.md for attribution.

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 local, quota-aware video setting selection in pure Go.

The default trained model is embedded. Custom models can be memory-mapped from disk or loaded from bytes. 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.LoadDefault()
defer m.Close()
result := steady.PickSettings(m, steady.PickRequest{
	Prompt: "a flower transforming in a timelapse",
	Mode:   "text-to-video",
}, "v1")

Training:

go run ./cmd/steady-picker train --input data.txt --output model.bin

Input format: __label__d2 Text here

Example (Classify)

Example_classify demonstrates loading a model and classifying text.

package main

import (
	"fmt"
	"os"
	"strings"

	steady "github.com/hensmth/steady-picker"
)

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

Examples

Constants

View Source
const (
	PolicyVersion     = "balanced-v1"
	DefaultResolution = "480p"
	MaximumDuration   = 6
	FallbackDuration  = 4
	FallbackAspect    = "16:9"
	MinimumConfidence = 0.80
)
View Source
const DefaultModelVersion = "v1"

DefaultModelVersion identifies the model embedded in released binaries.

Variables

View Source
var PresetLabels = []string{"d2", "d4", "d6"}

Functions

func ApplyPlatt

func ApplyPlatt(score, a, b float32) float32

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

func ComputeQuantile(scores []float32, alpha float64) float32

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

func Encode(text []byte, table []float32, bucket, dim int, pool *memory.Pool) []float32

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

func Load(path string) (*Model, error)

Load opens a model file and returns the loaded Model. The caller must call Close to release resources.

func LoadBytes

func LoadBytes(data []byte) (*Model, error)

LoadBytes loads a model from an in-memory artifact. Unlike Load, it copies the embedding table instead of memory-mapping it. The caller must call Close.

func LoadDefault

func LoadDefault() (*Model, error)

LoadDefault loads the trained settings model embedded in this package. The caller must call Close to release its 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) Close

func (m *Model) Close() error

Close releases resources held by the model.

func (*Model) SetLabelNames

func (m *Model) SetLabelNames(names []string)

SetLabelNames sets the human-readable label names used in prediction sets.

type PickRequest

type PickRequest struct {
	Prompt           string  `json:"prompt"`
	Mode             string  `json:"mode"`
	ImageAspectRatio float64 `json:"image_aspect_ratio,omitempty"`
}

type PickResult

type PickResult struct {
	Duration      int     `json:"duration"`
	AspectRatio   string  `json:"aspect_ratio"`
	Resolution    string  `json:"resolution"`
	Source        string  `json:"source"`
	Confidence    float32 `json:"confidence"`
	ModelVersion  string  `json:"model_version"`
	PolicyVersion string  `json:"policy_version"`
}

func PickSettings

func PickSettings(model *Model, request PickRequest, modelVersion string) PickResult

type PredictionSet

type PredictionSet struct {
	Kinds       []string
	Confidences []float32
}

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

func PredictSet(probs []float32, labelNames []string, q float32, pool *memory.Pool) PredictionSet

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.

Directories

Path Synopsis
cmd
steady-picker command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL