Skip to content
BrightSecPublic

Repository files navigation

SHAInet - A neural network in pure Crystal

SHAInet (Super Human Artificial Intelligence Network) is a neural network library written in pure Crystal. Originally created for biologically inspired neural network research, it has evolved into a general-purpose library for training and running neural networks, with a focus on simplicity and ease of use.


Features

  • CPU and GPU (CUDA) support
  • Multiple layer types and activation functions
  • Various training algorithms (SGD, Adam, iRprop+, etc.)
  • Streaming data support for large datasets
  • HuggingFace model import via SafeTensors (no Python required)
  • LLM inference: LLaMA, Mistral, Qwen2, Qwen3, Qwen3-MoE, Qwen3.5 and Qwen4-35B-A3B (Qwen3.5's Gated DeltaNet hybrid stack runs on the GPU; a 27B k-quant GGUF fits a 16 GB card with the trunk placed automatically; Qwen4's 15 GB of experts run from a per-layer device cache -- see below)
  • Direct GGUF loading (Ollama blobs or .gguf files) with weights dequantized inside the GEMV/GEMM kernels, and automatic layer placement -- no environment variables required. Q4_K/Q6_K plus the i-quants IQ4_XS, IQ3_S and IQ3_XXS run on dedicated kernels; the lower-bit types (IQ2_S/XS/XXS, Q2_K, IQ1_M) load too, so mixed-precision files like ISTA-DASLab's GSQ-RCO builds work as shipped
  • KV-cache decoding, Q8/Q4 weight quantization, and MoE expert offload (run large Mixture-of-Experts models on small GPUs)
  • Text to speech with Qwen3-TTS: built-in speakers, voices designed from a text description, and voice cloning from a short clip, plus an OpenAI-compatible /v1/audio/speech endpoint

Installation

Add to your shard.yml:

dependencies:
  shainet:
    github: BrightSec/shainet

GPU Acceleration (Optional)

  • Install the CUDA Toolkit and ensure libcudart.so and libcublas.so are in your LD_LIBRARY_PATH.
  • SHAInet will auto-detect CUDA and use GPU acceleration if available.
  • For cuDNN support, ensure libcudnn.so is also in your LD_LIBRARY_PATH.
  • Compile the project with -Denable_cuda

Check CUDA availability:

require "shainet"
puts "CUDA available: #{SHAInet::CUDA.available?}"
puts "CUDA version: #{SHAInet::CUDA.version || "unknown"}"

Optimized GPU Setup

For best performance (especially with transformers):

git clone https://github.com/BrightSec/shainet.git
cd shainet
make install
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(pwd)
make test

To build kernels manually:

./build_cuda_kernels.sh

RTX 30/40 Series (Ampere/Ada) Note

These GPUs use TF32 tensor cores by default for FP32 matrix multiply, which reduces mantissa precision from 23 to 10 bits. For LLM inference this can cause non-deterministic token generation. SHAInet sets CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION automatically, but for full FP32 precision also set:

export NVIDIA_TF32_OVERRIDE=0

Device management

Layers such as LayerNorm allocate workspace matrices on the first forward pass and reuse them across iterations. Call to_gpu! or to_cpu! only when switching devices. Repeated calls without a device change keep the existing workspaces to avoid unnecessary allocations.


Usage

See examples/ for more.

XOR Example

require "shainet"

data = [
  [[0.0, 0.0], [0.0]],
  [[1.0, 0.0], [1.0]],
  [[0.0, 1.0], [1.0]],
  [[1.0, 1.0], [0.0]],
]

net = SHAInet::Network.new
net.add_layer(:input, 2)
net.add_layer(:hidden, 2)
net.add_layer(:output, 1)
net.fully_connect

net.train(data: data,
  training_type: :sgdm,
  cost_function: :mse,
  epochs: 5000,
  log_each: 1000)

puts net.run([0, 1])

For multiclass training with raw logits, use an identity output and cost_function: :c_ent_sm; targets can be one-hot vectors or single class indices. :mse and :c_ent remain elementwise losses. TransformerBlock training currently supports SGD only (its internal sublayers use plain SGD; momentum applies to dense projections). Embeddings and output projections are also updated; inference-only LLaMA, Gated DeltaNet and quantized blocks cannot be trained through Network#train. Transformer dropout is applied only during training.

