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 213)
194fn position_encoding_demo() -> Result<()> {
195 println!(" Testing quantum position encoding variants...");
196
197 let encoding_types = vec![
198 ("Sinusoidal", PositionEncodingType::Sinusoidal),
199 ("Quantum Phase", PositionEncodingType::QuantumPhase),
200 ("Learnable Quantum", PositionEncodingType::LearnableQuantum),
201 ("Relative", PositionEncodingType::Relative),
202 ("Rotary (RoPE)", PositionEncodingType::Rotary),
203 ];
204
205 let model_dim = 128;
206 let max_seq_len = 64;
207 let num_qubits = 8;
208
209 for (name, encoding_type) in encoding_types {
210 println!("\n --- {name} Position Encoding ---");
211
212 let pos_enc =
213 QuantumPositionEncoding::new(encoding_type, model_dim, max_seq_len, num_qubits)?;
214
215 let batch_size = 3;
216 let seq_len = 32;
217
218 let encodings = pos_enc.forward(seq_len, batch_size)?;
219 println!(" Encoding shape: {:?}", encodings.dim());
220
221 // Analyze position encoding properties
222 let encoding_range = {
223 let min_val = encodings.iter().copied().fold(f64::INFINITY, f64::min);
224 let max_val = encodings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
225 max_val - min_val
226 };
227
228 println!(" Value range: {encoding_range:.4}");
229
230 // Check position distinguishability
231 let pos1 = encodings
232 .slice(scirs2_core::ndarray::s![0, 0, ..])
233 .to_owned();
234 let pos2 = encodings
235 .slice(scirs2_core::ndarray::s![0, seq_len - 1, ..])
236 .to_owned();
237 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
238
239 println!(" Distance between first and last position: {position_distance:.4}");
240
241 // Analyze periodicity for sinusoidal encodings
242 if name == "Sinusoidal" {
243 let mut periodicities = Vec::new();
244 for d in (0..model_dim).step_by(10) {
245 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
246
247 // Simple periodicity check
248 let period = find_period(&values);
249 if period > 0 {
250 periodicities.push(period);
251 }
252 }
253
254 if !periodicities.is_empty() {
255 let avg_period =
256 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
257 println!(" Average period length: {avg_period:.1}");
258 }
259 }
260
261 // Check quantum phase encoding properties
262 if name == "Quantum Phase" {
263 let phase_variance = encodings.var(0.0);
264 println!(" Phase encoding variance: {phase_variance:.4}");
265 }
266 }
267
268 Ok(())
269}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 218)
194fn position_encoding_demo() -> Result<()> {
195 println!(" Testing quantum position encoding variants...");
196
197 let encoding_types = vec![
198 ("Sinusoidal", PositionEncodingType::Sinusoidal),
199 ("Quantum Phase", PositionEncodingType::QuantumPhase),
200 ("Learnable Quantum", PositionEncodingType::LearnableQuantum),
201 ("Relative", PositionEncodingType::Relative),
202 ("Rotary (RoPE)", PositionEncodingType::Rotary),
203 ];
204
205 let model_dim = 128;
206 let max_seq_len = 64;
207 let num_qubits = 8;
208
209 for (name, encoding_type) in encoding_types {
210 println!("\n --- {name} Position Encoding ---");
211
212 let pos_enc =
213 QuantumPositionEncoding::new(encoding_type, model_dim, max_seq_len, num_qubits)?;
214
215 let batch_size = 3;
216 let seq_len = 32;
217
218 let encodings = pos_enc.forward(seq_len, batch_size)?;
219 println!(" Encoding shape: {:?}", encodings.dim());
220
221 // Analyze position encoding properties
222 let encoding_range = {
223 let min_val = encodings.iter().copied().fold(f64::INFINITY, f64::min);
224 let max_val = encodings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
225 max_val - min_val
226 };
227
228 println!(" Value range: {encoding_range:.4}");
229
230 // Check position distinguishability
231 let pos1 = encodings
232 .slice(scirs2_core::ndarray::s![0, 0, ..])
233 .to_owned();
234 let pos2 = encodings
235 .slice(scirs2_core::ndarray::s![0, seq_len - 1, ..])
236 .to_owned();
237 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
238
239 println!(" Distance between first and last position: {position_distance:.4}");
240
241 // Analyze periodicity for sinusoidal encodings
242 if name == "Sinusoidal" {
243 let mut periodicities = Vec::new();
244 for d in (0..model_dim).step_by(10) {
245 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
246
247 // Simple periodicity check
248 let period = find_period(&values);
249 if period > 0 {
250 periodicities.push(period);
251 }
252 }
253
254 if !periodicities.is_empty() {
255 let avg_period =
256 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
257 println!(" Average period length: {avg_period:.1}");
258 }
259 }
260
261 // Check quantum phase encoding properties
262 if name == "Quantum Phase" {
263 let phase_variance = encodings.var(0.0);
264 println!(" Phase encoding variance: {phase_variance:.4}");
265 }
266 }
267
268 Ok(())
269}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.