// Package dibaguard is the Go reference runtime for DibaGuard tier-1 models: oblivious-tree ensembles (flows) // and the hashed n-gram embedding-bag + MLP (HTTP). It reads the flat export written by // dibaguard.parity.npz_to_flat (a .bin of little-endian arrays and a .bin.json header) and is proven against the // Python runtime by the parity fixtures. No dependencies beyond the standard library. package dibaguard import ( "encoding/binary" "encoding/json" "fmt" "math" "os" ) type arrayInfo struct { Dtype string `json:"dtype"` Shape []int `json:"shape"` Offset int `json:"offset"` NBytes int `json:"nbytes"` } // Flat is a loaded flat model file: raw bytes plus the header. type Flat struct { data []byte arrays map[string]arrayInfo Info map[string]any } // LoadFlat reads and .json. func LoadFlat(path string) (*Flat, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } hdr, err := os.ReadFile(path + ".json") if err != nil { return nil, err } var raw map[string]json.RawMessage if err := json.Unmarshal(hdr, &raw); err != nil { return nil, err } f := &Flat{data: data, arrays: map[string]arrayInfo{}} for k, v := range raw { if k == "info" { if err := json.Unmarshal(v, &f.Info); err != nil { return nil, err } continue } var ai arrayInfo if err := json.Unmarshal(v, &ai); err != nil { return nil, err } f.arrays[k] = ai } return f, nil } func (f *Flat) bytesOf(name string) ([]byte, arrayInfo, error) { ai, ok := f.arrays[name] if !ok { return nil, ai, fmt.Errorf("array %q missing", name) } return f.data[ai.Offset : ai.Offset+ai.NBytes], ai, nil } // Float32s returns the array as float32 regardless of its stored dtype (f4, f8, i1, i2, i4, i8). func (f *Flat) Float32s(name string) ([]float32, []int, error) { b, ai, err := f.bytesOf(name) if err != nil { return nil, nil, err } n := 1 for _, s := range ai.Shape { n *= s } out := make([]float32, n) switch ai.Dtype { case "