save_as_string / load_from_string preserve topology, weights and supported activations for plain dense networks only. Loading requires an empty network. Legacy files containing a Proc address instead of an activation name cannot be restored safely; embedding, transformer and quantized models need their dedicated model loaders rather than this dense JSON format.

Load a GGUF model (Ollama blob or .gguf file)

Point HFLoader.load at an Ollama model name, a blob, or a .gguf file. Q4_K and Q6_K weights are kept quantized and dequantized inside the GEMV/GEMM kernels, and layer placement is automatic — no environment variables are needed:

net = SHAInet::HFLoader.load("qwen3.5:27b")          # Ollama model name
net = SHAInet::HFLoader.load("/path/to/model.gguf")  # or a file
net.use_kv_cache = true
tokenizer = SHAInet::GGUF.extract_tokenizer("qwen3.5:27b")

The loader sums the real GGUF tensor sizes, measures free VRAM, and places as many layers on the card as fit, leaving the rest resident in host RAM. On a 16 GB card a 27B Q4_K/Q6_K model places 52 of 64 layers plus lm_head.

A mixed-precision i-quant build of the same 27B model fits entirely on the same card -- ISTA-DASLab's Qwen3.8-27B-GSQ-RCO-IQ3_S (11.8 GB) places all 64 layers with nothing left on the host. That matters more than the file size suggests: eliminating host-resident layers removes the per-token PCIe streaming that otherwise dominates decode. Measured on one 16 GB card, same prompt and same greedy output: 85 ms/token all-resident against 127 ms for the Q4_K build at 52 of 64 layers.

Files like these assign a quantization type per tensor rather than one type for the whole model, so a single file mixes eight of them. Those carrying most of the weight (IQ4_XS, IQ3_S, IQ3_XXS) have dedicated GEMV kernels; the low-bit tail is converted once at load time.

Weights left on the host are handled differently depending on batch size, because the two regimes are bound by different resources. Generating one token is memory-bound — the CPU streams those weights at full DDR5 bandwidth, so it keeps up. Prefill at hundreds of rows is compute-bound instead, where a CPU is about two orders of magnitude off the GPU, so past 32 rows the quantized weight is uploaded to the card and the matmul runs there. This mirrors llama.cpp's offload_op scheduler hook and uses its 32-row threshold; override with SHAINET_HOST_OFFLOAD_MIN_ROWS, or disable with SHAINET_HOST_OFFLOAD_OP=0.

For full fp32 determinism SHAInet sets CUBLAS_PEDANTIC_MATH on its cuBLAS handles, so TF32 tensor cores are not used for SGEMM and NVIDIA_TF32_OVERRIDE=0 is not required. Set SHAINET_CUBLAS_TF32=1 to allow TF32 back.

Qwen4-35B-A3B (GGUF qwen4exp)

The same HFLoader.load call takes Qwen4-35B-A3B GGUFs, split files included (pass the first shard). Verified against llama.cpp on unsloth's UD-IQ3_S build: the same greedy tokens, and llama.cpp's own chat template reproduced token for token.

net = SHAInet::HFLoader.load("~/models/qwen4/UD-IQ3_S/Qwen4-35B-A3B-UD-IQ3_S-00001-of-00002.gguf")

Everything except the routed experts goes to the GPU, about 2 GB. The experts (14.8 GB at IQ3_S) do not fit next to it on a 16 GB card. Instead, each layer gets a device cache over the mmap holding the same share of the free VRAM, about 190 of its 256 experts. A miss copies one expert (1-2 MB) and replaces the least recently used one. After warm-up about 95% of decode lookups hit. Prefill misses are staged for that one product rather than entering the cache, so a long prompt does not evict what decode needs. For up to 8 tokens, the routed experts run as one GEMV launch per projection over every (token, expert) pair rather than three launches per expert.

