pub struct QuantumTransformer { /* private fields */ }
Expand description
Main quantum transformer model
Implementations§
Source§impl QuantumTransformer
impl QuantumTransformer
Sourcepub fn new(config: QuantumTransformerConfig) -> Result<Self>
pub fn new(config: QuantumTransformerConfig) -> Result<Self>
Create new quantum transformer model
Examples found in repository?
examples/quantum_transformer.rs (line 96)
53fn config_demo() -> Result<()> {
54 println!(" Creating various transformer configurations...");
55
56 // Small efficient model
57 let small_config = QuantumTransformerConfig::small();
58 println!(
59 " Small model: {} params, {} heads, {} layers",
60 small_config.model_dim, small_config.num_heads, small_config.num_layers
61 );
62
63 // Standard model
64 let default_config = QuantumTransformerConfig::default();
65 println!(
66 " Default model: {} params, {} heads, {} layers",
67 default_config.model_dim, default_config.num_heads, default_config.num_layers
68 );
69
70 // Large model
71 let large_config = QuantumTransformerConfig::large();
72 println!(
73 " Large model: {} params, {} heads, {} layers",
74 large_config.model_dim, large_config.num_heads, large_config.num_layers
75 );
76
77 // Custom configuration
78 let custom_config = QuantumTransformerConfig {
79 model_dim: 384,
80 num_heads: 6,
81 ff_dim: 1536,
82 num_layers: 8,
83 max_seq_len: 1024,
84 num_qubits: 12,
85 dropout_rate: 0.15,
86 attention_type: QuantumAttentionType::QuantumEnhancedMultiHead,
87 position_encoding: PositionEncodingType::Rotary,
88 };
89
90 println!(
91 " Custom model: {} dim, {} qubits, {:?} attention",
92 custom_config.model_dim, custom_config.num_qubits, custom_config.attention_type
93 );
94
95 // Create transformer with custom config
96 let transformer = QuantumTransformer::new(custom_config)?;
97 println!(
98 " Created transformer with {} total parameters",
99 transformer.num_parameters()
100 );
101
102 Ok(())
103}
104
105/// Demonstrate different quantum attention mechanisms
106fn attention_mechanisms_demo() -> Result<()> {
107 println!(" Testing various quantum attention mechanisms...");
108
109 let attention_types = vec![
110 ("Full Quantum", QuantumAttentionType::FullQuantum),
111 (
112 "Hybrid Quantum-Classical",
113 QuantumAttentionType::HybridQuantumClassical,
114 ),
115 (
116 "Variational Quantum",
117 QuantumAttentionType::VariationalQuantum,
118 ),
119 (
120 "Quantum Enhanced Multi-Head",
121 QuantumAttentionType::QuantumEnhancedMultiHead,
122 ),
123 (
124 "Quantum Self-Attention",
125 QuantumAttentionType::QuantumSelfAttention,
126 ),
127 ];
128
129 for (name, attention_type) in attention_types {
130 println!("\n --- {} Attention ---", name);
131
132 let attention = QuantumMultiHeadAttention::new(4, 256, attention_type, 8)?;
133 println!(
134 " Created attention module: {} heads, {} model dim",
135 4, 256
136 ); // Fixed values since fields are private
137
138 // Test forward pass
139 let batch_size = 2;
140 let seq_len = 10;
141 let model_dim = 256;
142
143 let query = Array3::from_shape_fn((batch_size, seq_len, model_dim), |(b, s, d)| {
144 0.1 * (b as f64 + s as f64 * 0.1 + d as f64 * 0.01)
145 });
146 let key = query.clone();
147 let value = query.clone();
148
149 let attention_output = attention.forward(&query, &key, &value, None)?;
150
151 println!(
152 " Attention output shape: {:?}",
153 attention_output.output.dim()
154 );
155 println!(
156 " Attention weights shape: {:?}",
157 attention_output.attention_weights.dim()
158 );
159
160 // Analyze quantum attention properties
161 let quantum_info = &attention_output.quantum_info;
162 let avg_entanglement = quantum_info.entanglement_matrix.mean().unwrap_or(0.0);
163 let max_coherence = quantum_info
164 .coherence_scores
165 .iter()
166 .cloned()
167 .fold(f64::NEG_INFINITY, f64::max);
168
169 println!(" Average entanglement: {:.4}", avg_entanglement);
170 println!(" Maximum coherence: {:.4}", max_coherence);
171
172 // Attention pattern analysis
173 let attention_weights = &attention_output.attention_weights;
174 let max_attention = attention_weights
175 .iter()
176 .cloned()
177 .fold(f64::NEG_INFINITY, f64::max);
178 let avg_attention = attention_weights.mean().unwrap_or(0.0);
179
180 println!(" Max attention weight: {:.4}", max_attention);
181 println!(" Average attention: {:.4}", avg_attention);
182
183 // Check attention sparsity
184 let sparsity = attention_weights.iter().filter(|&&x| x < 0.01).count() as f64
185 / attention_weights.len() as f64;
186 println!(" Attention sparsity: {:.1}%", sparsity * 100.0);
187 }
188
189 Ok(())
190}
191
192/// Demonstrate different position encoding types
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 --- {} Position Encoding ---", name);
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().cloned().fold(f64::INFINITY, f64::min);
223 let max_val = encodings.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
224 max_val - min_val
225 };
226
227 println!(" Value range: {:.4}", encoding_range);
228
229 // Check position distinguishability
230 let pos1 = encodings.slice(scirs2_core::ndarray::s![0, 0, ..]).to_owned();
231 let pos2 = encodings.slice(scirs2_core::ndarray::s![0, seq_len - 1, ..]).to_owned();
232 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
233
234 println!(
235 " Distance between first and last position: {:.4}",
236 position_distance
237 );
238
239 // Analyze periodicity for sinusoidal encodings
240 if name == "Sinusoidal" {
241 let mut periodicities = Vec::new();
242 for d in (0..model_dim).step_by(10) {
243 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
244
245 // Simple periodicity check
246 let period = find_period(&values);
247 if period > 0 {
248 periodicities.push(period);
249 }
250 }
251
252 if !periodicities.is_empty() {
253 let avg_period =
254 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
255 println!(" Average period length: {:.1}", avg_period);
256 }
257 }
258
259 // Check quantum phase encoding properties
260 if name == "Quantum Phase" {
261 let phase_variance = encodings.var(0.0);
262 println!(" Phase encoding variance: {:.4}", phase_variance);
263 }
264 }
265
266 Ok(())
267}
268
269/// Demonstrate complete transformer forward pass
270fn transformer_forward_demo() -> Result<()> {
271 println!(" Testing complete quantum transformer forward pass...");
272
273 let config = QuantumTransformerConfig {
274 model_dim: 256,
275 num_heads: 8,
276 ff_dim: 1024,
277 num_layers: 4,
278 max_seq_len: 128,
279 num_qubits: 10,
280 dropout_rate: 0.1,
281 attention_type: QuantumAttentionType::HybridQuantumClassical,
282 position_encoding: PositionEncodingType::QuantumPhase,
283 };
284
285 let transformer = QuantumTransformer::new(config.clone())?;
286 println!(
287 " Created transformer: {} layers, {} parameters",
288 config.num_layers,
289 transformer.num_parameters()
290 );
291
292 // Test with different sequence lengths
293 let test_sequences = vec![
294 (2, 16, 128), // small batch, short sequence
295 (4, 32, 128), // medium batch, medium sequence
296 (1, 64, 128), // single sample, long sequence
297 ];
298
299 for (batch_size, seq_len, input_dim) in test_sequences {
300 println!(
301 "\n Testing: batch={}, seq_len={}, input_dim={}",
302 batch_size, seq_len, input_dim
303 );
304
305 // Create test input
306 let input = Array3::from_shape_fn((batch_size, seq_len, input_dim), |(b, s, d)| {
307 let base = 0.1 * (b as f64 + 1.0);
308 let seq_component = 0.05 * (s as f64 * 0.1).sin();
309 let dim_component = 0.02 * (d as f64 * 0.01).cos();
310 base + seq_component + dim_component
311 });
312
313 // Create causal mask for autoregressive modeling
314 let causal_mask = create_causal_mask(batch_size, seq_len);
315
316 // Forward pass
317 let start_time = std::time::Instant::now();
318 let output = transformer.forward(&input, Some(&causal_mask))?;
319 let forward_time = start_time.elapsed();
320
321 println!(" Output shape: {:?}", output.dim());
322 println!(" Forward pass time: {:.2?}", forward_time);
323
324 // Analyze output properties
325 let output_mean = output.mean().unwrap_or(0.0);
326 let output_std = output.var(0.0).sqrt();
327 let output_range = {
328 let min_val = output.iter().cloned().fold(f64::INFINITY, f64::min);
329 let max_val = output.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
330 max_val - min_val
331 };
332
333 println!(
334 " Output statistics: mean={:.4}, std={:.4}, range={:.4}",
335 output_mean, output_std, output_range
336 );
337
338 // Check causality (if using causal mask)
339 let causality_check = check_causality(&input, &output, &causal_mask);
340 if causality_check {
341 println!(" ✓ Causal dependencies respected");
342 } else {
343 println!(" ⚠ Potential causality violations detected");
344 }
345
346 // Memory efficiency analysis
347 let memory_per_token = (transformer.num_parameters() * 8 + output.len() * 8) as f64
348 / (batch_size * seq_len) as f64;
349 println!(" Memory per token: {:.1} bytes", memory_per_token);
350 }
351
352 Ok(())
353}
354
355/// Demonstrate quantum language modeling
356fn language_modeling_demo() -> Result<()> {
357 println!(" Quantum language modeling with transformer...");
358
359 let config = QuantumTransformerConfig {
360 model_dim: 384,
361 num_heads: 6,
362 ff_dim: 1536,
363 num_layers: 6,
364 max_seq_len: 256,
365 num_qubits: 12,
366 dropout_rate: 0.1,
367 attention_type: QuantumAttentionType::QuantumSelfAttention,
368 position_encoding: PositionEncodingType::Rotary,
369 };
370
371 let transformer = QuantumTransformer::new(config.clone())?;
372
373 // Simulate language modeling task
374 let vocab_size = 1000;
375 let batch_size = 4;
376 let seq_len = 64;
377
378 // Create tokenized sequences (simulated)
379 let input_tokens =
380 Array3::from_shape_fn((batch_size, seq_len, config.model_dim), |(b, s, d)| {
381 // Simulate token embeddings
382 let token_id = (b * seq_len + s) % vocab_size;
383 let embedding_val = (token_id as f64 / vocab_size as f64) * 2.0 - 1.0;
384 embedding_val * (1.0 + 0.1 * (d as f64 / config.model_dim as f64))
385 });
386
387 println!(
388 " Processing {} sequences of length {}",
389 batch_size, seq_len
390 );
391
392 // Create causal mask for language modeling
393 let causal_mask = create_causal_mask(batch_size, seq_len);
394
395 // Forward pass
396 let logits = transformer.forward(&input_tokens, Some(&causal_mask))?;
397
398 // Simulate next token prediction
399 let mut perplexities = Vec::new();
400
401 for batch_idx in 0..batch_size {
402 let mut log_likelihood = 0.0;
403 let mut valid_predictions = 0;
404
405 for pos in 0..seq_len - 1 {
406 let current_logits = logits.slice(scirs2_core::ndarray::s![batch_idx, pos, ..]);
407
408 // Convert to probabilities (simplified softmax)
409 let max_logit = current_logits
410 .iter()
411 .cloned()
412 .fold(f64::NEG_INFINITY, f64::max);
413 let exp_logits: Array1<f64> = current_logits.mapv(|x| (x - max_logit).exp());
414 let sum_exp = exp_logits.sum();
415 let probs = exp_logits / sum_exp;
416
417 // Simulate target token (next position embedding)
418 let target_embedding = input_tokens.slice(scirs2_core::ndarray::s![batch_idx, pos + 1, ..]);
419 let target_prob = compute_token_probability(&probs, &target_embedding.to_owned())?;
420
421 if target_prob > 1e-10 {
422 log_likelihood += target_prob.ln();
423 valid_predictions += 1;
424 }
425 }
426
427 if valid_predictions > 0 {
428 let avg_log_likelihood = log_likelihood / valid_predictions as f64;
429 let perplexity = (-avg_log_likelihood).exp();
430 perplexities.push(perplexity);
431 }
432 }
433
434 if !perplexities.is_empty() {
435 let avg_perplexity = perplexities.iter().sum::<f64>() / perplexities.len() as f64;
436 println!(" Average perplexity: {:.2}", avg_perplexity);
437
438 // Analyze quantum language model properties
439 println!(" Quantum language model analysis:");
440
441 // Attention pattern analysis
442 println!(" - Uses quantum self-attention for context modeling");
443 println!(" - Rotary position encoding preserves relative positions");
444 println!(
445 " - {} layers provide hierarchical representation",
446 config.num_layers
447 );
448
449 // Information flow analysis
450 let first_layer_norm = logits.slice(scirs2_core::ndarray::s![0, .., ..]).var(0.0).sqrt();
451 println!(
452 " - Output layer standard deviation: {:.4}",
453 first_layer_norm
454 );
455
456 // Quantum coherence in language representation
457 let quantum_coherence = analyze_quantum_language_coherence(&logits)?;
458 println!(
459 " - Quantum coherence in representations: {:.4}",
460 quantum_coherence
461 );
462 }
463
464 Ok(())
465}
466
467/// Demonstrate sequence-to-sequence tasks
468fn seq2seq_demo() -> Result<()> {
469 println!(" Quantum sequence-to-sequence modeling...");
470
471 // Encoder configuration
472 let encoder_config = QuantumTransformerConfig {
473 model_dim: 256,
474 num_heads: 8,
475 ff_dim: 1024,
476 num_layers: 4,
477 max_seq_len: 128,
478 num_qubits: 10,
479 dropout_rate: 0.1,
480 attention_type: QuantumAttentionType::HybridQuantumClassical,
481 position_encoding: PositionEncodingType::Sinusoidal,
482 };
483
484 // Decoder configuration (with causal attention)
485 let decoder_config = QuantumTransformerConfig {
486 model_dim: 256,
487 num_heads: 8,
488 ff_dim: 1024,
489 num_layers: 4,
490 max_seq_len: 128,
491 num_qubits: 10,
492 dropout_rate: 0.1,
493 attention_type: QuantumAttentionType::QuantumEnhancedMultiHead,
494 position_encoding: PositionEncodingType::QuantumPhase,
495 };
496
497 let encoder = QuantumTransformer::new(encoder_config)?;
498 let decoder = QuantumTransformer::new(decoder_config)?;
499
500 println!(" Created encoder-decoder architecture");
501 println!(" Encoder: {} parameters", encoder.num_parameters());
502 println!(" Decoder: {} parameters", decoder.num_parameters());
503
504 // Simulate translation task
505 let batch_size = 3;
506 let src_len = 32;
507 let tgt_len = 28;
508 let model_dim = 256;
509
510 // Source sequence (e.g., English)
511 let source = Array3::from_shape_fn((batch_size, src_len, model_dim), |(b, s, d)| {
512 let src_pattern = 0.3 * ((s as f64 * 0.2 + b as f64).sin());
513 src_pattern + 0.1 * (d as f64 / model_dim as f64)
514 });
515
516 // Target sequence (e.g., French)
517 let target = Array3::from_shape_fn((batch_size, tgt_len, model_dim), |(b, s, d)| {
518 let tgt_pattern = 0.4 * ((s as f64 * 0.15 + b as f64 * 0.3).cos());
519 tgt_pattern + 0.12 * (d as f64 / model_dim as f64)
520 });
521
522 println!(
523 "\n Processing translation: {} -> {} tokens",
524 src_len, tgt_len
525 );
526
527 // Encode source sequence
528 let encoder_output = encoder.forward(&source, None)?;
529 println!(" Encoder output shape: {:?}", encoder_output.dim());
530
531 // Decode with causal mask
532 let causal_mask = create_causal_mask(batch_size, tgt_len);
533 let decoder_output = decoder.forward(&target, Some(&causal_mask))?;
534 println!(" Decoder output shape: {:?}", decoder_output.dim());
535
536 // Cross-attention simulation (simplified)
537 println!("\n Cross-attention analysis:");
538 let cross_attention_scores = compute_cross_attention(&encoder_output, &decoder_output)?;
539 println!(
540 " Cross-attention shape: {:?}",
541 cross_attention_scores.dim()
542 );
543
544 // Analyze attention alignment
545 let max_alignment = cross_attention_scores
546 .iter()
547 .cloned()
548 .fold(f64::NEG_INFINITY, f64::max);
549 let avg_alignment = cross_attention_scores.mean().unwrap_or(0.0);
550
551 println!(" Max alignment score: {:.4}", max_alignment);
552 println!(" Average alignment: {:.4}", avg_alignment);
553
554 // Translation quality metrics (simplified)
555 let translation_score = evaluate_translation_quality(&source, &target, &decoder_output)?;
556 println!(" Translation quality score: {:.4}", translation_score);
557
558 // Quantum entanglement in cross-lingual representations
559 let cross_lingual_entanglement =
560 analyze_cross_lingual_entanglement(&encoder_output, &decoder_output)?;
561 println!(
562 " Cross-lingual quantum entanglement: {:.4}",
563 cross_lingual_entanglement
564 );
565
566 Ok(())
567}
568
569/// Demonstrate quantum data processing
570fn quantum_data_demo() -> Result<()> {
571 println!(" Processing quantum measurement data with transformers...");
572
573 let config = QuantumTransformerConfig {
574 model_dim: 128,
575 num_heads: 4,
576 ff_dim: 512,
577 num_layers: 3,
578 max_seq_len: 64,
579 num_qubits: 8,
580 dropout_rate: 0.05,
581 attention_type: QuantumAttentionType::FullQuantum,
582 position_encoding: PositionEncodingType::QuantumPhase,
583 };
584
585 let transformer = QuantumTransformer::new(config)?;
586
587 // Simulate quantum measurement sequences
588 let batch_size = 5;
589 let seq_len = 32;
590 let model_dim = 128;
591
592 println!(" Generating quantum measurement sequences...");
593
594 // Create quantum state evolution data
595 let quantum_data = Array3::from_shape_fn((batch_size, seq_len, model_dim), |(b, t, d)| {
596 // Simulate quantum state evolution with decoherence
597 let decoherence_factor = (-0.1 * t as f64).exp();
598 let quantum_amplitude =
599 decoherence_factor * (2.0 * std::f64::consts::PI * t as f64 / 8.0 + b as f64).sin();
600
601 // Add measurement noise
602 let noise = 0.05 * (fastrand::f64() - 0.5);
603
604 // Encode as amplitude and phase information
605 if d % 2 == 0 {
606 quantum_amplitude + noise
607 } else {
608 (2.0 * std::f64::consts::PI * t as f64 / 10.0 + d as f64 * 0.1).cos() + noise
609 }
610 });
611
612 println!(
613 " Processing {} quantum sequences of {} measurements each",
614 batch_size, seq_len
615 );
616
617 // Process quantum data
618 let output = transformer.forward(&quantum_data, None)?;
619
620 // Analyze quantum data processing
621 println!("\n Quantum data analysis:");
622
623 // Coherence preservation
624 let input_coherence = compute_coherence_measure(&quantum_data)?;
625 let output_coherence = compute_coherence_measure(&output)?;
626 let coherence_preservation = output_coherence / input_coherence;
627
628 println!(" Input coherence: {:.4}", input_coherence);
629 println!(" Output coherence: {:.4}", output_coherence);
630 println!(
631 " Coherence preservation: {:.1}%",
632 coherence_preservation * 100.0
633 );
634
635 // Quantum information extraction
636 let quantum_features = extract_quantum_features(&output)?;
637 println!(" Extracted quantum features:");
638 println!(
639 " - Entanglement signature: {:.4}",
640 quantum_features.entanglement
641 );
642 println!(
643 " - Phase coherence: {:.4}",
644 quantum_features.phase_coherence
645 );
646 println!(
647 " - Amplitude stability: {:.4}",
648 quantum_features.amplitude_stability
649 );
650
651 // Decoherence detection
652 let decoherence_pattern = detect_decoherence_pattern(&output)?;
653 println!(" Decoherence detection:");
654 println!(" - Pattern strength: {:.4}", decoherence_pattern.strength);
655 println!(
656 " - Time constant: {:.2} steps",
657 decoherence_pattern.time_constant
658 );
659
660 // Quantum state classification
661 let state_classifications = classify_quantum_states(&output)?;
662 println!(" Quantum state classification:");
663 for (i, classification) in state_classifications.iter().enumerate() {
664 println!(
665 " - Sequence {}: {:.1}% entangled, {:.1}% coherent",
666 i,
667 classification.entangled_prob * 100.0,
668 classification.coherent_prob * 100.0
669 );
670 }
671
672 Ok(())
673}
674
675/// Demonstrate multi-scale quantum transformers
676fn multiscale_demo() -> Result<()> {
677 println!(" Multi-scale quantum transformer architecture...");
678
679 // Create transformers at different scales
680 let scales = vec![
681 (
682 "Fine-scale",
683 QuantumTransformerConfig {
684 model_dim: 128,
685 num_heads: 4,
686 ff_dim: 512,
687 num_layers: 2,
688 max_seq_len: 64,
689 num_qubits: 6,
690 dropout_rate: 0.1,
691 attention_type: QuantumAttentionType::VariationalQuantum,
692 position_encoding: PositionEncodingType::Sinusoidal,
693 },
694 ),
695 (
696 "Medium-scale",
697 QuantumTransformerConfig {
698 model_dim: 256,
699 num_heads: 8,
700 ff_dim: 1024,
701 num_layers: 4,
702 max_seq_len: 128,
703 num_qubits: 10,
704 dropout_rate: 0.1,
705 attention_type: QuantumAttentionType::HybridQuantumClassical,
706 position_encoding: PositionEncodingType::QuantumPhase,
707 },
708 ),
709 (
710 "Coarse-scale",
711 QuantumTransformerConfig {
712 model_dim: 512,
713 num_heads: 16,
714 ff_dim: 2048,
715 num_layers: 6,
716 max_seq_len: 256,
717 num_qubits: 16,
718 dropout_rate: 0.1,
719 attention_type: QuantumAttentionType::FullQuantum,
720 position_encoding: PositionEncodingType::Rotary,
721 },
722 ),
723 ];
724
725 let mut transformers = Vec::new();
726
727 for (scale_name, config) in scales {
728 let transformer = QuantumTransformer::new(config)?;
729 let num_params = transformer.num_parameters();
730
731 println!(" {} transformer: {} parameters", scale_name, num_params);
732 transformers.push((scale_name, transformer));
733 }
734
735 // Test hierarchical processing
736 println!("\n Hierarchical processing demonstration:");
737
738 let batch_size = 2;
739 let base_seq_len = 64;
740 let input_dim = 128;
741
742 // Create input data
743 let input_data = Array3::from_shape_fn((batch_size, base_seq_len, input_dim), |(b, s, d)| {
744 // Multi-scale signal with different frequency components
745 let fine_component = 0.3 * (s as f64 * 0.5).sin();
746 let medium_component = 0.2 * (s as f64 * 0.1).sin();
747 let coarse_component = 0.1 * (s as f64 * 0.02).sin();
748
749 let base_signal = fine_component + medium_component + coarse_component;
750 base_signal + 0.05 * (b as f64 + d as f64 * 0.01)
751 });
752
753 // Process at each scale
754 let mut scale_outputs = Vec::new();
755
756 for (scale_name, transformer) in &transformers {
757 // Adapt input to transformer's expected dimensions
758 let adapted_input = adapt_input_for_scale(&input_data, transformer.config())?;
759
760 println!(" Processing at {} scale...", scale_name);
761 println!(" Adapted input shape: {:?}", adapted_input.dim());
762
763 let output = transformer.forward(&adapted_input, None)?;
764
765 // Analyze scale-specific patterns
766 let pattern_analysis = analyze_scale_patterns(&output)?;
767
768 scale_outputs.push((*scale_name, output));
769 println!(" Pattern analysis:");
770 println!(
771 " - Local patterns: {:.4}",
772 pattern_analysis.local_strength
773 );
774 println!(
775 " - Global patterns: {:.4}",
776 pattern_analysis.global_strength
777 );
778 println!(
779 " - Cross-scale coherence: {:.4}",
780 pattern_analysis.coherence
781 );
782 }
783
784 // Multi-scale fusion
785 println!("\n Multi-scale fusion analysis:");
786 let scale_refs: Vec<(&str, Array3<f64>)> = scale_outputs
787 .iter()
788 .map(|(name, output)| (*name, output.clone()))
789 .collect();
790 let fusion_result = fuse_multiscale_outputs(&scale_refs)?;
791 println!(
792 " Fused representation dimensions: {} features",
793 fusion_result.len()
794 );
795
796 let fusion_quality = evaluate_fusion_quality(&fusion_result)?;
797 println!(" Fusion quality metrics:");
798 println!(
799 " - Information preservation: {:.1}%",
800 fusion_quality.info_preservation * 100.0
801 );
802 println!(
803 " - Scale consistency: {:.1}%",
804 fusion_quality.scale_consistency * 100.0
805 );
806 println!(
807 " - Quantum coherence: {:.4}",
808 fusion_quality.quantum_coherence
809 );
810
811 Ok(())
812}
Sourcepub fn forward(
&self,
input: &Array3<f64>,
attention_mask: Option<&Array3<bool>>,
) -> Result<Array3<f64>>
pub fn forward( &self, input: &Array3<f64>, attention_mask: Option<&Array3<bool>>, ) -> Result<Array3<f64>>
Forward pass through quantum transformer
Examples found in repository?
examples/quantum_transformer.rs (line 318)
270fn transformer_forward_demo() -> Result<()> {
271 println!(" Testing complete quantum transformer forward pass...");
272
273 let config = QuantumTransformerConfig {
274 model_dim: 256,
275 num_heads: 8,
276 ff_dim: 1024,
277 num_layers: 4,
278 max_seq_len: 128,
279 num_qubits: 10,
280 dropout_rate: 0.1,
281 attention_type: QuantumAttentionType::HybridQuantumClassical,
282 position_encoding: PositionEncodingType::QuantumPhase,
283 };
284
285 let transformer = QuantumTransformer::new(config.clone())?;
286 println!(
287 " Created transformer: {} layers, {} parameters",
288 config.num_layers,
289 transformer.num_parameters()
290 );
291
292 // Test with different sequence lengths
293 let test_sequences = vec![
294 (2, 16, 128), // small batch, short sequence
295 (4, 32, 128), // medium batch, medium sequence
296 (1, 64, 128), // single sample, long sequence
297 ];
298
299 for (batch_size, seq_len, input_dim) in test_sequences {
300 println!(
301 "\n Testing: batch={}, seq_len={}, input_dim={}",
302 batch_size, seq_len, input_dim
303 );
304
305 // Create test input
306 let input = Array3::from_shape_fn((batch_size, seq_len, input_dim), |(b, s, d)| {
307 let base = 0.1 * (b as f64 + 1.0);
308 let seq_component = 0.05 * (s as f64 * 0.1).sin();
309 let dim_component = 0.02 * (d as f64 * 0.01).cos();
310 base + seq_component + dim_component
311 });
312
313 // Create causal mask for autoregressive modeling
314 let causal_mask = create_causal_mask(batch_size, seq_len);
315
316 // Forward pass
317 let start_time = std::time::Instant::now();
318 let output = transformer.forward(&input, Some(&causal_mask))?;
319 let forward_time = start_time.elapsed();
320
321 println!(" Output shape: {:?}", output.dim());
322 println!(" Forward pass time: {:.2?}", forward_time);
323
324 // Analyze output properties
325 let output_mean = output.mean().unwrap_or(0.0);
326 let output_std = output.var(0.0).sqrt();
327 let output_range = {
328 let min_val = output.iter().cloned().fold(f64::INFINITY, f64::min);
329 let max_val = output.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
330 max_val - min_val
331 };
332
333 println!(
334 " Output statistics: mean={:.4}, std={:.4}, range={:.4}",
335 output_mean, output_std, output_range
336 );
337
338 // Check causality (if using causal mask)
339 let causality_check = check_causality(&input, &output, &causal_mask);
340 if causality_check {
341 println!(" ✓ Causal dependencies respected");
342 } else {
343 println!(" ⚠ Potential causality violations detected");
344 }
345
346 // Memory efficiency analysis
347 let memory_per_token = (transformer.num_parameters() * 8 + output.len() * 8) as f64
348 / (batch_size * seq_len) as f64;
349 println!(" Memory per token: {:.1} bytes", memory_per_token);
350 }
351
352 Ok(())
353}
354
355/// Demonstrate quantum language modeling
356fn language_modeling_demo() -> Result<()> {
357 println!(" Quantum language modeling with transformer...");
358
359 let config = QuantumTransformerConfig {
360 model_dim: 384,
361 num_heads: 6,
362 ff_dim: 1536,
363 num_layers: 6,
364 max_seq_len: 256,
365 num_qubits: 12,
366 dropout_rate: 0.1,
367 attention_type: QuantumAttentionType::QuantumSelfAttention,
368 position_encoding: PositionEncodingType::Rotary,
369 };
370
371 let transformer = QuantumTransformer::new(config.clone())?;
372
373 // Simulate language modeling task
374 let vocab_size = 1000;
375 let batch_size = 4;
376 let seq_len = 64;
377
378 // Create tokenized sequences (simulated)
379 let input_tokens =
380 Array3::from_shape_fn((batch_size, seq_len, config.model_dim), |(b, s, d)| {
381 // Simulate token embeddings
382 let token_id = (b * seq_len + s) % vocab_size;
383 let embedding_val = (token_id as f64 / vocab_size as f64) * 2.0 - 1.0;
384 embedding_val * (1.0 + 0.1 * (d as f64 / config.model_dim as f64))
385 });
386
387 println!(
388 " Processing {} sequences of length {}",
389 batch_size, seq_len
390 );
391
392 // Create causal mask for language modeling
393 let causal_mask = create_causal_mask(batch_size, seq_len);
394
395 // Forward pass
396 let logits = transformer.forward(&input_tokens, Some(&causal_mask))?;
397
398 // Simulate next token prediction
399 let mut perplexities = Vec::new();
400
401 for batch_idx in 0..batch_size {
402 let mut log_likelihood = 0.0;
403 let mut valid_predictions = 0;
404
405 for pos in 0..seq_len - 1 {
406 let current_logits = logits.slice(scirs2_core::ndarray::s![batch_idx, pos, ..]);
407
408 // Convert to probabilities (simplified softmax)
409 let max_logit = current_logits
410 .iter()
411 .cloned()
412 .fold(f64::NEG_INFINITY, f64::max);
413 let exp_logits: Array1<f64> = current_logits.mapv(|x| (x - max_logit).exp());
414 let sum_exp = exp_logits.sum();
415 let probs = exp_logits / sum_exp;
416
417 // Simulate target token (next position embedding)
418 let target_embedding = input_tokens.slice(scirs2_core::ndarray::s![batch_idx, pos + 1, ..]);
419 let target_prob = compute_token_probability(&probs, &target_embedding.to_owned())?;
420
421 if target_prob > 1e-10 {
422 log_likelihood += target_prob.ln();
423 valid_predictions += 1;
424 }
425 }
426
427 if valid_predictions > 0 {
428 let avg_log_likelihood = log_likelihood / valid_predictions as f64;
429 let perplexity = (-avg_log_likelihood).exp();
430 perplexities.push(perplexity);
431 }
432 }
433
434 if !perplexities.is_empty() {
435 let avg_perplexity = perplexities.iter().sum::<f64>() / perplexities.len() as f64;
436 println!(" Average perplexity: {:.2}", avg_perplexity);
437
438 // Analyze quantum language model properties
439 println!(" Quantum language model analysis:");
440
441 // Attention pattern analysis
442 println!(" - Uses quantum self-attention for context modeling");
443 println!(" - Rotary position encoding preserves relative positions");
444 println!(
445 " - {} layers provide hierarchical representation",
446 config.num_layers
447 );
448
449 // Information flow analysis
450 let first_layer_norm = logits.slice(scirs2_core::ndarray::s![0, .., ..]).var(0.0).sqrt();
451 println!(
452 " - Output layer standard deviation: {:.4}",
453 first_layer_norm
454 );
455
456 // Quantum coherence in language representation
457 let quantum_coherence = analyze_quantum_language_coherence(&logits)?;
458 println!(
459 " - Quantum coherence in representations: {:.4}",
460 quantum_coherence
461 );
462 }
463
464 Ok(())
465}
466
467/// Demonstrate sequence-to-sequence tasks
468fn seq2seq_demo() -> Result<()> {
469 println!(" Quantum sequence-to-sequence modeling...");
470
471 // Encoder configuration
472 let encoder_config = QuantumTransformerConfig {
473 model_dim: 256,
474 num_heads: 8,
475 ff_dim: 1024,
476 num_layers: 4,
477 max_seq_len: 128,
478 num_qubits: 10,
479 dropout_rate: 0.1,
480 attention_type: QuantumAttentionType::HybridQuantumClassical,
481 position_encoding: PositionEncodingType::Sinusoidal,
482 };
483
484 // Decoder configuration (with causal attention)
485 let decoder_config = QuantumTransformerConfig {
486 model_dim: 256,
487 num_heads: 8,
488 ff_dim: 1024,
489 num_layers: 4,
490 max_seq_len: 128,
491 num_qubits: 10,
492 dropout_rate: 0.1,
493 attention_type: QuantumAttentionType::QuantumEnhancedMultiHead,
494 position_encoding: PositionEncodingType::QuantumPhase,
495 };
496
497 let encoder = QuantumTransformer::new(encoder_config)?;
498 let decoder = QuantumTransformer::new(decoder_config)?;
499
500 println!(" Created encoder-decoder architecture");
501 println!(" Encoder: {} parameters", encoder.num_parameters());
502 println!(" Decoder: {} parameters", decoder.num_parameters());
503
504 // Simulate translation task
505 let batch_size = 3;
506 let src_len = 32;
507 let tgt_len = 28;
508 let model_dim = 256;
509
510 // Source sequence (e.g., English)
511 let source = Array3::from_shape_fn((batch_size, src_len, model_dim), |(b, s, d)| {
512 let src_pattern = 0.3 * ((s as f64 * 0.2 + b as f64).sin());
513 src_pattern + 0.1 * (d as f64 / model_dim as f64)
514 });
515
516 // Target sequence (e.g., French)
517 let target = Array3::from_shape_fn((batch_size, tgt_len, model_dim), |(b, s, d)| {
518 let tgt_pattern = 0.4 * ((s as f64 * 0.15 + b as f64 * 0.3).cos());
519 tgt_pattern + 0.12 * (d as f64 / model_dim as f64)
520 });
521
522 println!(
523 "\n Processing translation: {} -> {} tokens",
524 src_len, tgt_len
525 );
526
527 // Encode source sequence
528 let encoder_output = encoder.forward(&source, None)?;
529 println!(" Encoder output shape: {:?}", encoder_output.dim());
530
531 // Decode with causal mask
532 let causal_mask = create_causal_mask(batch_size, tgt_len);
533 let decoder_output = decoder.forward(&target, Some(&causal_mask))?;
534 println!(" Decoder output shape: {:?}", decoder_output.dim());
535
536 // Cross-attention simulation (simplified)
537 println!("\n Cross-attention analysis:");
538 let cross_attention_scores = compute_cross_attention(&encoder_output, &decoder_output)?;
539 println!(
540 " Cross-attention shape: {:?}",
541 cross_attention_scores.dim()
542 );
543
544 // Analyze attention alignment
545 let max_alignment = cross_attention_scores
546 .iter()
547 .cloned()
548 .fold(f64::NEG_INFINITY, f64::max);
549 let avg_alignment = cross_attention_scores.mean().unwrap_or(0.0);
550
551 println!(" Max alignment score: {:.4}", max_alignment);
552 println!(" Average alignment: {:.4}", avg_alignment);
553
554 // Translation quality metrics (simplified)
555 let translation_score = evaluate_translation_quality(&source, &target, &decoder_output)?;
556 println!(" Translation quality score: {:.4}", translation_score);
557
558 // Quantum entanglement in cross-lingual representations
559 let cross_lingual_entanglement =
560 analyze_cross_lingual_entanglement(&encoder_output, &decoder_output)?;
561 println!(
562 " Cross-lingual quantum entanglement: {:.4}",
563 cross_lingual_entanglement
564 );
565
566 Ok(())
567}
568
569/// Demonstrate quantum data processing
570fn quantum_data_demo() -> Result<()> {
571 println!(" Processing quantum measurement data with transformers...");
572
573 let config = QuantumTransformerConfig {
574 model_dim: 128,
575 num_heads: 4,
576 ff_dim: 512,
577 num_layers: 3,
578 max_seq_len: 64,
579 num_qubits: 8,
580 dropout_rate: 0.05,
581 attention_type: QuantumAttentionType::FullQuantum,
582 position_encoding: PositionEncodingType::QuantumPhase,
583 };
584
585 let transformer = QuantumTransformer::new(config)?;
586
587 // Simulate quantum measurement sequences
588 let batch_size = 5;
589 let seq_len = 32;
590 let model_dim = 128;
591
592 println!(" Generating quantum measurement sequences...");
593
594 // Create quantum state evolution data
595 let quantum_data = Array3::from_shape_fn((batch_size, seq_len, model_dim), |(b, t, d)| {
596 // Simulate quantum state evolution with decoherence
597 let decoherence_factor = (-0.1 * t as f64).exp();
598 let quantum_amplitude =
599 decoherence_factor * (2.0 * std::f64::consts::PI * t as f64 / 8.0 + b as f64).sin();
600
601 // Add measurement noise
602 let noise = 0.05 * (fastrand::f64() - 0.5);
603
604 // Encode as amplitude and phase information
605 if d % 2 == 0 {
606 quantum_amplitude + noise
607 } else {
608 (2.0 * std::f64::consts::PI * t as f64 / 10.0 + d as f64 * 0.1).cos() + noise
609 }
610 });
611
612 println!(
613 " Processing {} quantum sequences of {} measurements each",
614 batch_size, seq_len
615 );
616
617 // Process quantum data
618 let output = transformer.forward(&quantum_data, None)?;
619
620 // Analyze quantum data processing
621 println!("\n Quantum data analysis:");
622
623 // Coherence preservation
624 let input_coherence = compute_coherence_measure(&quantum_data)?;
625 let output_coherence = compute_coherence_measure(&output)?;
626 let coherence_preservation = output_coherence / input_coherence;
627
628 println!(" Input coherence: {:.4}", input_coherence);
629 println!(" Output coherence: {:.4}", output_coherence);
630 println!(
631 " Coherence preservation: {:.1}%",
632 coherence_preservation * 100.0
633 );
634
635 // Quantum information extraction
636 let quantum_features = extract_quantum_features(&output)?;
637 println!(" Extracted quantum features:");
638 println!(
639 " - Entanglement signature: {:.4}",
640 quantum_features.entanglement
641 );
642 println!(
643 " - Phase coherence: {:.4}",
644 quantum_features.phase_coherence
645 );
646 println!(
647 " - Amplitude stability: {:.4}",
648 quantum_features.amplitude_stability
649 );
650
651 // Decoherence detection
652 let decoherence_pattern = detect_decoherence_pattern(&output)?;
653 println!(" Decoherence detection:");
654 println!(" - Pattern strength: {:.4}", decoherence_pattern.strength);
655 println!(
656 " - Time constant: {:.2} steps",
657 decoherence_pattern.time_constant
658 );
659
660 // Quantum state classification
661 let state_classifications = classify_quantum_states(&output)?;
662 println!(" Quantum state classification:");
663 for (i, classification) in state_classifications.iter().enumerate() {
664 println!(
665 " - Sequence {}: {:.1}% entangled, {:.1}% coherent",
666 i,
667 classification.entangled_prob * 100.0,
668 classification.coherent_prob * 100.0
669 );
670 }
671
672 Ok(())
673}
674
675/// Demonstrate multi-scale quantum transformers
676fn multiscale_demo() -> Result<()> {
677 println!(" Multi-scale quantum transformer architecture...");
678
679 // Create transformers at different scales
680 let scales = vec![
681 (
682 "Fine-scale",
683 QuantumTransformerConfig {
684 model_dim: 128,
685 num_heads: 4,
686 ff_dim: 512,
687 num_layers: 2,
688 max_seq_len: 64,
689 num_qubits: 6,
690 dropout_rate: 0.1,
691 attention_type: QuantumAttentionType::VariationalQuantum,
692 position_encoding: PositionEncodingType::Sinusoidal,
693 },
694 ),
695 (
696 "Medium-scale",
697 QuantumTransformerConfig {
698 model_dim: 256,
699 num_heads: 8,
700 ff_dim: 1024,
701 num_layers: 4,
702 max_seq_len: 128,
703 num_qubits: 10,
704 dropout_rate: 0.1,
705 attention_type: QuantumAttentionType::HybridQuantumClassical,
706 position_encoding: PositionEncodingType::QuantumPhase,
707 },
708 ),
709 (
710 "Coarse-scale",
711 QuantumTransformerConfig {
712 model_dim: 512,
713 num_heads: 16,
714 ff_dim: 2048,
715 num_layers: 6,
716 max_seq_len: 256,
717 num_qubits: 16,
718 dropout_rate: 0.1,
719 attention_type: QuantumAttentionType::FullQuantum,
720 position_encoding: PositionEncodingType::Rotary,
721 },
722 ),
723 ];
724
725 let mut transformers = Vec::new();
726
727 for (scale_name, config) in scales {
728 let transformer = QuantumTransformer::new(config)?;
729 let num_params = transformer.num_parameters();
730
731 println!(" {} transformer: {} parameters", scale_name, num_params);
732 transformers.push((scale_name, transformer));
733 }
734
735 // Test hierarchical processing
736 println!("\n Hierarchical processing demonstration:");
737
738 let batch_size = 2;
739 let base_seq_len = 64;
740 let input_dim = 128;
741
742 // Create input data
743 let input_data = Array3::from_shape_fn((batch_size, base_seq_len, input_dim), |(b, s, d)| {
744 // Multi-scale signal with different frequency components
745 let fine_component = 0.3 * (s as f64 * 0.5).sin();
746 let medium_component = 0.2 * (s as f64 * 0.1).sin();
747 let coarse_component = 0.1 * (s as f64 * 0.02).sin();
748
749 let base_signal = fine_component + medium_component + coarse_component;
750 base_signal + 0.05 * (b as f64 + d as f64 * 0.01)
751 });
752
753 // Process at each scale
754 let mut scale_outputs = Vec::new();
755
756 for (scale_name, transformer) in &transformers {
757 // Adapt input to transformer's expected dimensions
758 let adapted_input = adapt_input_for_scale(&input_data, transformer.config())?;
759
760 println!(" Processing at {} scale...", scale_name);
761 println!(" Adapted input shape: {:?}", adapted_input.dim());
762
763 let output = transformer.forward(&adapted_input, None)?;
764
765 // Analyze scale-specific patterns
766 let pattern_analysis = analyze_scale_patterns(&output)?;
767
768 scale_outputs.push((*scale_name, output));
769 println!(" Pattern analysis:");
770 println!(
771 " - Local patterns: {:.4}",
772 pattern_analysis.local_strength
773 );
774 println!(
775 " - Global patterns: {:.4}",
776 pattern_analysis.global_strength
777 );
778 println!(
779 " - Cross-scale coherence: {:.4}",
780 pattern_analysis.coherence
781 );
782 }
783
784 // Multi-scale fusion
785 println!("\n Multi-scale fusion analysis:");
786 let scale_refs: Vec<(&str, Array3<f64>)> = scale_outputs
787 .iter()
788 .map(|(name, output)| (*name, output.clone()))
789 .collect();
790 let fusion_result = fuse_multiscale_outputs(&scale_refs)?;
791 println!(
792 " Fused representation dimensions: {} features",
793 fusion_result.len()
794 );
795
796 let fusion_quality = evaluate_fusion_quality(&fusion_result)?;
797 println!(" Fusion quality metrics:");
798 println!(
799 " - Information preservation: {:.1}%",
800 fusion_quality.info_preservation * 100.0
801 );
802 println!(
803 " - Scale consistency: {:.1}%",
804 fusion_quality.scale_consistency * 100.0
805 );
806 println!(
807 " - Quantum coherence: {:.4}",
808 fusion_quality.quantum_coherence
809 );
810
811 Ok(())
812}
Sourcepub fn config(&self) -> &QuantumTransformerConfig
pub fn config(&self) -> &QuantumTransformerConfig
Get model configuration
Examples found in repository?
examples/quantum_transformer.rs (line 758)
676fn multiscale_demo() -> Result<()> {
677 println!(" Multi-scale quantum transformer architecture...");
678
679 // Create transformers at different scales
680 let scales = vec![
681 (
682 "Fine-scale",
683 QuantumTransformerConfig {
684 model_dim: 128,
685 num_heads: 4,
686 ff_dim: 512,
687 num_layers: 2,
688 max_seq_len: 64,
689 num_qubits: 6,
690 dropout_rate: 0.1,
691 attention_type: QuantumAttentionType::VariationalQuantum,
692 position_encoding: PositionEncodingType::Sinusoidal,
693 },
694 ),
695 (
696 "Medium-scale",
697 QuantumTransformerConfig {
698 model_dim: 256,
699 num_heads: 8,
700 ff_dim: 1024,
701 num_layers: 4,
702 max_seq_len: 128,
703 num_qubits: 10,
704 dropout_rate: 0.1,
705 attention_type: QuantumAttentionType::HybridQuantumClassical,
706 position_encoding: PositionEncodingType::QuantumPhase,
707 },
708 ),
709 (
710 "Coarse-scale",
711 QuantumTransformerConfig {
712 model_dim: 512,
713 num_heads: 16,
714 ff_dim: 2048,
715 num_layers: 6,
716 max_seq_len: 256,
717 num_qubits: 16,
718 dropout_rate: 0.1,
719 attention_type: QuantumAttentionType::FullQuantum,
720 position_encoding: PositionEncodingType::Rotary,
721 },
722 ),
723 ];
724
725 let mut transformers = Vec::new();
726
727 for (scale_name, config) in scales {
728 let transformer = QuantumTransformer::new(config)?;
729 let num_params = transformer.num_parameters();
730
731 println!(" {} transformer: {} parameters", scale_name, num_params);
732 transformers.push((scale_name, transformer));
733 }
734
735 // Test hierarchical processing
736 println!("\n Hierarchical processing demonstration:");
737
738 let batch_size = 2;
739 let base_seq_len = 64;
740 let input_dim = 128;
741
742 // Create input data
743 let input_data = Array3::from_shape_fn((batch_size, base_seq_len, input_dim), |(b, s, d)| {
744 // Multi-scale signal with different frequency components
745 let fine_component = 0.3 * (s as f64 * 0.5).sin();
746 let medium_component = 0.2 * (s as f64 * 0.1).sin();
747 let coarse_component = 0.1 * (s as f64 * 0.02).sin();
748
749 let base_signal = fine_component + medium_component + coarse_component;
750 base_signal + 0.05 * (b as f64 + d as f64 * 0.01)
751 });
752
753 // Process at each scale
754 let mut scale_outputs = Vec::new();
755
756 for (scale_name, transformer) in &transformers {
757 // Adapt input to transformer's expected dimensions
758 let adapted_input = adapt_input_for_scale(&input_data, transformer.config())?;
759
760 println!(" Processing at {} scale...", scale_name);
761 println!(" Adapted input shape: {:?}", adapted_input.dim());
762
763 let output = transformer.forward(&adapted_input, None)?;
764
765 // Analyze scale-specific patterns
766 let pattern_analysis = analyze_scale_patterns(&output)?;
767
768 scale_outputs.push((*scale_name, output));
769 println!(" Pattern analysis:");
770 println!(
771 " - Local patterns: {:.4}",
772 pattern_analysis.local_strength
773 );
774 println!(
775 " - Global patterns: {:.4}",
776 pattern_analysis.global_strength
777 );
778 println!(
779 " - Cross-scale coherence: {:.4}",
780 pattern_analysis.coherence
781 );
782 }
783
784 // Multi-scale fusion
785 println!("\n Multi-scale fusion analysis:");
786 let scale_refs: Vec<(&str, Array3<f64>)> = scale_outputs
787 .iter()
788 .map(|(name, output)| (*name, output.clone()))
789 .collect();
790 let fusion_result = fuse_multiscale_outputs(&scale_refs)?;
791 println!(
792 " Fused representation dimensions: {} features",
793 fusion_result.len()
794 );
795
796 let fusion_quality = evaluate_fusion_quality(&fusion_result)?;
797 println!(" Fusion quality metrics:");
798 println!(
799 " - Information preservation: {:.1}%",
800 fusion_quality.info_preservation * 100.0
801 );
802 println!(
803 " - Scale consistency: {:.1}%",
804 fusion_quality.scale_consistency * 100.0
805 );
806 println!(
807 " - Quantum coherence: {:.4}",
808 fusion_quality.quantum_coherence
809 );
810
811 Ok(())
812}
Sourcepub fn num_parameters(&self) -> usize
pub fn num_parameters(&self) -> usize
Get number of parameters
Examples found in repository?
examples/quantum_transformer.rs (line 99)
53fn config_demo() -> Result<()> {
54 println!(" Creating various transformer configurations...");
55
56 // Small efficient model
57 let small_config = QuantumTransformerConfig::small();
58 println!(
59 " Small model: {} params, {} heads, {} layers",
60 small_config.model_dim, small_config.num_heads, small_config.num_layers
61 );
62
63 // Standard model
64 let default_config = QuantumTransformerConfig::default();
65 println!(
66 " Default model: {} params, {} heads, {} layers",
67 default_config.model_dim, default_config.num_heads, default_config.num_layers
68 );
69
70 // Large model
71 let large_config = QuantumTransformerConfig::large();
72 println!(
73 " Large model: {} params, {} heads, {} layers",
74 large_config.model_dim, large_config.num_heads, large_config.num_layers
75 );
76
77 // Custom configuration
78 let custom_config = QuantumTransformerConfig {
79 model_dim: 384,
80 num_heads: 6,
81 ff_dim: 1536,
82 num_layers: 8,
83 max_seq_len: 1024,
84 num_qubits: 12,
85 dropout_rate: 0.15,
86 attention_type: QuantumAttentionType::QuantumEnhancedMultiHead,
87 position_encoding: PositionEncodingType::Rotary,
88 };
89
90 println!(
91 " Custom model: {} dim, {} qubits, {:?} attention",
92 custom_config.model_dim, custom_config.num_qubits, custom_config.attention_type
93 );
94
95 // Create transformer with custom config
96 let transformer = QuantumTransformer::new(custom_config)?;
97 println!(
98 " Created transformer with {} total parameters",
99 transformer.num_parameters()
100 );
101
102 Ok(())
103}
104
105/// Demonstrate different quantum attention mechanisms
106fn attention_mechanisms_demo() -> Result<()> {
107 println!(" Testing various quantum attention mechanisms...");
108
109 let attention_types = vec![
110 ("Full Quantum", QuantumAttentionType::FullQuantum),
111 (
112 "Hybrid Quantum-Classical",
113 QuantumAttentionType::HybridQuantumClassical,
114 ),
115 (
116 "Variational Quantum",
117 QuantumAttentionType::VariationalQuantum,
118 ),
119 (
120 "Quantum Enhanced Multi-Head",
121 QuantumAttentionType::QuantumEnhancedMultiHead,
122 ),
123 (
124 "Quantum Self-Attention",
125 QuantumAttentionType::QuantumSelfAttention,
126 ),
127 ];
128
129 for (name, attention_type) in attention_types {
130 println!("\n --- {} Attention ---", name);
131
132 let attention = QuantumMultiHeadAttention::new(4, 256, attention_type, 8)?;
133 println!(
134 " Created attention module: {} heads, {} model dim",
135 4, 256
136 ); // Fixed values since fields are private
137
138 // Test forward pass
139 let batch_size = 2;
140 let seq_len = 10;
141 let model_dim = 256;
142
143 let query = Array3::from_shape_fn((batch_size, seq_len, model_dim), |(b, s, d)| {
144 0.1 * (b as f64 + s as f64 * 0.1 + d as f64 * 0.01)
145 });
146 let key = query.clone();
147 let value = query.clone();
148
149 let attention_output = attention.forward(&query, &key, &value, None)?;
150
151 println!(
152 " Attention output shape: {:?}",
153 attention_output.output.dim()
154 );
155 println!(
156 " Attention weights shape: {:?}",
157 attention_output.attention_weights.dim()
158 );
159
160 // Analyze quantum attention properties
161 let quantum_info = &attention_output.quantum_info;
162 let avg_entanglement = quantum_info.entanglement_matrix.mean().unwrap_or(0.0);
163 let max_coherence = quantum_info
164 .coherence_scores
165 .iter()
166 .cloned()
167 .fold(f64::NEG_INFINITY, f64::max);
168
169 println!(" Average entanglement: {:.4}", avg_entanglement);
170 println!(" Maximum coherence: {:.4}", max_coherence);
171
172 // Attention pattern analysis
173 let attention_weights = &attention_output.attention_weights;
174 let max_attention = attention_weights
175 .iter()
176 .cloned()
177 .fold(f64::NEG_INFINITY, f64::max);
178 let avg_attention = attention_weights.mean().unwrap_or(0.0);
179
180 println!(" Max attention weight: {:.4}", max_attention);
181 println!(" Average attention: {:.4}", avg_attention);
182
183 // Check attention sparsity
184 let sparsity = attention_weights.iter().filter(|&&x| x < 0.01).count() as f64
185 / attention_weights.len() as f64;
186 println!(" Attention sparsity: {:.1}%", sparsity * 100.0);
187 }
188
189 Ok(())
190}
191
192/// Demonstrate different position encoding types
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 --- {} Position Encoding ---", name);
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().cloned().fold(f64::INFINITY, f64::min);
223 let max_val = encodings.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
224 max_val - min_val
225 };
226
227 println!(" Value range: {:.4}", encoding_range);
228
229 // Check position distinguishability
230 let pos1 = encodings.slice(scirs2_core::ndarray::s![0, 0, ..]).to_owned();
231 let pos2 = encodings.slice(scirs2_core::ndarray::s![0, seq_len - 1, ..]).to_owned();
232 let position_distance = (&pos1 - &pos2).mapv(|x| x * x).sum().sqrt();
233
234 println!(
235 " Distance between first and last position: {:.4}",
236 position_distance
237 );
238
239 // Analyze periodicity for sinusoidal encodings
240 if name == "Sinusoidal" {
241 let mut periodicities = Vec::new();
242 for d in (0..model_dim).step_by(10) {
243 let values: Vec<f64> = (0..seq_len).map(|s| encodings[[0, s, d]]).collect();
244
245 // Simple periodicity check
246 let period = find_period(&values);
247 if period > 0 {
248 periodicities.push(period);
249 }
250 }
251
252 if !periodicities.is_empty() {
253 let avg_period =
254 periodicities.iter().sum::<usize>() as f64 / periodicities.len() as f64;
255 println!(" Average period length: {:.1}", avg_period);
256 }
257 }
258
259 // Check quantum phase encoding properties
260 if name == "Quantum Phase" {
261 let phase_variance = encodings.var(0.0);
262 println!(" Phase encoding variance: {:.4}", phase_variance);
263 }
264 }
265
266 Ok(())
267}
268
269/// Demonstrate complete transformer forward pass
270fn transformer_forward_demo() -> Result<()> {
271 println!(" Testing complete quantum transformer forward pass...");
272
273 let config = QuantumTransformerConfig {
274 model_dim: 256,
275 num_heads: 8,
276 ff_dim: 1024,
277 num_layers: 4,
278 max_seq_len: 128,
279 num_qubits: 10,
280 dropout_rate: 0.1,
281 attention_type: QuantumAttentionType::HybridQuantumClassical,
282 position_encoding: PositionEncodingType::QuantumPhase,
283 };
284
285 let transformer = QuantumTransformer::new(config.clone())?;
286 println!(
287 " Created transformer: {} layers, {} parameters",
288 config.num_layers,
289 transformer.num_parameters()
290 );
291
292 // Test with different sequence lengths
293 let test_sequences = vec![
294 (2, 16, 128), // small batch, short sequence
295 (4, 32, 128), // medium batch, medium sequence
296 (1, 64, 128), // single sample, long sequence
297 ];
298
299 for (batch_size, seq_len, input_dim) in test_sequences {
300 println!(
301 "\n Testing: batch={}, seq_len={}, input_dim={}",
302 batch_size, seq_len, input_dim
303 );
304
305 // Create test input
306 let input = Array3::from_shape_fn((batch_size, seq_len, input_dim), |(b, s, d)| {
307 let base = 0.1 * (b as f64 + 1.0);
308 let seq_component = 0.05 * (s as f64 * 0.1).sin();
309 let dim_component = 0.02 * (d as f64 * 0.01).cos();
310 base + seq_component + dim_component
311 });
312
313 // Create causal mask for autoregressive modeling
314 let causal_mask = create_causal_mask(batch_size, seq_len);
315
316 // Forward pass
317 let start_time = std::time::Instant::now();
318 let output = transformer.forward(&input, Some(&causal_mask))?;
319 let forward_time = start_time.elapsed();
320
321 println!(" Output shape: {:?}", output.dim());
322 println!(" Forward pass time: {:.2?}", forward_time);
323
324 // Analyze output properties
325 let output_mean = output.mean().unwrap_or(0.0);
326 let output_std = output.var(0.0).sqrt();
327 let output_range = {
328 let min_val = output.iter().cloned().fold(f64::INFINITY, f64::min);
329 let max_val = output.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
330 max_val - min_val
331 };
332
333 println!(
334 " Output statistics: mean={:.4}, std={:.4}, range={:.4}",
335 output_mean, output_std, output_range
336 );
337
338 // Check causality (if using causal mask)
339 let causality_check = check_causality(&input, &output, &causal_mask);
340 if causality_check {
341 println!(" ✓ Causal dependencies respected");
342 } else {
343 println!(" ⚠ Potential causality violations detected");
344 }
345
346 // Memory efficiency analysis
347 let memory_per_token = (transformer.num_parameters() * 8 + output.len() * 8) as f64
348 / (batch_size * seq_len) as f64;
349 println!(" Memory per token: {:.1} bytes", memory_per_token);
350 }
351
352 Ok(())
353}
354
355/// Demonstrate quantum language modeling
356fn language_modeling_demo() -> Result<()> {
357 println!(" Quantum language modeling with transformer...");
358
359 let config = QuantumTransformerConfig {
360 model_dim: 384,
361 num_heads: 6,
362 ff_dim: 1536,
363 num_layers: 6,
364 max_seq_len: 256,
365 num_qubits: 12,
366 dropout_rate: 0.1,
367 attention_type: QuantumAttentionType::QuantumSelfAttention,
368 position_encoding: PositionEncodingType::Rotary,
369 };
370
371 let transformer = QuantumTransformer::new(config.clone())?;
372
373 // Simulate language modeling task
374 let vocab_size = 1000;
375 let batch_size = 4;
376 let seq_len = 64;
377
378 // Create tokenized sequences (simulated)
379 let input_tokens =
380 Array3::from_shape_fn((batch_size, seq_len, config.model_dim), |(b, s, d)| {
381 // Simulate token embeddings
382 let token_id = (b * seq_len + s) % vocab_size;
383 let embedding_val = (token_id as f64 / vocab_size as f64) * 2.0 - 1.0;
384 embedding_val * (1.0 + 0.1 * (d as f64 / config.model_dim as f64))
385 });
386
387 println!(
388 " Processing {} sequences of length {}",
389 batch_size, seq_len
390 );
391
392 // Create causal mask for language modeling
393 let causal_mask = create_causal_mask(batch_size, seq_len);
394
395 // Forward pass
396 let logits = transformer.forward(&input_tokens, Some(&causal_mask))?;
397
398 // Simulate next token prediction
399 let mut perplexities = Vec::new();
400
401 for batch_idx in 0..batch_size {
402 let mut log_likelihood = 0.0;
403 let mut valid_predictions = 0;
404
405 for pos in 0..seq_len - 1 {
406 let current_logits = logits.slice(scirs2_core::ndarray::s![batch_idx, pos, ..]);
407
408 // Convert to probabilities (simplified softmax)
409 let max_logit = current_logits
410 .iter()
411 .cloned()
412 .fold(f64::NEG_INFINITY, f64::max);
413 let exp_logits: Array1<f64> = current_logits.mapv(|x| (x - max_logit).exp());
414 let sum_exp = exp_logits.sum();
415 let probs = exp_logits / sum_exp;
416
417 // Simulate target token (next position embedding)
418 let target_embedding = input_tokens.slice(scirs2_core::ndarray::s![batch_idx, pos + 1, ..]);
419 let target_prob = compute_token_probability(&probs, &target_embedding.to_owned())?;
420
421 if target_prob > 1e-10 {
422 log_likelihood += target_prob.ln();
423 valid_predictions += 1;
424 }
425 }
426
427 if valid_predictions > 0 {
428 let avg_log_likelihood = log_likelihood / valid_predictions as f64;
429 let perplexity = (-avg_log_likelihood).exp();
430 perplexities.push(perplexity);
431 }
432 }
433
434 if !perplexities.is_empty() {
435 let avg_perplexity = perplexities.iter().sum::<f64>() / perplexities.len() as f64;
436 println!(" Average perplexity: {:.2}", avg_perplexity);
437
438 // Analyze quantum language model properties
439 println!(" Quantum language model analysis:");
440
441 // Attention pattern analysis
442 println!(" - Uses quantum self-attention for context modeling");
443 println!(" - Rotary position encoding preserves relative positions");
444 println!(
445 " - {} layers provide hierarchical representation",
446 config.num_layers
447 );
448
449 // Information flow analysis
450 let first_layer_norm = logits.slice(scirs2_core::ndarray::s![0, .., ..]).var(0.0).sqrt();
451 println!(
452 " - Output layer standard deviation: {:.4}",
453 first_layer_norm
454 );
455
456 // Quantum coherence in language representation
457 let quantum_coherence = analyze_quantum_language_coherence(&logits)?;
458 println!(
459 " - Quantum coherence in representations: {:.4}",
460 quantum_coherence
461 );
462 }
463
464 Ok(())
465}
466
467/// Demonstrate sequence-to-sequence tasks
468fn seq2seq_demo() -> Result<()> {
469 println!(" Quantum sequence-to-sequence modeling...");
470
471 // Encoder configuration
472 let encoder_config = QuantumTransformerConfig {
473 model_dim: 256,
474 num_heads: 8,
475 ff_dim: 1024,
476 num_layers: 4,
477 max_seq_len: 128,
478 num_qubits: 10,
479 dropout_rate: 0.1,
480 attention_type: QuantumAttentionType::HybridQuantumClassical,
481 position_encoding: PositionEncodingType::Sinusoidal,
482 };
483
484 // Decoder configuration (with causal attention)
485 let decoder_config = QuantumTransformerConfig {
486 model_dim: 256,
487 num_heads: 8,
488 ff_dim: 1024,
489 num_layers: 4,
490 max_seq_len: 128,
491 num_qubits: 10,
492 dropout_rate: 0.1,
493 attention_type: QuantumAttentionType::QuantumEnhancedMultiHead,
494 position_encoding: PositionEncodingType::QuantumPhase,
495 };
496
497 let encoder = QuantumTransformer::new(encoder_config)?;
498 let decoder = QuantumTransformer::new(decoder_config)?;
499
500 println!(" Created encoder-decoder architecture");
501 println!(" Encoder: {} parameters", encoder.num_parameters());
502 println!(" Decoder: {} parameters", decoder.num_parameters());
503
504 // Simulate translation task
505 let batch_size = 3;
506 let src_len = 32;
507 let tgt_len = 28;
508 let model_dim = 256;
509
510 // Source sequence (e.g., English)
511 let source = Array3::from_shape_fn((batch_size, src_len, model_dim), |(b, s, d)| {
512 let src_pattern = 0.3 * ((s as f64 * 0.2 + b as f64).sin());
513 src_pattern + 0.1 * (d as f64 / model_dim as f64)
514 });
515
516 // Target sequence (e.g., French)
517 let target = Array3::from_shape_fn((batch_size, tgt_len, model_dim), |(b, s, d)| {
518 let tgt_pattern = 0.4 * ((s as f64 * 0.15 + b as f64 * 0.3).cos());
519 tgt_pattern + 0.12 * (d as f64 / model_dim as f64)
520 });
521
522 println!(
523 "\n Processing translation: {} -> {} tokens",
524 src_len, tgt_len
525 );
526
527 // Encode source sequence
528 let encoder_output = encoder.forward(&source, None)?;
529 println!(" Encoder output shape: {:?}", encoder_output.dim());
530
531 // Decode with causal mask
532 let causal_mask = create_causal_mask(batch_size, tgt_len);
533 let decoder_output = decoder.forward(&target, Some(&causal_mask))?;
534 println!(" Decoder output shape: {:?}", decoder_output.dim());
535
536 // Cross-attention simulation (simplified)
537 println!("\n Cross-attention analysis:");
538 let cross_attention_scores = compute_cross_attention(&encoder_output, &decoder_output)?;
539 println!(
540 " Cross-attention shape: {:?}",
541 cross_attention_scores.dim()
542 );
543
544 // Analyze attention alignment
545 let max_alignment = cross_attention_scores
546 .iter()
547 .cloned()
548 .fold(f64::NEG_INFINITY, f64::max);
549 let avg_alignment = cross_attention_scores.mean().unwrap_or(0.0);
550
551 println!(" Max alignment score: {:.4}", max_alignment);
552 println!(" Average alignment: {:.4}", avg_alignment);
553
554 // Translation quality metrics (simplified)
555 let translation_score = evaluate_translation_quality(&source, &target, &decoder_output)?;
556 println!(" Translation quality score: {:.4}", translation_score);
557
558 // Quantum entanglement in cross-lingual representations
559 let cross_lingual_entanglement =
560 analyze_cross_lingual_entanglement(&encoder_output, &decoder_output)?;
561 println!(
562 " Cross-lingual quantum entanglement: {:.4}",
563 cross_lingual_entanglement
564 );
565
566 Ok(())
567}
568
569/// Demonstrate quantum data processing
570fn quantum_data_demo() -> Result<()> {
571 println!(" Processing quantum measurement data with transformers...");
572
573 let config = QuantumTransformerConfig {
574 model_dim: 128,
575 num_heads: 4,
576 ff_dim: 512,
577 num_layers: 3,
578 max_seq_len: 64,
579 num_qubits: 8,
580 dropout_rate: 0.05,
581 attention_type: QuantumAttentionType::FullQuantum,
582 position_encoding: PositionEncodingType::QuantumPhase,
583 };
584
585 let transformer = QuantumTransformer::new(config)?;
586
587 // Simulate quantum measurement sequences
588 let batch_size = 5;
589 let seq_len = 32;
590 let model_dim = 128;
591
592 println!(" Generating quantum measurement sequences...");
593
594 // Create quantum state evolution data
595 let quantum_data = Array3::from_shape_fn((batch_size, seq_len, model_dim), |(b, t, d)| {
596 // Simulate quantum state evolution with decoherence
597 let decoherence_factor = (-0.1 * t as f64).exp();
598 let quantum_amplitude =
599 decoherence_factor * (2.0 * std::f64::consts::PI * t as f64 / 8.0 + b as f64).sin();
600
601 // Add measurement noise
602 let noise = 0.05 * (fastrand::f64() - 0.5);
603
604 // Encode as amplitude and phase information
605 if d % 2 == 0 {
606 quantum_amplitude + noise
607 } else {
608 (2.0 * std::f64::consts::PI * t as f64 / 10.0 + d as f64 * 0.1).cos() + noise
609 }
610 });
611
612 println!(
613 " Processing {} quantum sequences of {} measurements each",
614 batch_size, seq_len
615 );
616
617 // Process quantum data
618 let output = transformer.forward(&quantum_data, None)?;
619
620 // Analyze quantum data processing
621 println!("\n Quantum data analysis:");
622
623 // Coherence preservation
624 let input_coherence = compute_coherence_measure(&quantum_data)?;
625 let output_coherence = compute_coherence_measure(&output)?;
626 let coherence_preservation = output_coherence / input_coherence;
627
628 println!(" Input coherence: {:.4}", input_coherence);
629 println!(" Output coherence: {:.4}", output_coherence);
630 println!(
631 " Coherence preservation: {:.1}%",
632 coherence_preservation * 100.0
633 );
634
635 // Quantum information extraction
636 let quantum_features = extract_quantum_features(&output)?;
637 println!(" Extracted quantum features:");
638 println!(
639 " - Entanglement signature: {:.4}",
640 quantum_features.entanglement
641 );
642 println!(
643 " - Phase coherence: {:.4}",
644 quantum_features.phase_coherence
645 );
646 println!(
647 " - Amplitude stability: {:.4}",
648 quantum_features.amplitude_stability
649 );
650
651 // Decoherence detection
652 let decoherence_pattern = detect_decoherence_pattern(&output)?;
653 println!(" Decoherence detection:");
654 println!(" - Pattern strength: {:.4}", decoherence_pattern.strength);
655 println!(
656 " - Time constant: {:.2} steps",
657 decoherence_pattern.time_constant
658 );
659
660 // Quantum state classification
661 let state_classifications = classify_quantum_states(&output)?;
662 println!(" Quantum state classification:");
663 for (i, classification) in state_classifications.iter().enumerate() {
664 println!(
665 " - Sequence {}: {:.1}% entangled, {:.1}% coherent",
666 i,
667 classification.entangled_prob * 100.0,
668 classification.coherent_prob * 100.0
669 );
670 }
671
672 Ok(())
673}
674
675/// Demonstrate multi-scale quantum transformers
676fn multiscale_demo() -> Result<()> {
677 println!(" Multi-scale quantum transformer architecture...");
678
679 // Create transformers at different scales
680 let scales = vec![
681 (
682 "Fine-scale",
683 QuantumTransformerConfig {
684 model_dim: 128,
685 num_heads: 4,
686 ff_dim: 512,
687 num_layers: 2,
688 max_seq_len: 64,
689 num_qubits: 6,
690 dropout_rate: 0.1,
691 attention_type: QuantumAttentionType::VariationalQuantum,
692 position_encoding: PositionEncodingType::Sinusoidal,
693 },
694 ),
695 (
696 "Medium-scale",
697 QuantumTransformerConfig {
698 model_dim: 256,
699 num_heads: 8,
700 ff_dim: 1024,
701 num_layers: 4,
702 max_seq_len: 128,
703 num_qubits: 10,
704 dropout_rate: 0.1,
705 attention_type: QuantumAttentionType::HybridQuantumClassical,
706 position_encoding: PositionEncodingType::QuantumPhase,
707 },
708 ),
709 (
710 "Coarse-scale",
711 QuantumTransformerConfig {
712 model_dim: 512,
713 num_heads: 16,
714 ff_dim: 2048,
715 num_layers: 6,
716 max_seq_len: 256,
717 num_qubits: 16,
718 dropout_rate: 0.1,
719 attention_type: QuantumAttentionType::FullQuantum,
720 position_encoding: PositionEncodingType::Rotary,
721 },
722 ),
723 ];
724
725 let mut transformers = Vec::new();
726
727 for (scale_name, config) in scales {
728 let transformer = QuantumTransformer::new(config)?;
729 let num_params = transformer.num_parameters();
730
731 println!(" {} transformer: {} parameters", scale_name, num_params);
732 transformers.push((scale_name, transformer));
733 }
734
735 // Test hierarchical processing
736 println!("\n Hierarchical processing demonstration:");
737
738 let batch_size = 2;
739 let base_seq_len = 64;
740 let input_dim = 128;
741
742 // Create input data
743 let input_data = Array3::from_shape_fn((batch_size, base_seq_len, input_dim), |(b, s, d)| {
744 // Multi-scale signal with different frequency components
745 let fine_component = 0.3 * (s as f64 * 0.5).sin();
746 let medium_component = 0.2 * (s as f64 * 0.1).sin();
747 let coarse_component = 0.1 * (s as f64 * 0.02).sin();
748
749 let base_signal = fine_component + medium_component + coarse_component;
750 base_signal + 0.05 * (b as f64 + d as f64 * 0.01)
751 });
752
753 // Process at each scale
754 let mut scale_outputs = Vec::new();
755
756 for (scale_name, transformer) in &transformers {
757 // Adapt input to transformer's expected dimensions
758 let adapted_input = adapt_input_for_scale(&input_data, transformer.config())?;
759
760 println!(" Processing at {} scale...", scale_name);
761 println!(" Adapted input shape: {:?}", adapted_input.dim());
762
763 let output = transformer.forward(&adapted_input, None)?;
764
765 // Analyze scale-specific patterns
766 let pattern_analysis = analyze_scale_patterns(&output)?;
767
768 scale_outputs.push((*scale_name, output));
769 println!(" Pattern analysis:");
770 println!(
771 " - Local patterns: {:.4}",
772 pattern_analysis.local_strength
773 );
774 println!(
775 " - Global patterns: {:.4}",
776 pattern_analysis.global_strength
777 );
778 println!(
779 " - Cross-scale coherence: {:.4}",
780 pattern_analysis.coherence
781 );
782 }
783
784 // Multi-scale fusion
785 println!("\n Multi-scale fusion analysis:");
786 let scale_refs: Vec<(&str, Array3<f64>)> = scale_outputs
787 .iter()
788 .map(|(name, output)| (*name, output.clone()))
789 .collect();
790 let fusion_result = fuse_multiscale_outputs(&scale_refs)?;
791 println!(
792 " Fused representation dimensions: {} features",
793 fusion_result.len()
794 );
795
796 let fusion_quality = evaluate_fusion_quality(&fusion_result)?;
797 println!(" Fusion quality metrics:");
798 println!(
799 " - Information preservation: {:.1}%",
800 fusion_quality.info_preservation * 100.0
801 );
802 println!(
803 " - Scale consistency: {:.1}%",
804 fusion_quality.scale_consistency * 100.0
805 );
806 println!(
807 " - Quantum coherence: {:.4}",
808 fusion_quality.quantum_coherence
809 );
810
811 Ok(())
812}
Trait Implementations§
Source§impl Clone for QuantumTransformer
impl Clone for QuantumTransformer
Source§fn clone(&self) -> QuantumTransformer
fn clone(&self) -> QuantumTransformer
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 QuantumTransformer
impl !RefUnwindSafe for QuantumTransformer
impl Send for QuantumTransformer
impl Sync for QuantumTransformer
impl Unpin for QuantumTransformer
impl !UnwindSafe for QuantumTransformer
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.