torobi 0.1.0-arm64-darwin
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +71 -0
- data/LICENSE +21 -0
- data/README.md +259 -0
- data/config/ops.yml +230 -0
- data/docs/plan.md +3982 -0
- data/docs/vendoring.md +656 -0
- data/lib/torobi/3.3/torobi.bundle +0 -0
- data/lib/torobi/3.4/torobi.bundle +0 -0
- data/lib/torobi/4.0/torobi.bundle +0 -0
- data/lib/torobi/adapter_file.rb +184 -0
- data/lib/torobi/batch.rb +55 -0
- data/lib/torobi/checkpoint.rb +60 -0
- data/lib/torobi/dsl/builder.rb +414 -0
- data/lib/torobi/dsl/handle.rb +156 -0
- data/lib/torobi/dsl/layers.rb +82 -0
- data/lib/torobi/dsl.rb +35 -0
- data/lib/torobi/errors.rb +88 -0
- data/lib/torobi/export.rb +534 -0
- data/lib/torobi/freeze.rb +24 -0
- data/lib/torobi/freshness.rb +57 -0
- data/lib/torobi/grad_cache.rb +143 -0
- data/lib/torobi/graph_config.rb +301 -0
- data/lib/torobi/hooks.rb +439 -0
- data/lib/torobi/ir/dimensions.rb +26 -0
- data/lib/torobi/ir/dtype.rb +28 -0
- data/lib/torobi/ir/graph/check.rb +116 -0
- data/lib/torobi/ir/graph.rb +52 -0
- data/lib/torobi/ir/input_spec.rb +39 -0
- data/lib/torobi/ir/json.rb +45 -0
- data/lib/torobi/ir/node_spec.rb +52 -0
- data/lib/torobi/ir/parameter_spec.rb +67 -0
- data/lib/torobi/ir/ref.rb +52 -0
- data/lib/torobi/ir/source.rb +65 -0
- data/lib/torobi/ir.rb +23 -0
- data/lib/torobi/journal.rb +310 -0
- data/lib/torobi/lora.rb +190 -0
- data/lib/torobi/memory.rb +50 -0
- data/lib/torobi/metallib.rb +50 -0
- data/lib/torobi/mlx_prebuilt.json +24 -0
- data/lib/torobi/mlx_prebuilt.rb +378 -0
- data/lib/torobi/models/build.rb +37 -0
- data/lib/torobi/models/description.rb +59 -0
- data/lib/torobi/models/gemma3.rb +273 -0
- data/lib/torobi/models/llama.rb +381 -0
- data/lib/torobi/models/modern_bert.rb +513 -0
- data/lib/torobi/models/padding.rb +27 -0
- data/lib/torobi/models/windows.rb +53 -0
- data/lib/torobi/ops.rb +81 -0
- data/lib/torobi/preflight.rb +136 -0
- data/lib/torobi/provenance.rb +75 -0
- data/lib/torobi/quantization.rb +151 -0
- data/lib/torobi/replay.rb +229 -0
- data/lib/torobi/runner.rb +419 -0
- data/lib/torobi/session.rb +855 -0
- data/lib/torobi/shape.rb +438 -0
- data/lib/torobi/tensor_data.rb +178 -0
- data/lib/torobi/version.rb +5 -0
- data/lib/torobi/weights.rb +108 -0
- data/lib/torobi.rb +67 -0
- data/licenses/MLX.txt +21 -0
- data/licenses/README.md +16 -0
- data/licenses/gguflib.txt +21 -0
- data/licenses/mlx-c.txt +21 -0
- data/licenses/mlx-rs.txt +27 -0
- metadata +196 -0
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Torobi
|
|
6
|
+
# An adapter as PEFT saves one: `adapter_config.json` and
|
|
7
|
+
# `adapter_model.safetensors`, read back (docs/qlora.md section 3.6 is
|
|
8
|
+
# the other direction).
|
|
9
|
+
#
|
|
10
|
+
# What it is for is carrying an adapter between processes. A fine-tune
|
|
11
|
+
# writes one (`Session#export_adapter!`), and what generates with it, or
|
|
12
|
+
# trains it further, is another run that opened the base model and
|
|
13
|
+
# declared the same adapter. An adapter made by PEFT itself comes the
|
|
14
|
+
# same way.
|
|
15
|
+
#
|
|
16
|
+
# **It reads what it understands and refuses the rest.** PEFT's adapters
|
|
17
|
+
# can be many things, and a few of them look like a LoRA and are not: a
|
|
18
|
+
# `use_rslora` adapter scales by `alpha / sqrt(rank)` rather than by
|
|
19
|
+
# `alpha / rank`, so its matrices read as a LoRA would be a different
|
|
20
|
+
# function that runs without complaint. Each of those is a refusal that
|
|
21
|
+
# names the key, rather than a model that is quietly not the one that was
|
|
22
|
+
# trained.
|
|
23
|
+
#
|
|
24
|
+
# file = Torobi::AdapterFile.read("out/adapter")
|
|
25
|
+
# file.lora # => Torobi::LoRA, from the config
|
|
26
|
+
# file.base # => "Qwen/Qwen2.5-0.5B" (what it was trained on), or nil
|
|
27
|
+
# file.tensors # => { "model.layers.0.self_attn.q_proj.lora_A.weight" => TensorData, ... }
|
|
28
|
+
class AdapterFile
|
|
29
|
+
CONFIG = "adapter_config.json"
|
|
30
|
+
WEIGHTS = "adapter_model.safetensors"
|
|
31
|
+
|
|
32
|
+
# What PEFT puts before a module's own path in the file.
|
|
33
|
+
PREFIX = "base_model.model."
|
|
34
|
+
|
|
35
|
+
# Keys of the config that make an adapter something other than the
|
|
36
|
+
# plain LoRA this is: key => [the value that means plain, why not].
|
|
37
|
+
PLAIN = {
|
|
38
|
+
"use_rslora" => [false, "it scales by alpha / sqrt(rank), not alpha / rank"],
|
|
39
|
+
"use_dora" => [false, "it also trains a magnitude vector per weight"],
|
|
40
|
+
"bias" => ["none", "it trains biases too"],
|
|
41
|
+
"fan_in_fan_out" => [false, "its weights are stored transposed"],
|
|
42
|
+
"modules_to_save" => [nil, "it saves whole modules beside the low-rank matrices"]
|
|
43
|
+
}.freeze
|
|
44
|
+
|
|
45
|
+
attr_reader :config, :tensors
|
|
46
|
+
|
|
47
|
+
def self.read(dir)
|
|
48
|
+
dir = dir.to_s
|
|
49
|
+
raise ArgumentError, "#{dir.inspect} is not a directory" unless File.directory?(dir)
|
|
50
|
+
|
|
51
|
+
config_path = File.join(dir, CONFIG)
|
|
52
|
+
weights_path = File.join(dir, WEIGHTS)
|
|
53
|
+
[config_path, weights_path].each do |path|
|
|
54
|
+
raise ArgumentError, "#{path} is missing: not an adapter PEFT saved" unless File.file?(path)
|
|
55
|
+
end
|
|
56
|
+
new(JSON.parse(File.read(config_path)), read_safetensors(weights_path), dir)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def initialize(config, tensors, dir = nil)
|
|
60
|
+
@config = config
|
|
61
|
+
@dir = dir
|
|
62
|
+
check_plain!
|
|
63
|
+
@tensors = name_tensors(tensors)
|
|
64
|
+
freeze
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# What the adapter was trained on, as the config says it.
|
|
68
|
+
def base = config["base_model_name_or_path"]
|
|
69
|
+
|
|
70
|
+
# The adapter as a graph declares one: the rank, the scale's alpha and
|
|
71
|
+
# the linears it is on. `lora_dropout` is how it was trained and not
|
|
72
|
+
# what it is, so it is not read.
|
|
73
|
+
def lora
|
|
74
|
+
targets = config["target_modules"]
|
|
75
|
+
unless targets.is_a?(Array) && !targets.empty? && targets.all?(String)
|
|
76
|
+
raise ConfigError,
|
|
77
|
+
"#{where}target_modules is #{targets.inspect}; a list of module names is " \
|
|
78
|
+
"what is read (a string is a regular expression to PEFT, which this does not match)"
|
|
79
|
+
end
|
|
80
|
+
%w[rank_pattern alpha_pattern].each do |key|
|
|
81
|
+
next if config[key].nil? || config[key].empty?
|
|
82
|
+
|
|
83
|
+
raise ConfigError, "#{where}#{key} gives some layers another rank or alpha than " \
|
|
84
|
+
"the rest, which a Torobi::LoRA does not say"
|
|
85
|
+
end
|
|
86
|
+
LoRA.new(rank: config.fetch("r"), alpha: config.fetch("lora_alpha"), on: targets,
|
|
87
|
+
dropout: config["lora_dropout"] || 0.0, tokens: trained_tokens)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# The tokens whose rows it trains (`trainable_token_indices`): a list of ids, or ids by
|
|
91
|
+
# module, which must be the same for each module, as a `Torobi::LoRA` trains one set.
|
|
92
|
+
def trained_tokens
|
|
93
|
+
given = config["trainable_token_indices"]
|
|
94
|
+
case given
|
|
95
|
+
when nil then []
|
|
96
|
+
when Array then given
|
|
97
|
+
when Hash
|
|
98
|
+
sets = given.values.uniq
|
|
99
|
+
return sets.first if sets.size == 1
|
|
100
|
+
|
|
101
|
+
raise ConfigError,
|
|
102
|
+
"#{where}trainable_token_indices names different tokens for different modules, " \
|
|
103
|
+
"which a Torobi::LoRA does not say"
|
|
104
|
+
else
|
|
105
|
+
raise ConfigError, "#{where}trainable_token_indices is #{given.inspect}"
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Reads the file as safetensors, to `{ name => TensorData }` in f32:
|
|
110
|
+
# an adapter's matrices are f32 in a run, and a file in f16 or bf16 is
|
|
111
|
+
# widened on the way in.
|
|
112
|
+
def self.read_safetensors(path)
|
|
113
|
+
File.open(path, "rb") do |io|
|
|
114
|
+
header = JSON.parse(io.read(io.read(8).unpack1("Q<")))
|
|
115
|
+
base = io.pos
|
|
116
|
+
header.except("__metadata__").to_h do |name, entry|
|
|
117
|
+
from, to = entry.fetch("data_offsets")
|
|
118
|
+
io.seek(base + from)
|
|
119
|
+
[name, decode(name, entry.fetch("dtype"), entry.fetch("shape"), io.read(to - from))]
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def self.decode(name, dtype, shape, bytes)
|
|
125
|
+
packed =
|
|
126
|
+
case dtype
|
|
127
|
+
when "F32" then bytes
|
|
128
|
+
when "BF16" then bytes.unpack("S<*").map { |bits| bits << 16 }.pack("L<*")
|
|
129
|
+
when "F16" then bytes.unpack("S<*").map { |bits| half(bits) }.pack("f*")
|
|
130
|
+
else raise ConfigError,
|
|
131
|
+
"#{name}: a tensor of dtype #{dtype}; an adapter's are F32, F16 or BF16"
|
|
132
|
+
end
|
|
133
|
+
TensorData.new(shape, packed, dtype: :f32, where: name)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# An IEEE half as a Float.
|
|
137
|
+
def self.half(bits)
|
|
138
|
+
sign = bits[15].zero? ? 1.0 : -1.0
|
|
139
|
+
exponent = (bits >> 10) & 0x1f
|
|
140
|
+
fraction = bits & 0x3ff
|
|
141
|
+
return sign * fraction * (2.0**-24) if exponent.zero?
|
|
142
|
+
return fraction.zero? ? sign * Float::INFINITY : Float::NAN if exponent == 31
|
|
143
|
+
|
|
144
|
+
sign * (1 + (fraction / 1024.0)) * (2.0**(exponent - 15))
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
private
|
|
148
|
+
|
|
149
|
+
def where = @dir ? "#{File.join(@dir, CONFIG)}: " : "adapter config: "
|
|
150
|
+
|
|
151
|
+
def check_plain!
|
|
152
|
+
unless config["peft_type"] == "LORA"
|
|
153
|
+
raise ConfigError, "#{where}peft_type is #{config["peft_type"].inspect}; only LORA is read"
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
PLAIN.each do |key, (plain, why)|
|
|
157
|
+
value = config[key]
|
|
158
|
+
next if value.nil? || value == plain || value == []
|
|
159
|
+
|
|
160
|
+
raise ConfigError,
|
|
161
|
+
"#{where}#{key} is #{value.inspect}, and #{why}; that is not a LoRA this reads"
|
|
162
|
+
end
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# The names in the file are `base_model.model.<module path>.lora_A.weight`
|
|
166
|
+
# (older PEFT wrote `lora_A.default.weight`); what a run calls the same
|
|
167
|
+
# parameter is the module path with the same ending.
|
|
168
|
+
def name_tensors(tensors)
|
|
169
|
+
tensors.to_h do |name, tensor|
|
|
170
|
+
path = name.delete_prefix(PREFIX).sub(/\.(lora_[AB])\.default\.weight\z/, '.\1.weight')
|
|
171
|
+
.sub(/\.token_adapter\.#{LoRA.rows_name}(\.default)?\z/, ".#{LoRA.rows_name}")
|
|
172
|
+
known = path.match?(/\.lora_[AB]\.weight\z|\.#{LoRA.rows_name}\z/)
|
|
173
|
+
unless known && name.start_with?(PREFIX)
|
|
174
|
+
raise ConfigError,
|
|
175
|
+
"#{name.inspect} is not one of the low-rank matrices " \
|
|
176
|
+
"(base_model.model.<module>.lora_A.weight and lora_B) or trained rows " \
|
|
177
|
+
"(<module>.token_adapter.trainable_tokens_delta); " \
|
|
178
|
+
"what else the file holds is not read"
|
|
179
|
+
end
|
|
180
|
+
[path, tensor]
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
end
|
data/lib/torobi/batch.rb
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
# One step's inputs: a TensorData per batch field.
|
|
5
|
+
#
|
|
6
|
+
# A batch is written as {name => tensor}, where a tensor is a
|
|
7
|
+
# `Torobi::TensorData` or the plain {shape:, data:, dtype:} Hash that
|
|
8
|
+
# predates it (`TensorData.from`). Either way it is a TensorData once it
|
|
9
|
+
# is in here, so what crosses the boundary is one kind of value, checked
|
|
10
|
+
# once: that its bytes are as many as its shape and dtype say.
|
|
11
|
+
#
|
|
12
|
+
# Prefer TensorData for anything large. A Hash of numbers means every
|
|
13
|
+
# element exists in Ruby before any of it is packed, which for a mask is
|
|
14
|
+
# millions of Floats built to be thrown away; TensorData can be built
|
|
15
|
+
# from runs instead.
|
|
16
|
+
#
|
|
17
|
+
# The packing itself is measured rather than assumed: JSON cost two
|
|
18
|
+
# thirds of a step at 512 rows while the call boundary was noise (see
|
|
19
|
+
# docs/plan.md section 5A.2.1 and bench/boundary.rb).
|
|
20
|
+
class Batch
|
|
21
|
+
# `batch` may already be a Batch, which is returned as it is.
|
|
22
|
+
def self.of(batch) = batch.is_a?(Batch) ? batch : new(batch)
|
|
23
|
+
|
|
24
|
+
def initialize(fields)
|
|
25
|
+
@fields = fields.to_h do |name, tensor|
|
|
26
|
+
[name.to_s, TensorData.from(tensor, where: "input #{name}")]
|
|
27
|
+
end.freeze
|
|
28
|
+
freeze
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The fields, by name.
|
|
32
|
+
attr_reader :fields
|
|
33
|
+
|
|
34
|
+
def names = @fields.keys
|
|
35
|
+
|
|
36
|
+
def fetch(name) = @fields.fetch(name.to_s)
|
|
37
|
+
|
|
38
|
+
# A digest of the data, so a journal can name the batch it was fed
|
|
39
|
+
# without holding it (`Provenance.digest_of`), and a replay can say
|
|
40
|
+
# whether the data it is given is the data that was recorded.
|
|
41
|
+
#
|
|
42
|
+
# Reading the whole payload makes this a per-step cost proportional to
|
|
43
|
+
# the batch. It is paid only where a journal is written: `Session`
|
|
44
|
+
# computes it as the argument to a `&.` call, and a run that records
|
|
45
|
+
# nothing computes nothing.
|
|
46
|
+
def digest
|
|
47
|
+
Provenance.digest_of(*@fields.sort.flat_map do |name, tensor|
|
|
48
|
+
[name, tensor.dtype.to_s, tensor.shape, tensor.bytes]
|
|
49
|
+
end)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# What the engine is handed: {name => [dtype, shape, bytes]}.
|
|
53
|
+
def to_native = @fields.transform_values(&:to_native)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
# A checkpoint directory, and what it says about itself, read without a
|
|
5
|
+
# session.
|
|
6
|
+
#
|
|
7
|
+
# A checkpoint is a run's record, not only its numbers: it carries the
|
|
8
|
+
# GraphConfig it belongs to, the parameter inventory with shapes and
|
|
9
|
+
# dtypes, the optimizer and its step count, the build and the machine,
|
|
10
|
+
# and whatever the caller recorded about where in the data it was
|
|
11
|
+
# (docs/plan.md section 11.2). Reading it is how a caller decides which
|
|
12
|
+
# one to resume from, before committing a session to it.
|
|
13
|
+
#
|
|
14
|
+
# checkpoint = s.checkpoint!("run/000200", at: { epoch: 2 })
|
|
15
|
+
# checkpoint.step # => 200
|
|
16
|
+
# checkpoint.position # => {"epoch" => 2}
|
|
17
|
+
#
|
|
18
|
+
# Read from disk each time it is asked, never remembered: the directory
|
|
19
|
+
# is the checkpoint, and a run may write it again.
|
|
20
|
+
class Checkpoint
|
|
21
|
+
def initialize(dir)
|
|
22
|
+
@dir = dir.to_s
|
|
23
|
+
freeze
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
attr_reader :dir
|
|
27
|
+
|
|
28
|
+
# A checkpoint stands where a path is asked for: `File.exist?(c)`,
|
|
29
|
+
# `s.restore(c)`.
|
|
30
|
+
def to_path = @dir
|
|
31
|
+
alias to_s to_path
|
|
32
|
+
|
|
33
|
+
# Whether the directory holds a checkpoint at all.
|
|
34
|
+
def exist? = File.exist?(File.join(@dir, "manifest.json"))
|
|
35
|
+
|
|
36
|
+
# The manifest, as a Hash. Raises if the directory holds no checkpoint
|
|
37
|
+
# or holds one of another schema.
|
|
38
|
+
def manifest = Native.checkpoint_manifest(@dir)
|
|
39
|
+
|
|
40
|
+
# The step the run had reached.
|
|
41
|
+
def step = manifest.fetch("step")
|
|
42
|
+
|
|
43
|
+
# Where in the data the run was, as the caller recorded it. Torobi does
|
|
44
|
+
# not own datasets, so this is whatever `checkpoint!` was given.
|
|
45
|
+
def position = manifest.dig("run", "position")
|
|
46
|
+
|
|
47
|
+
# The GraphConfig the checkpoint belongs to, as JSON text. Present so
|
|
48
|
+
# that a checkpoint can be read by someone who does not have the
|
|
49
|
+
# description that produced it: a digest names one, it does not
|
|
50
|
+
# reconstruct one.
|
|
51
|
+
def graph_json = File.read(File.join(@dir, "graph.json"))
|
|
52
|
+
|
|
53
|
+
def ==(other) = other.is_a?(Checkpoint) && other.dir == dir
|
|
54
|
+
alias eql? ==
|
|
55
|
+
|
|
56
|
+
def hash = [Checkpoint, dir].hash
|
|
57
|
+
|
|
58
|
+
def inspect = "#<Torobi::Checkpoint #{dir}>"
|
|
59
|
+
end
|
|
60
|
+
end
|