The file's MTP block drafts one token per step for speculative decoding, the agent's and server's default for this model (SHAINET_SPEC_K overrides; later drafts are kept far less often). Measured on an RTX 4090 Laptop at a 16K context over 256 tokens of a chat answer: 52 tok/s without MTP and 63 tok/s with it, 85% of drafts kept. A 1500-token prefill takes about 6.5 s.

The attention layers use QSA: past 2051 tokens, each token attends only to the top 512 blocks of 4 keys chosen by the indexer, plus its own unfinished block. Shorter contexts are dense, which is exact. The agent and the OpenAI server switch to Qwen4's chat template on their own. That template states the reasoning effort, uses a tool role, and its <think>/<tool_call> are control tokens.

Settings: SHAINET_MAX_CONTEXT (default 32768) sizes the KV reserve. SHAINET_QWEN4_RESERVE_MB and SHAINET_QWEN4_EXPERT_CACHE_MB override how VRAM is split between the reserve and the experts. SHAINET_PREFILL_CHUNK sets the prefill slice (default 1024). The vision tower is not loaded.

Load a HuggingFace Model (SafeTensors)

Load models directly from HuggingFace SafeTensors — no Python, no PyTorch, just pure Crystal binary parsing. HFLoader.load auto-detects the architecture from the model's config.json:

require "shainet"

# Auto-detects the architecture (llama / mistral / qwen2 / qwen3 / qwen3_moe / qwen3_5)
net = SHAInet::HFLoader.load("/path/to/model-dir")

# Optionally quantize weights to int8 at load time (Q8):
net = SHAInet::HFLoader.load("/path/to/model-dir", quantize: true, bits: 8)

Supported architectures: LLaMA, Mistral, Qwen2, Qwen3, Qwen3-MoE, Qwen3.5. Supported tensor dtypes: F16, BF16, F32, F64.

For a full chat loop (tokenizer, KV-cache decoding, sampling) see examples/llama_chat.cr; for a tool-using coding agent built on Network#run see examples/agent.cr.

Text to speech (Qwen3-TTS)

Qwen3-TTS 12 Hz checkpoints (Apache 2.0) load from their HuggingFace directory. Output is 24 kHz mono. Three kinds of checkpoint are supported, and they differ in where the voice comes from:

Checkpoint Voice
Qwen3-TTS-12Hz-0.6B/1.7B-CustomVoice One of 9 built-in speakers (ryan, vivian, ...). The 1.7B also follows style instructions.
Qwen3-TTS-12Hz-1.7B-VoiceDesign A text description: "an old man with a deep, raspy, gravelly voice"
Qwen3-TTS-12Hz-1.7B-Base Cloned from a 3-10 s reference clip
require "shainet"

# Built-in speaker
tts = SHAInet::Qwen3TTS.load("~/models/Qwen3-TTS-12Hz-0.6B-CustomVoice")
wav = tts.synthesize("Hello from Crystal.", "ryan", "english")
SHAInet::WAV.write("hello.wav", wav, tts.sample_rate)

# Voice from a description
designer = SHAInet::Qwen3TTS.load("~/models/Qwen3-TTS-12Hz-1.7B-VoiceDesign")
wav = designer.synthesize("Turn back, traveler.", nil, "english",
  instruct: "An old man in his eighties, deep raspy gravelly voice, slow and weary.")
SHAInet::WAV.write("hermit.wav", wav, designer.sample_rate)

A designed voice is sampled afresh on every call, so the same description sounds a little different from line to line. For a character that must sound the same in every line, design the voice once, then clone that clip with the Base model and save the result:

base = SHAInet::Qwen3TTS.load("~/models/Qwen3-TTS-12Hz-1.7B-Base")
clip, rate = SHAInet::WAV.read("hermit.wav")
clip = SHAInet::WAV.resample(clip, rate, base.sample_rate)

# With the clip's transcript the clone is in-context (ICL): the talker continues from the
# clip's own codes, which keeps accent and pacing. Without it, only the speaker embedding is used.
voice = base.clone_voice(clip, "Turn back, traveler.")
File.write("hermit.voice.json", voice.to_json)

