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