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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! FHE Modulus Switching Operation
//!
//! **Purpose**: Reduce ciphertext noise by switching to a smaller modulus
//!
//! **Algorithm**: Scale-and-round modulus reduction
//! - Noise reduction: ~`log(q_old/q_new)` bits
//! - Preserves plaintext (decrypt correctness maintained)
//! - Essential for leveled FHE schemes (BFV, BGV)
//!
//! **Deep Debt Compliance**:
//! - ✅ Pure Rust + WGSL (no unsafe)
//! - ✅ GPU-accelerated via compute shaders
//! - ✅ Numerically precise (exact rounding)
//! - ✅ Production-ready (full error handling)
//!
//! ## Mathematical Background
//!
//! Modulus switching converts a ciphertext under modulus `q_old` to modulus `q_new`:
//! ```text
//! ct_new = round((q_new / q_old) * ct_old) mod q_new
//! ```
//!
//! **Key Properties**:
//! 1. **Correctness**: `Dec(ct_new`, sk, `q_new`) = `Dec(ct_old`, sk, `q_old`)
//! 2. **Noise Reduction**: `noise_new` ≈ `noise_old` * (`q_new` / `q_old`)
//! 3. **Homomorphism**: Can continue operations under `q_new`
//!
//! **Use Cases**:
//! - **Noise Management**: Reduce accumulated noise before overflow
//! - **Leveled FHE**: Enable deeper circuits without bootstrapping
//! - **Bandwidth**: Smaller ciphertexts for network transmission
//!
//! ## Usage Example
//!
//! ```rust,ignore
//! use barracuda::ops::fhe_modulus_switch::FheModulusSwitch;
//! use barracuda::prelude::Tensor;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Ciphertext under large modulus (e.g., after multiplication)
//! let ct = Tensor::from_u64_poly(&ciphertext, degree).await?;
//!
//! // Switch to smaller modulus for noise reduction
//! let q_old = 1152921504606584833u64; // 60-bit prime
//! let q_new = 288230376151711777u64; // 58-bit prime (4x smaller)
//!
//! let switch_op = FheModulusSwitch::new(ct, degree, q_old, q_new)?;
//! let ct_new = switch_op.execute()?;
//!
//! // ct_new has same plaintext, but ~4x less noise
//! # Ok(())
//! # }
//! ```
use crate::device::compute_pipeline::ComputeDispatch;
use crate::error::{BarracudaError, Result};
use crate::tensor::Tensor;
/// FHE Modulus Switching operation
///
/// Scales ciphertext coefficients to smaller modulus while preserving plaintext.
pub struct FheModulusSwitch {
input: Tensor,
degree: u32,
modulus_old: u64,
modulus_new: u64,
}
impl FheModulusSwitch {
/// Create a new modulus switching operation
/// **Parameters**:
/// - `input`: Ciphertext polynomial (2*degree u32 values, u64 emulated)
/// - `degree`: Polynomial degree (power of 2)
/// - `modulus_old`: Current modulus
/// - `modulus_new`: Target modulus (must be < `modulus_old`)
/// **Returns**: `FheModulusSwitch` operation ready to execute
/// **Errors**:
/// - Invalid degree (not power of 2)
/// - `modulus_new` >= `modulus_old`
/// - Input tensor size mismatch
/// # Errors
/// Returns [`Err`] if degree is not a power of 2, `modulus_new` < `modulus_old`,
/// or input size does not match degree.
pub fn new(input: Tensor, degree: u32, modulus_old: u64, modulus_new: u64) -> Result<Self> {
// ✅ VALIDATION: Degree must be power of 2
if !degree.is_power_of_two() || degree < 4 {
return Err(BarracudaError::InvalidInput {
message: format!("Degree must be power of 2 >= 4, got {degree}"),
});
}
// ✅ VALIDATION: New modulus must be smaller
if modulus_new >= modulus_old {
return Err(BarracudaError::InvalidInput {
message: format!(
"New modulus ({modulus_new}) must be < old modulus ({modulus_old})"
),
});
}
// ✅ VALIDATION: Input tensor must be 2*degree (u64 as 2xu32)
let expected_size = (degree * 2) as usize;
if input.shape()[0] != expected_size {
return Err(BarracudaError::InvalidInput {
message: format!(
"Input must have {} elements (degree={}, u64 emulated), got {}",
expected_size,
degree,
input.shape()[0]
),
});
}
Ok(Self {
input,
degree,
modulus_old,
modulus_new,
})
}
/// Execute modulus switching on GPU
/// **Returns**: Tensor with coefficients scaled to new modulus
/// **Performance**: O(n) GPU parallel execution
/// # Errors
/// Returns [`Err`] if buffer allocation, GPU dispatch, or buffer
/// readback fails (e.g. device lost or out of memory).
pub fn execute(self) -> Result<Tensor> {
let device = self.input.device();
// Create output buffer
let output_buffer = device.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("FHE Modulus Switch Output"),
size: self.input.buffer().size(),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct SwitchParams {
degree: u32,
modulus_old_lo: u32,
modulus_old_hi: u32,
modulus_new_lo: u32,
modulus_new_hi: u32,
_padding: [u32; 3],
}
let params = SwitchParams {
degree: self.degree,
modulus_old_lo: (self.modulus_old & 0xFFFF_FFFF) as u32,
modulus_old_hi: (self.modulus_old >> 32) as u32,
modulus_new_lo: (self.modulus_new & 0xFFFF_FFFF) as u32,
modulus_new_hi: (self.modulus_new >> 32) as u32,
_padding: [0; 3],
};
let params_buffer = device.create_uniform_buffer("FHE Modulus Switch Params", ¶ms);
ComputeDispatch::new(device.as_ref(), "FHE Modulus Switch")
.shader(include_str!("fhe_modulus_switch.wgsl"), "modulus_switch")
.storage_read(0, self.input.buffer())
.storage_rw(1, &output_buffer)
.uniform(2, ¶ms_buffer)
.dispatch_1d(self.degree)
.submit()?;
// Return result tensor
Ok(Tensor::from_buffer(
output_buffer,
self.input.shape().to_vec(),
device.clone(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_modulus_switch_validation() {
let device = crate::device::test_pool::get_test_device().await;
let t = || Tensor::zeros_on(vec![8], device.clone());
// Test invalid degree
let result = FheModulusSwitch::new(
t().await.unwrap(),
3, // Not power of 2
12_289,
6145,
);
assert!(result.is_err());
// Test new modulus >= old modulus
let result = FheModulusSwitch::new(
t().await.unwrap(),
4,
12_289,
12_289, // Equal (should fail)
);
assert!(result.is_err());
}
// Full integration tests in tests/fhe_shader_unit_tests.rs
}