voice = SHAInet::Qwen3TTS::Voice.from_json(File.read("hermit.voice.json"))
wav = base.synthesize_clone("The well ran dry three summers ago.", voice, "english")
SHAInet::WAV.write("line1.wav", wav, base.sample_rate)

Every stage was checked against the official qwen-tts package in fp32: the vocoder matches within 3.5e-6 per sample, the speaker embedding to a relative 1e-6, the speech-encoder codes exactly, and with the reference's codes fed back in the talker picks the same code for 99.8% of positions. Weights stay fp32 on the GPU by default (talker_bits: 8 for Q8 halves the VRAM but costs about 6 points of that agreement). The vocoder runs on the CPU.

Speech over the OpenAI-compatible server

examples/openai_server.cr serves POST /v1/audio/speech when given a Qwen3-TTS directory, either as its only model or beside a chat model:

crystal build --release -Denable_cuda examples/openai_server.cr -o openai_server
./openai_server ~/models/Qwen3-TTS-12Hz-0.6B-CustomVoice 8080          # speech only
SHAINET_TTS_MODEL=~/models/Qwen3-TTS-12Hz-0.6B-CustomVoice ./openai_server qwen3.8:27b

curl localhost:8080/v1/audio/speech -d '{"input":"Hello there.","voice":"vivian"}' -o hello.wav
curl localhost:8080/v1/audio/voices                                  # voices and languages

The request follows OpenAI's: input, voice, response_format (wav, the default here, or pcm: raw 16-bit little-endian at 24 kHz), and instructions. It adds language (auto by default). A VoiceDesign model takes the description in instructions, or in voice for clients that only expose that field:

curl localhost:8080/v1/audio/speech -o guard.wav \
  -d '{"input":"Halt. Show me your papers.","instructions":"A tired old city guard with a hoarse, smoky voice"}'

A Base model speaks in voices saved with POST /v1/audio/voices. The request body holds a name, the clip as base64 WAV (any sample rate, up to 30 s), and its transcript. Leave the transcript out for an x-vector-only voice. Voices are stored as JSON under ~/.local/share/shainet/voices (SHAINET_TTS_VOICES overrides) and survive restarts.

./openai_server ~/models/Qwen3-TTS-12Hz-1.7B-Base 8080
printf '{"name":"hermit","text":"Turn back, traveler.","audio":"%s"}' "$(base64 -w0 hermit.wav)" > voice.json
curl localhost:8080/v1/audio/voices --data-binary @voice.json
curl localhost:8080/v1/audio/speech -d '{"input":"The well ran dry.","voice":"hermit"}' -o line1.wav

Several speech models can be served together: list their directories, comma-separated, as the model (or in SHAINET_TTS_MODEL). VoiceDesign and Base together give the whole character workflow over HTTP. Describe a character once, the designer speaks a sample line, and the Base model clones that clip into a saved voice that sounds the same in every later line:

./openai_server ~/models/Qwen3-TTS-12Hz-1.7B-VoiceDesign,~/models/Qwen3-TTS-12Hz-1.7B-Base 8080

# Design and save. `text` is the sample line (a neutral default is used if omitted), `seed` makes
# the design repeatable, and the response names the designed clip, saved as <name>.wav.
curl localhost:8080/v1/audio/voices -d '{"name":"hermit","seed":3,"language":"english",
  "description":"An old man in his eighties, with a deep, raspy, gravelly voice, speaking slowly and wearily."}'

curl localhost:8080/v1/audio/speech -d '{"input":"The well ran dry.","voice":"hermit"}' -o line1.wav

Each request goes to the model that can serve it. A model naming a loaded model or a kind (base, voice_design, custom_voice) picks that model. Otherwise a known voice goes to the model that has it, and a description goes to the designer. A one-word voice is always read as a name, so a typo gets an error listing the voices instead of being taken as a description. Models with the same speech tokenizer (every 12 Hz checkpoint) share one vocoder. Both 1.7B models together take about 11.5 GB of VRAM in fp32.

SHAINET_TTS_BITS=8 loads the speech models' weights as Q8 (about a quarter of the fp32 VRAM).

Text to speech with vocal events (Breeze TTS 2)

