use super::config::{NttRepresentation, power_mod};
use crate::crypto::ntt::NttConfig;
use crate::{
DType, Engine, Error, Matrix, OpAttribute, Result,
runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
};
#[derive(Clone)]
pub struct NttParameters {
config: NttConfig,
forward: Matrix,
inverse: Matrix,
forward_scalar: Option<Matrix>,
inverse_scalar: Option<Matrix>,
negative_inverse: u32,
r2: u64,
inverse_length: u64,
}
impl NttParameters {
pub const fn config(&self) -> &NttConfig {
&self.config
}
}
pub fn prepare(engine: &Engine, config: &NttConfig) -> Result<NttParameters> {
let engine = engine.handle();
let modulus = config.modulus;
let root = config.root;
let one = ((1_u128 << 64) % u128::from(modulus)) as u64;
let r2 = ((u128::from(one) * u128::from(one)) % u128::from(modulus)) as u64;
let root_montgomery = ((u128::from(root) * u128::from(one)) % u128::from(modulus)) as u64;
let inverse_root = power_mod(root, modulus - 2, modulus);
let inverse_root_montgomery =
((u128::from(inverse_root) * u128::from(one)) % u128::from(modulus)) as u64;
let inverse_length = ((u128::from(power_mod(config.length as u64, modulus - 2, modulus))
* u128::from(one))
% u128::from(modulus)) as u64;
let mut inverse = 1_u32;
for _ in 0..5 {
inverse = inverse.wrapping_mul(2_u32.wrapping_sub((modulus as u32).wrapping_mul(inverse)));
}
let negative_inverse = inverse.wrapping_neg();
let count = (config.length / 2) as u32;
let groups = engine.linear_dispatch_grid(count, 128)?;
let forward = Matrix::allocate_output(
&engine,
vec![config.length / 2, 2],
config.length,
DType::U32,
)?;
let inverse = Matrix::allocate_output(
&engine,
vec![config.length / 2, 2],
config.length,
DType::U32,
)?;
let kernel = KernelId::CryptographyNttTwiddlesU32;
let buffers = [
BufferBinding::write(forward.storage()),
BufferBinding::write(inverse.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(negative_inverse),
PushConstant::U32(root_montgomery as u32),
PushConstant::U32((root_montgomery >> 32) as u32),
PushConstant::U32(inverse_root_montgomery as u32),
PushConstant::U32((inverse_root_montgomery >> 32) as u32),
PushConstant::U32(one as u32),
PushConstant::U32((one >> 32) as u32),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TWIDDLES,
inputs: &[],
outputs: &[&forward, &inverse],
attributes: &attributes,
},
)?;
let (forward_scalar, inverse_scalar) = if modulus < (1_u64 << 31) {
let one_scalar = ((1_u128 << 32) % u128::from(modulus)) as u32;
let root_scalar = ((u128::from(root) * u128::from(one_scalar)) % u128::from(modulus)) as u32;
let inverse_root_scalar =
((u128::from(inverse_root) * u128::from(one_scalar)) % u128::from(modulus)) as u32;
let forward_scalar = Matrix::allocate_output(
&engine,
vec![config.length / 2],
config.length / 2,
DType::U32,
)?;
let inverse_scalar = Matrix::allocate_output(
&engine,
vec![config.length / 2],
config.length / 2,
DType::U32,
)?;
let kernel = KernelId::CryptographyNttTwiddlesScalarU32;
let buffers = [
BufferBinding::write(forward_scalar.storage()),
BufferBinding::write(inverse_scalar.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(modulus as u32),
PushConstant::U32(negative_inverse),
PushConstant::U32(root_scalar),
PushConstant::U32(inverse_root_scalar),
PushConstant::U32(one_scalar),
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TWIDDLES,
inputs: &[],
outputs: &[&forward_scalar, &inverse_scalar],
attributes: &attributes,
},
)?;
(Some(forward_scalar), Some(inverse_scalar))
} else {
(None, None)
};
Ok(NttParameters {
config: config.clone(),
forward,
inverse,
forward_scalar,
inverse_scalar,
negative_inverse,
r2,
inverse_length,
})
}
pub fn forward(input: &Matrix, parameters: &NttParameters) -> Result<Matrix> {
let config = ¶meters.config;
let scalar = input.shape().len() == 2;
if input.dtype() != DType::U32
|| !input
.engine_handle()
.same_as(parameters.forward.engine_handle())
|| (scalar && input.shape()[1] != config.length)
|| (!scalar && (input.shape().len() != 3 || input.shape()[1..] != [config.length, 2]))
{
return Err(Error::invalid_argument(
"NTT requires matching-owner U32 [batch, length] scalar or [batch, length, 2] paired coefficients",
));
}
let elements = input.num_elements();
let bytes = elements
.checked_mul(4)
.ok_or_else(|| Error::invalid_argument("NTT input byte extent overflows usize"))?;
u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT input byte extent exceeds u32"))?;
let count = u32::try_from(elements / if scalar { 1 } else { 2 })
.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
let engine = input.engine_handle();
let first = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
if count == 0 {
return Ok(first);
}
let modulus = config.modulus;
let montgomery = u32::from(config.representation == NttRepresentation::Montgomery);
let shared_bytes = engine.compute_shared_memory_bytes() as usize;
if scalar {
let Some(twiddles) = parameters.forward_scalar.as_ref() else {
return Err(Error::invalid_argument(
"Scalar NTT storage requires a prepared modulus below 2^31",
));
};
let cooperative = [
(256, KernelId::CryptographyNttCooperativeScalar256U32),
(1024, KernelId::CryptographyNttCooperativeScalar1024U32),
(4096, KernelId::CryptographyNttCooperativeScalar4096U32),
(8192, KernelId::CryptographyNttCooperativeScalar8192U32),
]
.into_iter()
.find(|(capacity, _)| config.length <= *capacity && capacity * 4 <= shared_bytes);
let Some((_, kernel)) = cooperative else {
return Err(Error::invalid_argument(
"Scalar NTT length exceeds the shared-memory provider capacity; use paired-word storage",
));
};
let modulus32 = modulus as u32;
let r2_scalar = ((1_u128 << 64) % u128::from(modulus)) as u32;
let normalization = ((1_u128 << 32) % u128::from(modulus)) as u32;
let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(input.shape()[0] as u32),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(r2_scalar),
PushConstant::U32(normalization),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 0,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
inputs: &[input, twiddles],
outputs: &[&first],
attributes: &attributes,
},
)?;
return Ok(first);
}
let twiddles = ¶meters.forward;
let normalization = ((1_u128 << 64) % u128::from(modulus)) as u64;
let cooperative = [
(256, KernelId::CryptographyNttCooperative256U32),
(1024, KernelId::CryptographyNttCooperative1024U32),
(4096, KernelId::CryptographyNttCooperative4096U32),
(8192, KernelId::CryptographyNttCooperative8192U32),
]
.into_iter()
.find(|(capacity, _)| config.length <= *capacity && capacity * 8 <= shared_bytes);
if let Some((_, kernel)) = cooperative {
let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(input.shape()[0] as u32),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(parameters.r2 as u32),
PushConstant::U32((parameters.r2 >> 32) as u32),
PushConstant::U32(normalization as u32),
PushConstant::U32((normalization >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 0,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
inputs: &[input, twiddles],
outputs: &[&first],
attributes: &attributes,
},
)?;
return Ok(first);
}
let second = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
let groups = engine.linear_dispatch_grid(count, 128)?;
let kernel = KernelId::CryptographyNttReorderU32;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(parameters.r2 as u32),
PushConstant::U32((parameters.r2 >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_REORDER,
inputs: &[input],
outputs: &[&first],
attributes: &attributes,
},
)?;
let mut current = first.clone();
let fused = [
(8192, KernelId::CryptographyNttStageFused8192U32),
(4096, KernelId::CryptographyNttStageFused4096U32),
(1024, KernelId::CryptographyNttStageFused1024U32),
(256, KernelId::CryptographyNttStageFused256U32),
]
.into_iter()
.find(|(capacity, _)| *capacity < config.length && capacity * 8 <= shared_bytes);
let mut completed_stages = 0u32;
if let Some((capacity, kernel)) = fused {
let tiles = count / capacity as u32;
let groups = engine.linear_dispatch_grid(tiles, 1)?;
let output = second.reshape_semantic_output(input.shape().to_vec())?;
let buffers = [
BufferBinding::read(current.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(tiles),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 0,
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_STAGE_FUSED,
inputs: &[¤t, twiddles],
outputs: &[&output],
attributes: &attributes,
},
)?;
current = output;
completed_stages = capacity.trailing_zeros();
}
let mut current_is_second = fused.is_some();
let groups = engine.linear_dispatch_grid(count / 2, 128)?;
for stage in (completed_stages + 1)..=config.length.trailing_zeros() {
let span = 1_u32 << stage;
let target = if current_is_second { &first } else { &second };
let output = target.reshape_semantic_output(input.shape().to_vec())?;
let kernel = KernelId::CryptographyNttStageU32;
let buffers = [
BufferBinding::read(current.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(count / 2),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.length as u32),
PushConstant::U32(span),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(normalization as u32),
PushConstant::U32((normalization >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "span".into(),
value: u64::from(span),
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 0,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_STAGE,
inputs: &[¤t, twiddles],
outputs: &[&output],
attributes: &attributes,
},
)?;
current = output;
current_is_second = !current_is_second;
}
Ok(current)
}
pub fn inverse(input: &Matrix, parameters: &NttParameters) -> Result<Matrix> {
let config = ¶meters.config;
let scalar = input.shape().len() == 2;
if input.dtype() != DType::U32
|| !input
.engine_handle()
.same_as(parameters.forward.engine_handle())
|| (scalar && input.shape()[1] != config.length)
|| (!scalar && (input.shape().len() != 3 || input.shape()[1..] != [config.length, 2]))
{
return Err(Error::invalid_argument(
"NTT requires matching-owner U32 [batch, length] scalar or [batch, length, 2] paired coefficients",
));
}
let elements = input.num_elements();
let bytes = elements
.checked_mul(4)
.ok_or_else(|| Error::invalid_argument("NTT input byte extent overflows usize"))?;
u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT input byte extent exceeds u32"))?;
let count = u32::try_from(elements / if scalar { 1 } else { 2 })
.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
let engine = input.engine_handle();
let first = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
if count == 0 {
return Ok(first);
}
let modulus = config.modulus;
let montgomery = u32::from(config.representation == NttRepresentation::Montgomery);
let shared_bytes = engine.compute_shared_memory_bytes() as usize;
if scalar {
let Some(twiddles) = parameters.inverse_scalar.as_ref() else {
return Err(Error::invalid_argument(
"Scalar NTT storage requires a prepared modulus below 2^31",
));
};
let cooperative = [
(256, KernelId::CryptographyNttCooperativeScalar256U32),
(1024, KernelId::CryptographyNttCooperativeScalar1024U32),
(4096, KernelId::CryptographyNttCooperativeScalar4096U32),
(8192, KernelId::CryptographyNttCooperativeScalar8192U32),
]
.into_iter()
.find(|(capacity, _)| config.length <= *capacity && capacity * 4 <= shared_bytes);
let Some((_, kernel)) = cooperative else {
return Err(Error::invalid_argument(
"Scalar NTT length exceeds the shared-memory provider capacity; use paired-word storage",
));
};
let modulus32 = modulus as u32;
let r2_scalar = ((1_u128 << 64) % u128::from(modulus)) as u32;
let normalization = ((u128::from(power_mod(config.length as u64, modulus - 2, modulus))
* (1_u128 << 32))
% u128::from(modulus)) as u32;
let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(input.shape()[0] as u32),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(r2_scalar),
PushConstant::U32(normalization),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 1,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
inputs: &[input, twiddles],
outputs: &[&first],
attributes: &attributes,
},
)?;
return Ok(first);
}
let twiddles = ¶meters.inverse;
let normalization = parameters.inverse_length;
let cooperative = [
(256, KernelId::CryptographyNttCooperative256U32),
(1024, KernelId::CryptographyNttCooperative1024U32),
(4096, KernelId::CryptographyNttCooperative4096U32),
(8192, KernelId::CryptographyNttCooperative8192U32),
]
.into_iter()
.find(|(capacity, _)| config.length <= *capacity && capacity * 8 <= shared_bytes);
if let Some((_, kernel)) = cooperative {
let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(input.shape()[0] as u32),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(parameters.r2 as u32),
PushConstant::U32((parameters.r2 >> 32) as u32),
PushConstant::U32(normalization as u32),
PushConstant::U32((normalization >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 1,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
inputs: &[input, twiddles],
outputs: &[&first],
attributes: &attributes,
},
)?;
return Ok(first);
}
let second = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
let groups = engine.linear_dispatch_grid(count, 128)?;
let kernel = KernelId::CryptographyNttReorderU32;
let buffers = [
BufferBinding::read(input.storage()),
BufferBinding::write(first.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.length as u32),
PushConstant::U32(config.length.trailing_zeros()),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(parameters.r2 as u32),
PushConstant::U32((parameters.r2 >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_REORDER,
inputs: &[input],
outputs: &[&first],
attributes: &attributes,
},
)?;
let mut current = first.clone();
let fused = [
(8192, KernelId::CryptographyNttStageFused8192U32),
(4096, KernelId::CryptographyNttStageFused4096U32),
(1024, KernelId::CryptographyNttStageFused1024U32),
(256, KernelId::CryptographyNttStageFused256U32),
]
.into_iter()
.find(|(capacity, _)| *capacity < config.length && capacity * 8 <= shared_bytes);
let mut completed_stages = 0u32;
if let Some((capacity, kernel)) = fused {
let tiles = count / capacity as u32;
let groups = engine.linear_dispatch_grid(tiles, 1)?;
let output = second.reshape_semantic_output(input.shape().to_vec())?;
let buffers = [
BufferBinding::read(current.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(tiles),
PushConstant::U32(groups[0]),
PushConstant::U32(config.length as u32),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 1,
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_STAGE_FUSED,
inputs: &[¤t, twiddles],
outputs: &[&output],
attributes: &attributes,
},
)?;
current = output;
completed_stages = capacity.trailing_zeros();
}
let mut current_is_second = fused.is_some();
let groups = engine.linear_dispatch_grid(count / 2, 128)?;
for stage in (completed_stages + 1)..=config.length.trailing_zeros() {
let span = 1_u32 << stage;
let target = if current_is_second { &first } else { &second };
let output = target.reshape_semantic_output(input.shape().to_vec())?;
let kernel = KernelId::CryptographyNttStageU32;
let buffers = [
BufferBinding::read(current.storage()),
BufferBinding::read(twiddles.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(count / 2),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.length as u32),
PushConstant::U32(span),
PushConstant::U32(modulus as u32),
PushConstant::U32((modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(normalization as u32),
PushConstant::U32((normalization >> 32) as u32),
PushConstant::U32(montgomery),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "span".into(),
value: u64::from(span),
},
OpAttribute::UnsignedInteger {
name: "inverse".into(),
value: 1,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_STAGE,
inputs: &[¤t, twiddles],
outputs: &[&output],
attributes: &attributes,
},
)?;
current = output;
current_is_second = !current_is_second;
}
Ok(current)
}
pub fn pointwise_multiply(
left: &Matrix,
right: &Matrix,
parameters: &NttParameters,
) -> Result<Matrix> {
let config = ¶meters.config;
let scalar = left.shape().len() == 2;
if left.dtype() != DType::U32
|| right.dtype() != DType::U32
|| right.shape() != left.shape()
|| !left.engine_handle().same_as(right.engine_handle())
|| !left
.engine_handle()
.same_as(parameters.forward.engine_handle())
|| (scalar && left.shape()[1] != config.length)
|| (!scalar && (left.shape().len() != 3 || left.shape()[1..] != [config.length, 2]))
{
return Err(Error::invalid_argument(
"NTT pointwise multiplication requires matching-owner U32 rows in one coefficient layout",
));
}
let elements = left.num_elements();
let bytes = elements
.checked_mul(4)
.ok_or_else(|| Error::invalid_argument("NTT byte extent overflows usize"))?;
u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT byte extent exceeds u32"))?;
let count = u32::try_from(elements / if scalar { 1 } else { 2 })
.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
let engine = left.engine_handle();
let output = Matrix::allocate_output(engine, left.shape().to_vec(), elements, DType::U32)?;
if count != 0 && scalar {
if parameters.forward_scalar.is_none() {
return Err(Error::invalid_argument(
"Scalar NTT storage requires a prepared modulus below 2^31",
));
}
let groups = engine.linear_dispatch_grid(count, 128)?;
let kernel = KernelId::CryptographyNttPointwiseScalarU32;
let buffers = [
BufferBinding::read(left.storage()),
BufferBinding::read(right.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.modulus as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(((1_u128 << 64) % u128::from(config.modulus)) as u32),
PushConstant::U32(u32::from(
config.representation == NttRepresentation::Montgomery,
)),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: config.modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(config.representation == NttRepresentation::Montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_POINTWISE,
inputs: &[left, right],
outputs: &[&output],
attributes: &attributes,
},
)?;
return Ok(output);
}
if count != 0 {
let groups = engine.linear_dispatch_grid(count, 128)?;
let kernel = KernelId::CryptographyNttPointwiseU32;
let buffers = [
BufferBinding::read(left.storage()),
BufferBinding::read(right.storage()),
BufferBinding::write(output.storage()),
];
let push_constants = [
PushConstant::U32(count),
PushConstant::U32(groups[0] * 128),
PushConstant::U32(config.modulus as u32),
PushConstant::U32((config.modulus >> 32) as u32),
PushConstant::U32(parameters.negative_inverse),
PushConstant::U32(parameters.r2 as u32),
PushConstant::U32((parameters.r2 >> 32) as u32),
PushConstant::U32(u32::from(
config.representation == NttRepresentation::Montgomery,
)),
];
let attributes = [
OpAttribute::UnsignedInteger {
name: "modulus".into(),
value: config.modulus,
},
OpAttribute::UnsignedInteger {
name: "length".into(),
value: config.length as u64,
},
OpAttribute::UnsignedInteger {
name: "montgomery".into(),
value: u64::from(config.representation == NttRepresentation::Montgomery),
},
];
engine.record_semantic(
ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: groups,
indirect: None,
},
SemanticDispatch {
contract: crate::core::operation::crypto::ntt::NTT_POINTWISE,
inputs: &[left, right],
outputs: &[&output],
attributes: &attributes,
},
)?;
}
Ok(output)
}