Skip to main content

oa/ml/
byte.rs

1//! Raw-byte model inputs and logit decoding.
2
3use crate::{DType, Error, Matrix, Result, Runtime};
4
5/// Fixed vocabulary cardinality for one token per byte value.
6pub const VOCAB_SIZE: usize = 256;
7/// Optional zero-valued padding byte.
8pub const PAD: u8 = 0x00;
9/// Optional beginning-of-sequence byte.
10pub const BOS: u8 = 0x01;
11/// Optional end-of-sequence byte.
12pub const EOS: u8 = 0x02;
13/// Optional sequence-separator byte.
14pub const SEP: u8 = 0x03;
15
16/// Upload raw bytes as a rank-one U8 Matrix on this thread's default runtime.
17///
18/// # Errors
19///
20/// Returns an error when the default runtime cannot be initialized or when
21/// allocation or upload fails.
22pub fn encode(bytes: &[u8]) -> Result<Matrix> {
23	encode_on(&Runtime::current()?, bytes)
24}
25
26/// Upload raw bytes as a rank-one U8 Matrix on a particular runtime.
27///
28/// # Errors
29///
30/// Returns an error when allocation or upload fails.
31pub fn encode_on(runtime: &Runtime, bytes: &[u8]) -> Result<Matrix> {
32	Matrix::new_from_slice_on(runtime, [bytes.len()], bytes)
33}
34
35/// Upload raw bytes as one batched U8 sequence `[1, S]` on this thread's
36/// default runtime.
37///
38/// # Errors
39///
40/// Returns an error when the default runtime cannot be initialized or when
41/// allocation or upload fails.
42pub fn encode_batched(bytes: &[u8]) -> Result<Matrix> {
43	encode_batched_on(&Runtime::current()?, bytes)
44}
45
46/// Upload raw bytes as one batched U8 sequence `[1, S]` on a particular
47/// runtime.
48///
49/// # Errors
50///
51/// Returns an error when allocation or upload fails.
52pub fn encode_batched_on(runtime: &Runtime, bytes: &[u8]) -> Result<Matrix> {
53	Matrix::new_from_slice_on(runtime, [1, bytes.len()], bytes)
54}
55
56/// Upload UTF-8 text without tokenization or normalization on this thread's
57/// default runtime.
58///
59/// # Errors
60///
61/// Returns an error when the default runtime cannot be initialized or when
62/// allocation or upload fails.
63pub fn encode_text(text: &str) -> Result<Matrix> {
64	encode_text_on(&Runtime::current()?, text)
65}
66
67/// Upload UTF-8 text without tokenization or normalization on a particular
68/// runtime.
69///
70/// # Errors
71///
72/// Returns an error when allocation or upload fails.
73pub fn encode_text_on(runtime: &Runtime, text: &str) -> Result<Matrix> {
74	encode_on(runtime, text.as_bytes())
75}
76
77/// Greedily decode one byte from each FP32 logit row.
78///
79/// This is an explicit submission, completion, and compact host-read boundary.
80///
81/// # Errors
82///
83/// Returns an error unless logits are rank-one `[256]` or rank-two `[N, 256]`
84/// FP32, or execution/readback fails.
85pub fn decode(logits: &Matrix) -> Result<Vec<u8>> {
86	decode_sampled(logits, 0.0, 0, 1.0, 0)
87}
88
89/// Sample one byte from each FP32 logit row.
90///
91/// # Errors
92///
93/// Returns an error for an invalid 256-class logit contract, sampling contract,
94/// execution, or readback failure.
95pub fn sample(
96	logits: &Matrix,
97	temperature: f32,
98	top_k: i32,
99	top_p: f32,
100	seed: u64,
101) -> Result<Vec<u8>> {
102	decode_sampled(logits, temperature, top_k, top_p, seed)
103}
104
105/// Greedily decode logits and require exact UTF-8 output.
106///
107/// # Errors
108///
109/// Returns the errors from [`decode`] or [`crate::ErrorKind::DataLoss`] when the
110/// decoded byte stream is not UTF-8.
111pub fn decode_text(logits: &Matrix) -> Result<String> {
112	String::from_utf8(decode(logits)?)
113		.map_err(|_| Error::data_loss("byte logits do not decode to valid UTF-8"))
114}
115
116fn decode_sampled(
117	logits: &Matrix,
118	temperature: f32,
119	top_k: i32,
120	top_p: f32,
121	seed: u64,
122) -> Result<Vec<u8>> {
123	if logits.dtype() != DType::F32
124		|| !(1..=2).contains(&logits.shape().len())
125		|| logits.shape().last() != Some(&VOCAB_SIZE)
126	{
127		return Err(Error::invalid_argument(
128			"byte decoding requires rank-one or rank-two FP32 logits with 256 classes",
129		));
130	}
131	let ids = crate::matrix::sample_logits(logits, temperature, top_k, top_p, seed)?;
132	ids
133		.read::<i32>()?
134		.into_iter()
135		.map(|id| {
136			u8::try_from(id)
137				.map_err(|_| Error::internal("256-class byte sampling produced an out-of-range token"))
138		})
139		.collect()
140}