Breeze TTS 2 loads the same way and adds inline vocal events: (sigh), (laugh), (cough) and (clears throat) in English text ([叹气], [笑] in Chinese). It speaks English and Chinese. One model covers four uses:

Use Input
Default voice text only
Voice design an instruction describing the voice
Voice clone a reference clip's codes and its exact transcript
Voice direction a clone plus an instruction steering tone and pace

Its weights and the audio it generates are licensed for research and non-commercial use only (BreezeBlue Research and Non-Commercial License).

breeze = SHAInet::BreezeTTS.load("~/models/Breeze-TTS-2")
wav = breeze.synthesize("(sigh) Turn back, traveler. (cough) Nothing waits in those hills.",
  "An old man in his eighties, with a deep, raspy, gravelly voice.", cfg_scale: 4.0)
SHAInet::WAV.write("hermit.wav", wav, breeze.sample_rate)

# Clone that clip and direct it.
codes = breeze.speech_encoder.encode(wav)
wav = breeze.synthesize("(clears throat) Listen to me. You will die out there.",
  "Angry and urgent.", "Turn back, traveler. Nothing waits in those hills.", codes, cfg_scale: 4.0)

An instruction is applied by classifier-free guidance: a second pass over the prompt without it, mixed as uncond + cfg_scale * (cond - uncond). Breeze recommends cfg_scale 4; at 1 the instruction is only a hint. Checked against the reference implementation in fp32: the tokenizer, text encoder and prompt match, and teacher-forced the port picks the same code at 99.6-99.9% of positions (plain, designed with guidance, and cloned). It needs about 7 GB of VRAM in fp32 and runs at 10-11 frames/s on a laptop RTX 4090, or 4-5 with guidance (12.5 is real time).

On the server it routes like the Qwen models (it lists as kind breeze): no voice uses its default voice, instructions designs one, and a saved voice clones it. Voices saved by a Qwen Base model work too, since both keep the clip's codes and transcript. Without a Qwen designer, POST /v1/audio/voices with a description designs the voice with Breeze itself:

./openai_server ~/models/Breeze-TTS-2 8080
curl localhost:8080/v1/audio/voices -d '{"name":"warlord","seed":9,
  "description":"A middle-aged warlord with a booming, harsh, commanding voice",
  "text":"You dare come to my camp empty handed?"}'
curl localhost:8080/v1/audio/speech -o line.wav \
  -d '{"input":"(laugh) The desert takes the weak. It will not take me.","voice":"warlord"}'
curl localhost:8080/v1/audio/speech -o whisper.wav \
  -d '{"input":"We ride at dawn.","voice":"warlord","instructions":"Quietly, almost whispering."}'

Requests also take seed (a repeatable take) and cfg_scale (default 4 with an instruction, else 1).

Iris Classification

data = SHAInet::Data.new_with_csv_input_target("iris.csv", 0..3, 4)
train, test = data.split(0.67)

iris = SHAInet::Network.new
iris.add_layer(:input, 4)
iris.add_layer(:hidden, 5)
iris.add_layer(:output, 3)
iris.fully_connect

iris.train_batch(
  data: train,
  training_type: :adam,
  cost_function: :mse,
  epochs: 2000,
  log_each: 100)

puts iris.test(test)

Streaming Data

Efficiently train on large datasets:

stream = SHAInet::StreamingData.new(
  "data.txt",
  shuffle: true,
  chunk_size: 1024,
  gpu_batches: true)

net = SHAInet::Network.new
net.add_layer(:input, 2, :memory, SHAInet.sigmoid)
net.add_layer(:hidden, 3, :memory, SHAInet.sigmoid)
net.add_layer(:output, 1, :memory, SHAInet.sigmoid)
net.fully_connect

net.train(
  data: stream,
  training_type: :sgdm,
  epochs: 5000,
  mini_batch_size: 2,
  log_each: 1000)

