1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use super::*;
use crate::{
execution::{BindingContract, BufferView, GpuKernel, Graph, KernelContract, MemoryPlacement},
inference::{InferenceGraph, ModelContext, PreparedModel},
tensor::{DeviceTensor, TensorDesc},
};
#[derive(Clone)]
enum Storage {
Weight(crate::execution::Buffer),
Scratch(usize, Placement),
}
/// Immutable model code and weights in a shared context. Shape-specific plans
/// allocate private scratch and graph storage for each bounded inference slot.
pub struct ModelDefinition {
id: u64,
context: ModelContext,
allocations: Vec<Storage>,
kernels: Vec<Kernel>,
}
/// Validated, shape-specific model commands with shared immutable weights.
/// Record into a caller-owned graph to connect stages without copies, or build
/// a standalone bounded inference pool with [`Self::prepare`].
pub struct ModelFragment {
context: ModelContext,
allocations: Vec<Storage>,
extents: Vec<usize>,
commands: Vec<(Option<GpuKernel>, Vec<Region>, Option<u8>)>,
inputs: Vec<(Region, TensorDesc)>,
outputs: Vec<(Region, TensorDesc)>,
}
impl ModelSession {
/// Transfer code and immutable weights to a coordinated context. All raw
/// graphs are destroyed after synchronization, before adopting allocations.
/// Scratch and host staging are discarded; prepared slots initialize their
/// own scratch. Values needed across inferences must use [`Self::weight`].
pub fn freeze(mut self, context: &ModelContext) -> Result<ModelDefinition> {
self.synchronize()?;
if self.stream.device_id()
!= Device::open(context.runtime().gpu()?.index())?
.stream()?
.device_id()
{
return Err(Error::Message("model belongs to another device".into()));
}
self.graphs.clear();
let allocations = self
.allocations
.drain(..)
.map(|allocation| {
if allocation.immutable {
// The session exclusively owns the allocation. Upload has been
// drained above; all old native graphs have been destroyed.
let buffer = unsafe {
context
.runtime()
.adopt_gpu_buffer(allocation.buffer, MemoryPlacement::GpuLocal)?
};
Ok(Storage::Weight(buffer))
} else {
Ok(Storage::Scratch(
allocation.buffer.bytes(),
allocation.placement,
))
}
})
.collect::<Result<Vec<_>>>()?;
Ok(ModelDefinition {
id: self.id,
context: context.clone(),
allocations,
kernels: self.kernels,
})
}
}
impl ModelDefinition {
/// Shared scheduling and allocation domain.
pub fn context(&self) -> &ModelContext {
&self.context
}
/// Physical immutable weight bytes, counted once regardless of plan or slot count.
pub fn weight_bytes(&self) -> usize {
self.allocations
.iter()
.map(|storage| match storage {
Storage::Weight(buffer) => buffer.len(),
Storage::Scratch(..) => 0,
})
.sum()
}
fn validate_region(&self, region: Region) -> Result<()> {
if region.session != self.id {
return Err(Error::Message(
"model region belongs to another definition".into(),
));
}
let bytes = match self.allocations.get(region.allocation) {
Some(Storage::Weight(buffer)) => buffer.len(),
Some(Storage::Scratch(bytes, _)) => *bytes,
None => return Err(Error::Message("invalid model allocation".into())),
};
if region
.offset
.checked_add(region.bytes)
.is_none_or(|end| end > bytes)
{
return Err(Error::Message("model region exceeds allocation".into()));
}
Ok(())
}
/// Prepare a shape with shared weights and fixed-address private slots.
/// Input/output descriptors select leading bytes of their corresponding
/// regions. Commands must restrict accesses to the selected shape.
///
/// # Safety
/// Dispatch bindings and scalar arguments must exactly describe the trusted
/// compiled code, including accessible extents and every read or write.
/// Writable argument aliasing must be safe for that kernel's execution.
pub unsafe fn prepare(
&self,
commands: &[Command],
inputs: &[(Region, TensorDesc)],
outputs: &[(Region, TensorDesc)],
capacity: usize,
) -> Result<PreparedModel> {
// Safety: forwarded unchanged from the caller.
unsafe { self.fragment(commands, inputs, outputs)? }.prepare(capacity)
}
/// Validate a shape's commands once, without allocating inference slots.
/// The fragment owns shared weights and code independently of this definition.
///
/// # Safety
/// Dispatch contracts, accessible extents and writable aliases must satisfy
/// the same requirements as [`Self::prepare`].
pub unsafe fn fragment(
&self,
commands: &[Command],
inputs: &[(Region, TensorDesc)],
outputs: &[(Region, TensorDesc)],
) -> Result<ModelFragment> {
for (region, desc) in inputs.iter().chain(outputs) {
self.validate_region(*region)?;
if desc.is_empty() || desc.bytes() > region.bytes {
return Err(Error::Message(
"model IO descriptor exceeds its region or is empty".into(),
));
}
if matches!(self.allocations[region.allocation], Storage::Weight(_)) {
return Err(Error::Message(
"model IO cannot alias immutable weights".into(),
));
}
}
let mut prepared = Vec::with_capacity(commands.len());
for command in commands {
match command {
Command::Fill { region, value } => {
self.validate_region(*region)?;
if matches!(self.allocations[region.allocation], Storage::Weight(_)) {
return Err(Error::Message("cannot fill immutable weights".into()));
}
prepared.push((None, vec![*region], Some(*value)));
}
Command::Dispatch(dispatch) => {
if dispatch.kernel.session != self.id {
return Err(Error::Message(
"kernel belongs to another definition".into(),
));
}
let kernel = self
.kernels
.get(dispatch.kernel.index)
.ok_or_else(|| Error::Message("invalid model kernel".into()))?;
let mut bindings = Vec::with_capacity(dispatch.bindings.len());
for binding in &dispatch.bindings {
self.validate_region(binding.region)?;
if binding.access != Access::Read
&& matches!(
self.allocations[binding.region.allocation],
Storage::Weight(_)
)
{
return Err(Error::Message("cannot write immutable weights".into()));
}
bindings.push(BindingContract {
bytes: binding.region.bytes,
alignment: 1,
access: binding.access,
layout: "model region".into(),
});
}
let constants = match &dispatch.arguments {
Arguments::Indices(values) => Constants::indices(kernel, values)?,
Arguments::Packed(constants) => *constants.clone(),
};
// Safety: inherited from this method's caller.
let kernel = unsafe {
self.context.runtime().adopt_gpu_kernel(
kernel.clone(),
dispatch.grid,
kernel.info().workgroup_size,
KernelContract {
bindings,
constants: constants.as_bytes().to_vec(),
},
)?
};
prepared.push((
Some(kernel),
dispatch.bindings.iter().map(|b| b.region).collect(),
None,
));
}
}
}
let mut extents = vec![0; self.allocations.len()];
for (_, regions, _) in &prepared {
for region in regions {
extents[region.allocation] =
extents[region.allocation].max(region.offset + region.bytes);
}
}
for (region, desc) in inputs.iter().chain(outputs) {
extents[region.allocation] =
extents[region.allocation].max(region.offset + desc.bytes());
}
Ok(ModelFragment {
context: self.context.clone(),
allocations: self.allocations.clone(),
extents,
commands: prepared,
inputs: inputs.to_vec(),
outputs: outputs.to_vec(),
})
}
}
impl ModelFragment {
/// Allocate independent fixed-address slots, exposing their actual model IO.
pub fn prepare(&self, capacity: usize) -> Result<PreparedModel> {
PreparedModel::prepare(&self.context, capacity, |context| {
let mut graph = context.runtime().graph();
let (inputs, outputs) = self.append(&mut graph, None)?;
Ok(InferenceGraph {
inputs,
outputs,
graph: graph.prepare()?,
})
})
}
/// Append model commands directly to an unprepared graph. Inputs are bound
/// without a device copy; outputs and scratch are allocated for this graph.
/// Adjacent stages can consume the returned tensors before graph preparation.
/// No pool, host staging, submission or intermediate synchronization is added.
///
/// Inputs must describe the complete accessed regions of their allocations.
/// Partial aliases which would require a copy are rejected. Initialization
/// producers are drained here; this is a preparation-time operation.
pub fn record(&self, graph: &mut Graph, inputs: &[DeviceTensor]) -> Result<Vec<DeviceTensor>> {
Ok(self.append(graph, Some(inputs))?.1)
}
fn append(
&self,
graph: &mut Graph,
supplied: Option<&[DeviceTensor]>,
) -> Result<(Vec<DeviceTensor>, Vec<DeviceTensor>)> {
graph.validate_runtime(self.context.runtime())?;
let mut buffers: Vec<Option<(usize, BufferView)>> = vec![None; self.allocations.len()];
if let Some(inputs) = supplied {
if inputs.len() != self.inputs.len() {
return Err(Error::Message("fragment input count mismatch".into()));
}
for ((region, desc), tensor) in self.inputs.iter().zip(inputs) {
self.context.validate(tensor)?;
if tensor.desc() != desc {
return Err(Error::Message("fragment input descriptor mismatch".into()));
}
tensor.completion().wait()?;
let binding = tensor.binding().expect("nonempty fragment IO");
if buffers.iter().enumerate().any(|(index, old)| {
index != region.allocation && old.as_ref().is_some_and(|(_, old)| old.overlaps(&binding))
}) || self.allocations.iter().any(|storage| {
matches!(storage, Storage::Weight(weight) if weight.view().overlaps(&binding))
}) {
return Err(Error::Message("fragment remapping introduces an undeclared alias".into()));
}
if let Some((base, old)) = &buffers[region.allocation] {
if *base != region.offset || !old.same_region(&binding) {
return Err(Error::Message(
"fragment inputs alias one allocation inconsistently".into(),
));
}
} else {
buffers[region.allocation] = Some((region.offset, binding));
}
}
}
for (index, storage) in self.allocations.iter().enumerate() {
if buffers[index].is_none() {
buffers[index] = match storage {
Storage::Weight(buffer) => Some((0, buffer.view())),
Storage::Scratch(..) if self.extents[index] == 0 => None,
Storage::Scratch(_, placement) => Some((
0,
self.context
.runtime()
.allocate(
self.extents[index],
match placement {
Placement::Device => MemoryPlacement::GpuLocal,
Placement::Shared => MemoryPlacement::HostVisible,
},
)?
.view(),
)),
};
}
}
let view = |region: Region| -> Result<BufferView> {
let (base, buffer) = buffers[region.allocation]
.as_ref()
.expect("referenced allocation");
let start = region
.offset
.checked_sub(*base)
.ok_or_else(|| Error::Message("fragment access precedes bound input".into()))?;
buffer.slice(start..start + region.bytes)
};
let tensors = |io: &[(Region, TensorDesc)]| {
io.iter()
.map(|(region, desc)| {
self.context.tensor(
desc.clone(),
view(region.slice(0, desc.bytes())?)?,
crate::Completion::ready(),
)
})
.collect::<Result<Vec<_>>>()
};
let inputs = tensors(&self.inputs)?;
let outputs = tensors(&self.outputs)?;
// Validate every binding before mutating the caller's graph.
let bindings = self
.commands
.iter()
.map(|(_, regions, _)| {
regions
.iter()
.map(|®ion| view(region))
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<_>>>()?;
for ((kernel, _, fill), bindings) in self.commands.iter().zip(bindings) {
if let Some(value) = fill {
graph.fill(bindings[0].clone(), *value)?;
} else if let Some(kernel) = kernel {
// Safety: fragment construction validated the caller's trusted
// contracts. Remapping preserves region offsets and extents.
unsafe {
graph.gpu_aliasing(kernel, &bindings)?;
}
}
}
Ok((inputs, outputs))
}
}