pub struct QuantumPositionEncoding { /* private fields */ }Expand description
Quantum position encoding module
Implementations§
Source§impl QuantumPositionEncoding
impl QuantumPositionEncoding
Sourcepub fn new(
encoding_type: PositionEncodingType,
model_dim: usize,
max_seq_len: usize,
num_qubits: usize,
) -> Result<Self>
pub fn new( encoding_type: PositionEncodingType, model_dim: usize, max_seq_len: usize, num_qubits: usize, ) -> Result<Self>
Create new quantum position encoding
Examples found in repository?
examples/quantum_transformer.rs (line 221)
202fn position_encoding_demo() -> Result<()> {
203 println!(" Testing quantum position encoding variants...");
204
205 let encoding_types = vec![
206 ("Sinusoidal", PositionEncodingType::Sinusoidal),
207 ("Quantum Phase", PositionEncodingType::QuantumPhase),
208 ("Learnable Quantum", PositionEncodingType::LearnableQuantum),
209 ("Relative", PositionEncodingType::Relative),
210 ("Rotary (RoPE)", PositionEncodingType::Rotary),
211 ];
212
213 let model_dim = 128;
214 let max_seq_len = 64;
215 let num_qubits = 8;
216
217 for (name, encoding_type) in encoding_types {
218 println!("\n --- {name} Position Encoding ---");
219
220 let pos_enc =
221 QuantumPositionEncoding::new(encoding_type, model_dim, max_seq_len, num_qubits)?;
222
223 let batch_size = 3;
224 let seq_len = 32;
225
226 let encodings = pos_enc.forward(seq_len, batch_size)?;
227 println!(" Encoding shape: {:?}", encodings.dim());
228
229 // Analyze position encoding properties
230 let encoding_range = {
231 let min_val = encodings.iter().copied().fold(f64::INFINITY, f64::min);
232 let max_val = encodings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
233 max_val - min_val
234 };
235
236 println!(" Value range: {encoding_range:.4}");
237
238 // Check position distinguishability
239 let pos1 = encodings
240 .slice(scirs2_core::ndarray::s![0, 0, ..])
241 .to_owned();
242 let pos2 = encodings
243 .slice(scirs2_core::ndarray::s![0, seq_len - 1, ..])
244 .to_owned();
245 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
246
247 println!(" Distance between first and last position: {position_distance:.4}");
248
249 // Analyze periodicity for sinusoidal encodings
250 if name == "Sinusoidal" {
251 let mut periodicities = Vec::new();
252 for d in (0..model_dim).step_by(10) {
253 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
254
255 // Simple periodicity check
256 let period = find_period(&values);
257 if period > 0 {
258 periodicities.push(period);
259 }
260 }
261
262 if !periodicities.is_empty() {
263 let avg_period =
264 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
265 println!(" Average period length: {avg_period:.1}");
266 }
267 }
268
269 // Check quantum phase encoding properties
270 if name == "Quantum Phase" {
271 let phase_variance = encodings.var(0.0);
272 println!(" Phase encoding variance: {phase_variance:.4}");
273 }
274 }
275
276 Ok(())
277}Sourcepub fn forward(&self, seq_len: usize, batch_size: usize) -> Result<Array3<f64>>
pub fn forward(&self, seq_len: usize, batch_size: usize) -> Result<Array3<f64>>
Generate position encodings for input sequence
Examples found in repository?
examples/quantum_transformer.rs (line 226)
202fn position_encoding_demo() -> Result<()> {
203 println!(" Testing quantum position encoding variants...");
204
205 let encoding_types = vec![
206 ("Sinusoidal", PositionEncodingType::Sinusoidal),
207 ("Quantum Phase", PositionEncodingType::QuantumPhase),
208 ("Learnable Quantum", PositionEncodingType::LearnableQuantum),
209 ("Relative", PositionEncodingType::Relative),
210 ("Rotary (RoPE)", PositionEncodingType::Rotary),
211 ];
212
213 let model_dim = 128;
214 let max_seq_len = 64;
215 let num_qubits = 8;
216
217 for (name, encoding_type) in encoding_types {
218 println!("\n --- {name} Position Encoding ---");
219
220 let pos_enc =
221 QuantumPositionEncoding::new(encoding_type, model_dim, max_seq_len, num_qubits)?;
222
223 let batch_size = 3;
224 let seq_len = 32;
225
226 let encodings = pos_enc.forward(seq_len, batch_size)?;
227 println!(" Encoding shape: {:?}", encodings.dim());
228
229 // Analyze position encoding properties
230 let encoding_range = {
231 let min_val = encodings.iter().copied().fold(f64::INFINITY, f64::min);
232 let max_val = encodings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
233 max_val - min_val
234 };
235
236 println!(" Value range: {encoding_range:.4}");
237
238 // Check position distinguishability
239 let pos1 = encodings
240 .slice(scirs2_core::ndarray::s![0, 0, ..])
241 .to_owned();
242 let pos2 = encodings
243 .slice(scirs2_core::ndarray::s![0, seq_len - 1, ..])
244 .to_owned();
245 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
246
247 println!(" Distance between first and last position: {position_distance:.4}");
248
249 // Analyze periodicity for sinusoidal encodings
250 if name == "Sinusoidal" {
251 let mut periodicities = Vec::new();
252 for d in (0..model_dim).step_by(10) {
253 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
254
255 // Simple periodicity check
256 let period = find_period(&values);
257 if period > 0 {
258 periodicities.push(period);
259 }
260 }
261
262 if !periodicities.is_empty() {
263 let avg_period =
264 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
265 println!(" Average period length: {avg_period:.1}");
266 }
267 }
268
269 // Check quantum phase encoding properties
270 if name == "Quantum Phase" {
271 let phase_variance = encodings.var(0.0);
272 println!(" Phase encoding variance: {phase_variance:.4}");
273 }
274 }
275
276 Ok(())
277}Trait Implementations§
Source§impl Clone for QuantumPositionEncoding
impl Clone for QuantumPositionEncoding
Source§fn clone(&self) -> QuantumPositionEncoding
fn clone(&self) -> QuantumPositionEncoding
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreAuto Trait Implementations§
impl Freeze for QuantumPositionEncoding
impl !RefUnwindSafe for QuantumPositionEncoding
impl Send for QuantumPositionEncoding
impl Sync for QuantumPositionEncoding
impl Unpin for QuantumPositionEncoding
impl !UnwindSafe for QuantumPositionEncoding
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
The inverse inclusion map: attempts to construct
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
Checks if
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
Use with care! Same as
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
The inclusion map: converts
self to the equivalent element of its superset.