Advanced

  • Run a real LLaMA model: crystal run examples/llama_chat.cr -Denable_cuda (auto-downloads Llama-3.2-1B-Instruct, chats with KV cache + GPU).

  • Quantized inference (Q8_0): call net.quantize! after loading to run with int8 weights + per-32-block fp32 scales (dequant-in-kernel GEMV). Cuts weight VRAM ~4x (1B model: ~5GB fp32 → ~1.3GB) and speeds up memory-bound decode. llama_chat.cr quantizes by default on GPU; set SHAINET_FP32=1 to keep fp32. Benchmark/eval both paths with examples/q8_eval.cr.

  • 4-bit quantization (Q4) + MoE expert offload: run large Mixture-of-Experts models on small GPUs by keeping experts in host RAM (pinned) and streaming them to the GPU on demand, backed by a hot-expert LRU cache. Controlled via environment variables:

    • SHAINET_Q4=1 — 4-bit weight quantization
    • SHAINET_MOE_OFFLOAD=1 — offload MoE experts to host RAM
    • SHAINET_DENSE_OFFLOAD=1 — offload the dense weights too (attention projections, dense FFN, lm_head). Requires SHAINET_Q4=1. This is what takes dense models off the VRAM budget, so a far larger dense model fits. Unlike experts, dense weights are touched on every token, so there is no sparsity to amortize the transfer: expect slower decode. Pair it with SHAINET_EXPERT_CACHE_MB — left unbounded the hot cache promotes the dense weights straight back onto the card and you can end up using more VRAM than not offloading (measured on Qwen3-0.6B: 586 MB with the default budget vs 483 MB not offloading vs 228 MB with the cache disabled, at 51 ms/step resident and 80 ms/step streamed, with identical greedy output throughout).
    • SHAINET_EXPERT_CACHE_MB=<N> — VRAM budget for the hot-weight cache (0 disables)

    For example, Qwen3-Coder-30B-A3B (30B params, ~3B active) runs on a 16 GB GPU.

  • Tool-using coding agent: examples/agent.cr is a small CLI coding agent (file tools + shell, context management, streaming UI) built entirely on Network#run. Run it against a local instruct model, e.g. SHAINET_Q4=1 SHAINET_MOE_OFFLOAD=1 crystal run examples/agent.cr -Denable_cuda -- /path/to/model-dir.

  • OpenAI-compatible API server: examples/openai_server.cr serves a loaded model over a subset of the OpenAI REST API (POST /v1/chat/completions with streaming SSE, GET /v1/models), so existing OpenAI clients (the openai Python package, curl, LangChain, …) can use it as a drop-in local endpoint. Built entirely on Network#run. Example: crystal run examples/openai_server.cr -Denable_cuda -- /path/to/model-dir 8080. Binds to 127.0.0.1 with no authentication by default — set SHAINET_API_KEY to require an Authorization: Bearer <key> header before exposing it.

  • See examples/babylm_transformer.cr for training a transformer language model.

  • Use SHAInet::SafeTensors::File to read any .safetensors file directly.

SafeTensors API

# Low-level tensor access
sf = SHAInet::SafeTensors::File.new("model.safetensors")
sf.tensor_names          # => ["transformer.wte.weight", ...]
info = sf.tensors["transformer.wte.weight"]
info.dtype               # => F32
info.shape               # => [50257, 768]

matrix = sf.read_matrix("transformer.wte.weight")  # => SimpleMatrix
data = sf.read_f64("transformer.h.0.ln_1.weight")  # => Array(Float64)
sf.close

Autograd

a = SHAInet::SimpleMatrix.tensor(1, 2)
a[0, 0] = SHAInet::Autograd::Tensor.new(2.0)
a[0, 1] = SHAInet::Autograd::Tensor.new(3.0)

w = SHAInet::SimpleMatrix.tensor(2, 1)
w[0, 0] = SHAInet::Autograd::Tensor.new(4.0)
w[1, 0] = SHAInet::Autograd::Tensor.new(5.0)

out = a * w
out[0, 0].as(SHAInet::Autograd::Tensor).backward

Contributing

  1. Fork https://github.com/BrightSec/shainet
  2. Create a feature branch
  3. Commit and push your changes
  4. Open a Pull Request

Contributors


Releases

Packages

Used by

Contributors

Languages